Programs & Examples On #Pnrp

"ImportError: no module named 'requests'" after installing with pip

if it works when you do :

python
>>> import requests

then it might be a mismatch between a previous version of python on your computer and the one you are trying to use

in that case : check the location of your working python:

which python And get sure it is matching the first line in your python code

#!<path_from_which_python_command>

Disabling the long-running-script message in Internet Explorer

In my case, while playing video, I needed to call a function everytime currentTime of video updates. So I used timeupdate event of video and I came to know that it was fired at least 4 times a second (depends on the browser you use, see this). So I changed it to call a function every second like this:

var currentIntTime = 0;

var someFunction = function() {
    currentIntTime++;
    // Do something here
} 
vidEl.on('timeupdate', function(){
    if(parseInt(vidEl.currentTime) > currentIntTime) {
        someFunction();
    }
});

This reduces calls to someFunc by at least 1/3 and it may help your browser to behave normally. It did for me !!!

Resource from src/main/resources not found after building with maven

The resources you put in src/main/resources will be copied during the build process to target/classes which can be accessed using:

...this.getClass().getResourceAsStream("/config.txt");

Laravel $q->where() between dates

You can chain your wheres directly, without function(q). There's also a nice date handling package in laravel, called Carbon. So you could do something like:

$projects = Project::where('recur_at', '>', Carbon::now())
    ->where('recur_at', '<', Carbon::now()->addWeek())
    ->where('status', '<', 5)
    ->where('recur_cancelled', '=', 0)
    ->get();

Just make sure you require Carbon in composer and you're using Carbon namespace (use Carbon\Carbon;) and it should work.

EDIT: As Joel said, you could do:

$projects = Project::whereBetween('recur_at', array(Carbon::now(), Carbon::now()->addWeek()))
    ->where('status', '<', 5)
    ->where('recur_cancelled', '=', 0)
    ->get();

HTML tag <a> want to add both href and onclick working

Use jQuery. You need to capture the click event and then go on to the website.

_x000D_
_x000D_
$("#myHref").on('click', function() {_x000D_
  alert("inside onclick");_x000D_
  window.location = "http://www.google.com";_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="#" id="myHref">Click me</a>
_x000D_
_x000D_
_x000D_

How to uncheck a checkbox in pure JavaScript?

There is another way to do this:

//elem - get the checkbox element and then
elem.setAttribute('checked', 'checked'); //check
elem.removeAttribute('checked'); //uncheck

Disable vertical scroll bar on div overflow: auto

These two CSS properties can be used to hide the scrollbars:

overflow-y: hidden; // hide vertical
overflow-x: hidden; // hide horizontal

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:

tripDetailsCollection.AddRange(tripDetails);

What is the difference between XML and XSD?

Basically an XSD file defines how the XML file is going to look like. It's a Schema file which defines the structure of the XML file. So it specifies what the possible fields are and what size they are going to be.

An XML file is an instance of XSD as it uses the rules defined in the XSD.

open a url on click of ok button in android

On Button click event write this:

Uri uri = Uri.parse("http://www.google.com"); // missing 'http://' will cause crashed
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);

that open the your URL.

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

Bootstrap sets the height of the navbar automatically to 50px. The padding above and below links is set to 15px. I think that bootstrap is adding padding to your logo.

You can either remove some of the padding above and below your logo or you can add more padding above and below links.

Adding more padding should look something like this:

nav.navbar-inverse>li>a {
 padding-top: 25px;
 padding-bottom: 25px;
}

Is there an XSL "contains" directive?

Sure there is! For instance:

<xsl:if test="not(contains($hhref, '1234'))">
  <li>
    <a href="{$hhref}" title="{$pdate}">
      <xsl:value-of select="title"/>
    </a>
  </li>
</xsl:if>

The syntax is: contains(stringToSearchWithin, stringToSearchFor)

How can I read Chrome Cache files?

I've made short stupid script which extracts JPG and PNG files:

#!/usr/bin/php
<?php
 $dir="/home/user/.cache/chromium/Default/Cache/";//Chrome or chromium cache folder. 
 $ppl="/home/user/Desktop/temporary/"; // Place for extracted files 

 $list=scandir($dir);
 foreach ($list as $filename)
 {

 if (is_file($dir.$filename))
    {
        $cont=file_get_contents($dir.$filename);
        if  (strstr($cont,'JFIF'))
        {
            echo ($filename."  JPEG \n");
            $start=(strpos($cont,"JFIF",0)-6);
            $end=strpos($cont,"HTTP/1.1 200 OK",0);
            $cont=substr($cont,$start,$end-6);
            $wholename=$ppl.$filename.".jpg";
            file_put_contents($wholename,$cont);
            echo("Saving :".$wholename." \n" );


                }
        elseif  (strstr($cont,"\211PNG"))
        {
            echo ($filename."  PNG \n");
            $start=(strpos($cont,"PNG",0)-1);
            $end=strpos($cont,"HTTP/1.1 200 OK",0);
            $cont=substr($cont,$start,$end-1);
            $wholename=$ppl.$filename.".png";
            file_put_contents($wholename,$cont);
            echo("Saving :".$wholename." \n" );


                }
        else
        {
            echo ($filename."  UNKNOWN \n");
        }
    }
 }
?>

How to fix error "Updating Maven Project". Unsupported IClasspathEntry kind=4?

Before importing the project, it should be converted into eclipse project mvn eclipse: eclipse Then i found the following error. An internal error occurred during: "Importing Maven projects".Unsupported IClasspathEntry kind=4

Where is the value kind = "var" that M2E does not recognize and therefore throws the error.

Now type this. mvn eclipse: clean

Now refresh the project in eclipse or re-import.

Get latitude and longitude automatically using php, API

I think allow_url_fopen on your apache server is disabled. you need to trun it on.

kindly change allow_url_fopen = 0 to allow_url_fopen = 1

Don't forget to restart your Apache server after changing it.

How to get the nvidia driver version from the command line?

Windows version:

cd \Program Files\NVIDIA Corporation\NVSMI

nvidia-smi

vuetify center items into v-flex

v-flex does not have a display flex! Inspect v-flex in your browser and you will find out it is just a simple block div.

So, you should override it with display: flex in your HTML or CSS to make it work with justify-content.

How can you print a variable name in python?

For the revised question of how to read in configuration parameters, I'd strongly recommend saving yourself some time and effort and use ConfigParser or (my preferred tool) ConfigObj.

They can do everything you need, they're easy to use, and someone else has already worried about how to get them to work properly!

How can I add the new "Floating Action Button" between two widgets/layouts

Keep it Simple Adding Floating Action Button using TextView by giving rounded xml background. - Add compile com.android.support:design:23.1.1 to gradle file

  • Use CoordinatorLayout as root view.
  • Before Ending the CoordinatorLayout introduce a textView.
  • Inside Drawable draw a circle.

Circle Xml is

<?xml version="1.0" encoding="utf-8"?>
<shape
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">

    <solid
        android:color="@color/colorPrimary"/>
    <size
        android:width="30dp"
        android:height="30dp"/>
</shape>

Layout xml is

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:weightSum="5"
    >

    <RelativeLayout
        android:id="@+id/viewA"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="1.6"
        android:background="@drawable/contact_bg"
        android:gravity="center_horizontal|center_vertical"
        >
        </RelativeLayout>

    <LinearLayout
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="3.4"
        android:orientation="vertical"
        android:padding="16dp"
        android:weightSum="10"
        >

        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            >
            </LinearLayout>

        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:weightSum="4"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:text="Name"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            <TextView
                android:id="@+id/name"
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:text="Ritesh Kumar Singh"
                android:singleLine="true"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            </LinearLayout>



        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:weightSum="4"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:text="Phone"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            <TextView
                android:id="@+id/number"
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:text="8283001122"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:singleLine="true"
                android:padding="3dp"
                />

        </LinearLayout>



        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:weightSum="4"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:text="Email"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:text="[email protected]"
                android:textSize="22dp"
                android:singleLine="true"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

        </LinearLayout>


        <LinearLayout
            android:layout_height="0dp"
            android:layout_width="match_parent"
            android:layout_weight="1"
            android:weightSum="4"
            android:orientation="horizontal"
            >
            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="1"
                android:text="City"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:padding="3dp"
                />

            <TextView
                android:layout_height="match_parent"
                android:layout_width="0dp"
                android:layout_weight="3"
                android:text="Panchkula"
                android:textSize="22dp"
                android:textColor="@android:color/black"
                android:singleLine="true"
                android:padding="3dp"
                />

        </LinearLayout>

    </LinearLayout>

</LinearLayout>


    <TextView
        android:id="@+id/floating"
        android:transitionName="@string/transition_name_circle"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_margin="16dp"
        android:clickable="false"
        android:background="@drawable/circle"
        android:elevation="10dp"
        android:text="R"
        android:textSize="40dp"
        android:gravity="center"
        android:textColor="@android:color/black"
        app:layout_anchor="@id/viewA"
        app:layout_anchorGravity="bottom"/>

        </android.support.design.widget.CoordinatorLayout>

Click here to se how it Will look like

REST vs JSON-RPC?

I have explored the issue in some detail and decided that pure REST is way too limiting, and RPC is best, even though most of my apps are CRUD apps. If you stick to REST, you eventually are going to be scratching your head wondering how you can easily add another needed method to your API for some special purpose. In many cases, the only way to do that with REST is to create another controller for it, which may unduly complicate your program.

If you decide on RPC, the only difference is that you are explicitly specifying the verb as part of the URI, which is clear, consistent, less buggy, and really no trouble. Especially if you create an app that goes way beyond simple CRUD, RPC is the only way to go. I have another issue with RESTful purists: HTTP POST, GET, PUT, DELETE have definite meanings in HTTP which have been subverted by REST into meaning other things, simply because they fit most of the time - but not all of the time.

In programming, I have long ago found that trying to use one thing to mean two things is going to come around sometime and bite you. I like to have the ability to use POST for just about every action, because it provides the freedom to send and receive data as your method needs to do. You can't fit the whole world into CRUD.

How to modify a specified commit?

Automated interactive rebase edit followed by commit revert ready for a do-over

I found myself fixing a past commit frequently enough that I wrote a script for it.

Here's the workflow:

  1. git commit-edit <commit-hash>
    

    This will drop you at the commit you want to edit.

  2. Fix and stage the commit as you wish it had been in the first place.

    (You may want to use git stash save to keep any files you're not committing)

  3. Redo the commit with --amend, eg:

    git commit --amend
    
  4. Complete the rebase:

    git rebase --continue
    

For the above to work, put the below script into an executable file called git-commit-edit somewhere in your $PATH:

#!/bin/bash

set -euo pipefail

script_name=${0##*/}

warn () { printf '%s: %s\n' "$script_name" "$*" >&2; }
die () { warn "$@"; exit 1; }

[[ $# -ge 2 ]] && die "Expected single commit to edit. Defaults to HEAD~"

# Default to editing the parent of the most recent commit
# The most recent commit can be edited with `git commit --amend`
commit=$(git rev-parse --short "${1:-HEAD~}")
message=$(git log -1 --format='%h %s' "$commit")

if [[ $OSTYPE =~ ^darwin ]]; then
  sed_inplace=(sed -Ei "")
else
  sed_inplace=(sed -Ei)
fi

export GIT_SEQUENCE_EDITOR="${sed_inplace[*]} "' "s/^pick ('"$commit"' .*)/edit \\1/"'
git rebase --quiet --interactive --autostash --autosquash "$commit"~
git reset --quiet @~ "$(git rev-parse --show-toplevel)"  # Reset the cache of the toplevel directory to the previous commit
git commit --quiet --amend --no-edit --allow-empty  #  Commit an empty commit so that that cache diffs are un-reversed

echo
echo "Editing commit: $message" >&2
echo

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

I you only want to apply the change only for one field, you could try serializing the field

class MyModel < ActiveRecord::Base
  serialize :content

  attr_accessible :content, :title
end

Run function from the command line

We can write something like this. I have used with python-3.7.x

import sys

def print_fn():
    print("Hi")

def sum_fn(a, b):
    print(a + b)

if __name__ == "__main__":
    args = sys.argv
    # args[0] = current file
    # args[1] = function name
    # args[2:] = function args : (*unpacked)
    globals()[args[1]](*args[2:])

python demo.py print_fn
python demo.py sum_fn 5 8

How to create a jar with external libraries included in Eclipse?

Personally,

None of the answers above worked for me, I still kept getting NoClassDefFound errors (I am using Maven for dependencies). My solution was to build using "mvn clean install" and use the "[project]-jar-with-dependencies.jar" that that command creates. Similarly in Eclipse you can right click the project -> Run As -> Maven Install and it will place the jars in the target folder.

How to use particular CSS styles based on screen size / device

Detection is automatic. You must specify what css can be used for each screen resolution:

/* for all screens, use 14px font size */
body {  
    font-size: 14px;    
}
/* responsive, form small screens, use 13px font size */
@media (max-width: 479px) {
    body {
        font-size: 13px;
    }
}

Parse XML using JavaScript

The following will parse an XML string into an XML document in all major browsers, including Internet Explorer 6. Once you have that, you can use the usual DOM traversal methods/properties such as childNodes and getElementsByTagName() to get the nodes you want.

var parseXml;
if (typeof window.DOMParser != "undefined") {
    parseXml = function(xmlStr) {
        return ( new window.DOMParser() ).parseFromString(xmlStr, "text/xml");
    };
} else if (typeof window.ActiveXObject != "undefined" &&
       new window.ActiveXObject("Microsoft.XMLDOM")) {
    parseXml = function(xmlStr) {
        var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
        xmlDoc.async = "false";
        xmlDoc.loadXML(xmlStr);
        return xmlDoc;
    };
} else {
    throw new Error("No XML parser found");
}

Example usage:

var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);

Which I got from https://stackoverflow.com/a/8412989/1232175.

How to get last 7 days data from current datetime to last 7 days in sql server

If you want to do it using Pentaho DI, you can use "Modified JavaScript" Step and write the below function:

dateAdd(d1, "d", -7);  // d1 is the current date and "d" is the date identifier

Check the image below: [Assuming current date is : 22 December 2014]

enter image description here

Hope it helps :)

Pass Hidden parameters using response.sendRedirect()

Generally, you cannot send a POST request using sendRedirect() method. You can use RequestDispatcher to forward() requests with parameters within the same web application, same context.

RequestDispatcher dispatcher = servletContext().getRequestDispatcher("test.jsp");
dispatcher.forward(request, response);

The HTTP spec states that all redirects must be in the form of a GET (or HEAD). You can consider encrypting your query string parameters if security is an issue. Another way is you can POST to the target by having a hidden form with method POST and submitting it with javascript when the page is loaded.

NameError: global name 'xrange' is not defined in Python 3

add xrange=range in your code :) It works to me.

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

So upon finding that there could be a missing package in the buildpath, thus the red x against the main project, to remove this:

1) go into "Configure Buildpath" of project 2) Java Build Path -> Source Tab - you should see the red x against the missing package/file. if it no longer exists, just "remove" it.

red X begone! :)

Change UITableView height dynamically

There isn't a system feature to change the height of the table based upon the contents of the tableview. Having said that, it is possible to programmatically change the height of the tableview based upon the contents, specifically based upon the contentSize of the tableview (which is easier than manually calculating the height yourself). A few of the particulars vary depending upon whether you're using the new autolayout that's part of iOS 6, or not.

But assuming you're configuring your table view's underlying model in viewDidLoad, if you want to then adjust the height of the tableview, you can do this in viewDidAppear:

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    [self adjustHeightOfTableview];
}

Likewise, if you ever perform a reloadData (or otherwise add or remove rows) for a tableview, you'd want to make sure that you also manually call adjustHeightOfTableView there, too, e.g.:

- (IBAction)onPressButton:(id)sender
{
    [self buildModel];
    [self.tableView reloadData];

    [self adjustHeightOfTableview];
}

So the question is what should our adjustHeightOfTableview do. Unfortunately, this is a function of whether you use the iOS 6 autolayout or not. You can determine if you have autolayout turned on by opening your storyboard or NIB and go to the "File Inspector" (e.g. press option+command+1 or click on that first tab on the panel on the right):

enter image description here

Let's assume for a second that autolayout was off. In that case, it's quite simple and adjustHeightOfTableview would just adjust the frame of the tableview:

- (void)adjustHeightOfTableview
{
    CGFloat height = self.tableView.contentSize.height;
    CGFloat maxHeight = self.tableView.superview.frame.size.height - self.tableView.frame.origin.y;

    // if the height of the content is greater than the maxHeight of
    // total space on the screen, limit the height to the size of the
    // superview.

    if (height > maxHeight)
        height = maxHeight;

    // now set the frame accordingly

    [UIView animateWithDuration:0.25 animations:^{
        CGRect frame = self.tableView.frame;
        frame.size.height = height;
        self.tableView.frame = frame;

        // if you have other controls that should be resized/moved to accommodate
        // the resized tableview, do that here, too
    }];
}

If your autolayout was on, though, adjustHeightOfTableview would adjust a height constraint for your tableview:

- (void)adjustHeightOfTableview
{
    CGFloat height = self.tableView.contentSize.height;
    CGFloat maxHeight = self.tableView.superview.frame.size.height - self.tableView.frame.origin.y;

    // if the height of the content is greater than the maxHeight of
    // total space on the screen, limit the height to the size of the
    // superview.

    if (height > maxHeight)
        height = maxHeight;

    // now set the height constraint accordingly

    [UIView animateWithDuration:0.25 animations:^{
        self.tableViewHeightConstraint.constant = height;
        [self.view setNeedsUpdateConstraints];
    }];
}

For this latter constraint-based solution to work with autolayout, we must take care of a few things first:

  1. Make sure your tableview has a height constraint by clicking on the center button in the group of buttons here and then choose to add the height constraint:

    add height constraint

  2. Then add an IBOutlet for that constraint:

    add IBOutlet

  3. Make sure you adjust other constraints so they don't conflict if you adjust the size tableview programmatically. In my example, the tableview had a trailing space constraint that locked it to the bottom of the screen, so I had to adjust that constraint so that rather than being locked at a particular size, it could be greater or equal to a value, and with a lower priority, so that the height and top of the tableview would rule the day:

    adjust other constraints

    What you do here with other constraints will depend entirely upon what other controls you have on your screen below the tableview. As always, dealing with constraints is a little awkward, but it definitely works, though the specifics in your situation depend entirely upon what else you have on the scene. But hopefully you get the idea. Bottom line, with autolayout, make sure to adjust your other constraints (if any) to be flexible to account for the changing tableview height.

As you can see, it's much easier to programmatically adjust the height of a tableview if you're not using autolayout, but in case you are, I present both alternatives.

ReactJS: "Uncaught SyntaxError: Unexpected token <"

Add type="text/babel" as an attribute of the script tag, like this:

<script type="text/babel" src="./lander.js"></script>

Get the selected option id with jQuery

Th easiest way to this is var id = $(this).val(); from inside an event like on change.

SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?

A cross join produces a cartesian product between the two tables, returning all possible combinations of all rows. It has no on clause because you're just joining everything to everything.

A full outer join is a combination of a left outer and right outer join. It returns all rows in both tables that match the query's where clause, and in cases where the on condition can't be satisfied for those rows it puts null values in for the unpopulated fields.

This wikipedia article explains the various types of joins with examples of output given a sample set of tables.

pull out p-values and r-squared from a linear regression

Another option is to use the cor.test function, instead of lm:

> x <- c(44.4, 45.9, 41.9, 53.3, 44.7, 44.1, 50.7, 45.2, 60.1)
> y <- c( 2.6,  3.1,  2.5,  5.0,  3.6,  4.0,  5.2,  2.8,  3.8)

> mycor = cor.test(x,y)
> mylm = lm(x~y)

# r and rsquared:
> cor.test(x,y)$estimate ** 2
      cor 
0.3262484 
> summary(lm(x~y))$r.squared
[1] 0.3262484

# P.value 

> lmp(lm(x~y))  # Using the lmp function defined in Chase's answer
[1] 0.1081731
> cor.test(x,y)$p.value
[1] 0.1081731

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is static inside the Program class. You can't call an instance method from inside a static method, which is why you're getting the error.

To fix it you just need to make your GetRandomBits() method static as well.

Evaluating string "3*(4+2)" yield int 18

You could fairly easily run this through the CSharpCodeProvider with suitable fluff wrapping it (a type and a method, basically). Likewise you could go through VB etc - or JavaScript, as another answer has suggested. I don't know of anything else built into the framework at this point.

I'd expect that .NET 4.0 with its support for dynamic languages may well have better capabilities on this front.

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

Oops, I just posted a dupe of this question...

The answer is, there is no built in function like Oracle's Greatest, but you can achieve a similar result for 2 columns with a UDF, note, the use of sql_variant is quite important here.

create table #t (a int, b int) 

insert #t
select 1,2 union all 
select 3,4 union all
select 5,2

-- option 1 - A case statement
select case when a > b then a else b end
from #t

-- option 2 - A union statement 
select a from #t where a >= b 
union all 
select b from #t where b > a 

-- option 3 - A udf
create function dbo.GREATEST
( 
    @a as sql_variant,
    @b as sql_variant
)
returns sql_variant
begin   
    declare @max sql_variant 
    if @a is null or @b is null return null
    if @b > @a return @b  
    return @a 
end


select dbo.GREATEST(a,b)
from #t

kristof

Posted this answer:

create table #t (id int IDENTITY(1,1), a int, b int)
insert #t
select 1,2 union all
select 3,4 union all
select 5,2

select id, max(val)
from #t
    unpivot (val for col in (a, b)) as unpvt
group by id

How to read keyboard-input?

It seems that you are mixing different Pythons here (Python 2.x vs. Python 3.x)... This is basically correct:

nb = input('Choose a number: ')

The problem is that it is only supported in Python 3. As @sharpner answered, for older versions of Python (2.x), you have to use the function raw_input:

nb = raw_input('Choose a number: ')

If you want to convert that to a number, then you should try:

number = int(nb)

... though you need to take into account that this can raise an exception:

try:
    number = int(nb)
except ValueError:
    print("Invalid number")

And if you want to print the number using formatting, in Python 3 str.format() is recommended:

print("Number: {0}\n".format(number))

Instead of:

print('Number %s \n' % (nb))

But both options (str.format() and %) do work in both Python 2.7 and Python 3.

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

Counting words in string

There may be a more efficient way to do this, but this is what has worked for me.

function countWords(passedString){
  passedString = passedString.replace(/(^\s*)|(\s*$)/gi, '');
  passedString = passedString.replace(/\s\s+/g, ' '); 
  passedString = passedString.replace(/,/g, ' ');  
  passedString = passedString.replace(/;/g, ' ');
  passedString = passedString.replace(/\//g, ' ');  
  passedString = passedString.replace(/\\/g, ' ');  
  passedString = passedString.replace(/{/g, ' ');
  passedString = passedString.replace(/}/g, ' ');
  passedString = passedString.replace(/\n/g, ' ');  
  passedString = passedString.replace(/\./g, ' '); 
  passedString = passedString.replace(/[\{\}]/g, ' ');
  passedString = passedString.replace(/[\(\)]/g, ' ');
  passedString = passedString.replace(/[[\]]/g, ' ');
  passedString = passedString.replace(/[ ]{2,}/gi, ' ');
  var countWordsBySpaces = passedString.split(' ').length; 
  return countWordsBySpaces;

}

its able to recognise all of the following as separate words:

abc,abc = 2 words,
abc/abc/abc = 3 words (works with forward and backward slashes),
abc.abc = 2 words,
abc[abc]abc = 3 words,
abc;abc = 2 words,

(some other suggestions I've tried count each example above as only 1 x word) it also:

  • ignores all leading and trailing white spaces

  • counts a single-letter followed by a new line, as a word - which I've found some of the suggestions given on this page don't count, for example:
    a
    a
    a
    a
    a
    sometimes gets counted as 0 x words, and other functions only count it as 1 x word, instead of 5 x words)

if anyone has any ideas on how to improve it, or cleaner / more efficient - then please add you 2 cents! Hope This Helps Someone out.

Setting up foreign keys in phpMyAdmin?

First set Storage Engine as InnoDB

First set Storage Engine as InnoDB

then the relation view option enable in structure menu

then the relation view option enable

In Objective-C, how do I test the object type?

You would probably use

- (BOOL)isKindOfClass:(Class)aClass

This is a method of NSObject.

For more info check the NSObject documentation.

This is how you use this.

BOOL test = [self isKindOfClass:[SomeClass class]];

You might also try doing somthing like this

for(id element in myArray)
{
    NSLog(@"=======================================");
    NSLog(@"Is of type: %@", [element className]);
    NSLog(@"Is of type NSString?: %@", ([[element className] isMemberOfClass:[NSString class]])? @"Yes" : @"No");
    NSLog(@"Is a kind of NSString: %@", ([[element classForCoder] isSubclassOfClass:[NSString class]])? @"Yes" : @"No");    
}

Oracle - How to create a readonly user

A user in an Oracle database only has the privileges you grant. So you can create a read-only user by simply not granting any other privileges.

When you create a user

CREATE USER ro_user
 IDENTIFIED BY ro_user
 DEFAULT TABLESPACE users
 TEMPORARY TABLESPACE temp;

the user doesn't even have permission to log in to the database. You can grant that

GRANT CREATE SESSION to ro_user

and then you can go about granting whatever read privileges you want. For example, if you want RO_USER to be able to query SCHEMA_NAME.TABLE_NAME, you would do something like

GRANT SELECT ON schema_name.table_name TO ro_user

Generally, you're better off creating a role, however, and granting the object privileges to the role so that you can then grant the role to different users. Something like

Create the role

CREATE ROLE ro_role;

Grant the role SELECT access on every table in a particular schema

BEGIN
  FOR x IN (SELECT * FROM dba_tables WHERE owner='SCHEMA_NAME')
  LOOP
    EXECUTE IMMEDIATE 'GRANT SELECT ON schema_name.' || x.table_name || 
                                  ' TO ro_role';
  END LOOP;
END;

And then grant the role to the user

GRANT ro_role TO ro_user;

Excel VBA Open a Folder

If you want to open a windows file explorer, you should call explorer.exe

Call Shell("explorer.exe" & " " & "P:\Engineering", vbNormalFocus)

Equivalent syxntax

Shell "explorer.exe" & " " & "P:\Engineering", vbNormalFocus

How do I clone a generic List in Java?

To clone a generic interface like java.util.List you will just need to cast it. here you are an example:

List list = new ArrayList();
List list2 = ((List) ( (ArrayList) list).clone());

It is a bit tricky, but it works, if you are limited to return a List interface, so anyone after you can implement your list whenever he wants.

I know this answer is close to the final answer, but my answer answers how to do all of that while you are working with List -the generic parent- not ArrayList

Custom Date/Time formatting in SQL Server

You're going to need DATEPART here. You can concatenate the results of the DATEPART calls together.

To get the month abbreviations, you might be able to use DATENAME; if that doesn't work for you, you can use a CASE statement on the DATEPART.

DATEPART also works for the time field.

I can think of a couple of ways of getting the AM/PM indicator, including comparing new dates built via DATEPART or calculating the total seconds elapsed in the day and comparing that to known AM/PM thresholds.

Error in model.frame.default: variable lengths differ

Another thing that can cause this error is creating a model with the centering/scaling standardize function from the arm package -- m <- standardize(lm(y ~ x, data = train))

If you then try predict(m), you get the same error as in this question.

no operator "<<" matches these operands

You're not including the standard <string> header.

You got [un]lucky that some of its pertinent definitions were accidentally made available by the other standard headers that you did include ... but operator<< was not.

How do I set headers using python's urllib?

adding HTTP headers using urllib2:

from the docs:

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
resp = urllib2.urlopen(req)
content = resp.read()

How do I specify the exit code of a console application in .NET?

My 2 cents:

You can find the system error codes here: https://msdn.microsoft.com/en-us/library/windows/desktop/ms681382(v=vs.85).aspx

You will find the typical codes like 2 for "file not found" or 5 for "access denied".

And when you stumble on an unknown code, you can use this command to find out what it means:

net helpmsg decimal_code

e.g.

net helpmsg 1

returns

Incorrect function

Cannot deserialize the current JSON array (e.g. [1,2,3]) into type

HttpClient webClient = new HttpClient();
Uri uri = new Uri("your url");
HttpResponseMessage response = await webClient.GetAsync(uri)
var jsonString = await response.Content.ReadAsStringAsync();
var objData = JsonConvert.DeserializeObject<List<CategoryModel>>(jsonString);

ERROR Android emulator gets killed

If you use McAfee Antivirus and Windows 10 this might help you:

Uninstalling and reinstalling Android Emulator as snehatilak suggested initially helped in my case, though the next day the emulator was dead yet again.

I found that McAfee antivirus had quarantined the file AVD.conf that had been in C:\Users[username].android\avd[avdImage]\

After restoring AVD.conf and excluding it from scans it seems to be ok again.

This all started 02.02.2021 after what I guess was an McAfee update.

Here are the steps:

First go to 'Quarantined items' under Settings and restore the AVD.conf file enter image description here

Then go to 'Real-Time Scanning' under Settings and exclude AVD.conf in each emulator you have created. (Located under C:\Users[username].android\avd[avdImage])

enter image description here

Differences between contentType and dataType in jQuery ajax function

From the documentation:

contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')

Type: String

When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it'll always be sent to the server (even if no data is sent). If no charset is specified, data will be transmitted to the server using the server's default charset; you must decode this appropriately on the server side.

and:

dataType (default: Intelligent Guess (xml, json, script, or html))

Type: String

The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).

They're essentially the opposite of what you thought they were.

Access denied for user 'root'@'localhost' (using password: Yes) after password reset LINUX

Actually I took a closer look at the user table in mysql database, turns out someone prior to me edited the ssl_type field for user root to SSL.

I edited that field and restarted mysql and it worked like a charm.

Thanks.

GenyMotion Unable to start the Genymotion virtual device

I had exactly the same problem as you, tried everything, but the solution is really easy:

  1. Open Network and Sharing Center
  2. Change adapter settings
  3. Right click your Virtualbox host-only adapter and select Properties Enable "Virtualbox NDIS6 Bridget Networking Driver"

How to Bulk Insert from XLSX file extension?

you can save the xlsx file as a tab-delimited text file and do

BULK INSERT TableName
        FROM 'C:\SomeDirectory\my table.txt'
            WITH
    (
                FIELDTERMINATOR = '\t',
                ROWTERMINATOR = '\n'
    )
GO

How to connect access database in c#

You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?

this.Controls.Add(dataGridView1);

By the way the code is a bit confused

String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql  = "SELECT Clients  FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
     conn.Open();
     DataSet ds = new DataSet();
     DataGridView dataGridView1 = new DataGridView();
     using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
     {
         adapter.Fill(ds);
         dataGridView1.DataSource = ds;
         // Of course, before addint the datagrid to the hosting form you need to 
         // set position, location and other useful properties. 
         // Why don't you create the DataGrid with the designer and use that instance instead?
         this.Controls.Add(dataGridView1);
     }
}

EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as

 SELECT field_names_list FROM _tablename_

so the correct syntax to use for retrieving all the clients data is

 string sql  = "SELECT * FROM Clients";

where the * means -> all the fields present in the table

How to insert special characters into a database?

$insert_data = mysql_real_escape_string($input_data);

Assuming that you have the data stored as $input_data

Razor HtmlHelper Extensions (or other namespaces for views) Not Found

Since the Beta, Razor uses a different config section for globally defining namespace imports. In your Views\Web.config file you should add the following:

<configSections>
  <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
    <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
  </sectionGroup>
</configSections>

<system.web.webPages.razor>
  <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      <add namespace="System.Web.Mvc.Html" />
      <add namespace="System.Web.Routing" />
      <!-- Your namespace here -->
    </namespaces>
  </pages>
</system.web.webPages.razor>

Use the MVC 3 upgrade tool to automatically ensure you have the right config values.

Note that you might need to close and reopen the file for the changes to be picked up by the editor.

Sorting object property by values

I made a plugin just for this, it accepts 1 arg which is an unsorted object, and returns an object which has been sorted by prop value. This will work on all 2 dimensional objects such as {"Nick": 28, "Bob": 52}...

var sloppyObj = {
    'C': 78,
    'A': 3,
    'B': 4
};

// Extend object to support sort method
function sortObj(obj) {
    "use strict";

    function Obj2Array(obj) {
        var newObj = [];
        for (var key in obj) {
            if (!obj.hasOwnProperty(key)) return;
            var value = [key, obj[key]];
            newObj.push(value);
        }
        return newObj;
    }

    var sortedArray = Obj2Array(obj).sort(function(a, b) {
        if (a[1] < b[1]) return -1;
        if (a[1] > b[1]) return 1;
        return 0;
    });

    function recreateSortedObject(targ) {
        var sortedObj = {};
        for (var i = 0; i < targ.length; i++) {
            sortedObj[targ[i][0]] = targ[i][1];
        }
        return sortedObj;
    }
    return recreateSortedObject(sortedArray);
}

var sortedObj = sortObj(sloppyObj);

alert(JSON.stringify(sortedObj));

Here is a demo of the function working as expected http://codepen.io/nicholasabrams/pen/RWRqve?editors=001

How to access site running apache server over lan without internet connection

In your httpd.conf make sure you have:

Listen *:80

And if you are using VirtualHosts then set them as given below:

NameVirtualHost *
<VirtualHost *>
   ...
</VirtualHost>

Access to file download dialog in Firefox

I didnt unserstood your objective, Do you wanted your test to automatically download file when test is getting executed, if yes, then You need to use custom Firefox profile in your test execution.

In the custom profile, for first time execute test manually and if download dialog comes, the set it Save it to Disk, also check Always perform this action checkbox which will ensure that file automatically get downloaded next time you run your test.

How to change package name in android studio?

Another good method is: First create a new package with the desired name by right clicking on the java folder -> new -> package.

Then, select and drag all your classes to the new package. Android Studio will refactor the package name everywhere.

Finally, delete the old package.

or Look into this post

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

Maybe your composer is outdated. Below are the steps to get rid of the error.

Note: For Windows professionals, Only Step2 and Step3 is needed and done.


Step1

Remove the composer:

sudo apt-get remove composer

Step2

Download the composer:

php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

Step3

Run composer-setup.php file

php composer-setup.php

Step4

Finally move the composer:

sudo mv composer.phar /usr/local/bin/composer  


Your composer should be updated now. To check it run command:

composer

You can remove the downloaded composer by php command

php -r "unlink('composer-setup.php');"

How to run (not only install) an android application using .apk file?

This is a solution in shell script:

apk="$apk_path"

1. Install apk

adb install "$apk"
sleep 1

2. Get package name

pkg_info=`aapt dump badging "$apk" | head -1 | awk -F " " '{print $2}'`
eval $pkg_info > /dev/null

3. Start app

pkg_name=$name
adb shell monkey -p "${pkg_name}" -c android.intent.category.LAUNCHER 1

Chart won't update in Excel (2007)

To update a chart just put a Sheets("Sheet1").Calculate into your sub procedure. If you have more charts on different tabs, then just create a worksheet loop.

Why can't Python find shared objects that are in directories in sys.path?

For me what works here is to using a version manager such as pyenv, which I strongly recommend to get your project environments and package versions well managed and separate from that of the operative system.

I had this same error after an OS update, but was easily fixed with pyenv install 3.7-dev (the version I use).

Using JSON POST Request

Modern browsers do not currently implement JSONRequest (as far as I know) since it is only a draft right now. I have found someone who has implemented it as a library that you can include in your page: http://devpro.it/JSON/files/JSONRequest-js.html (please note that it has a few dependencies).

Otherwise, you might want to go with another JS library like jQuery or Mootools.

PHP str_replace replace spaces with underscores

Try this instead:

$journalName = str_replace(' ', '_', $journalName);

to remove white space

Math.random() explanation

If you want to generate a number from 0 to 100, then your code would look like this:

(int)(Math.random() * 101);

To generate a number from 10 to 20 :

(int)(Math.random() * 11 + 10);

In the general case:

(int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);

(where lowerbound is inclusive and upperbound exclusive).

The inclusion or exclusion of upperbound depends on your choice. Let's say range = (upperbound - lowerbound) + 1 then upperbound is inclusive, but if range = (upperbound - lowerbound) then upperbound is exclusive.

Example: If I want an integer between 3-5, then if range is (5-3)+1 then 5 is inclusive, but if range is just (5-3) then 5 is exclusive.

What is the best or most commonly used JMX Console / Client

JRockit Mission Control is becoming Java Mission Control and will be dedicated exclusively to Hotspot. If you are an Oracle customer, you can download the 5.x versions of Java Mission Control from MOS (My Oracle Support). Java Mission Control will eventually be released together with the Oracle JDK. The reason it is not yet generally available is that there are some serious limitations, especially when using the Flight Recorder. However, if you are only interested in using the JMX console, you should be golden!

Writing .csv files from C++

Change

Morison_File << t;                                 //Printing to file
Morison_File << F;

To

Morison_File << t << ";" << F << endl;                                 //Printing to file

a , would also do instead of ;

How to remove leading and trailing white spaces from a given html string?

var trim = your_string.replace(/^\s+|\s+$/g, '');

How to create a timer using tkinter?

I have a simple answer to this problem. I created a thread to update the time. In the thread i run a while loop which gets the time and update it. Check the below code and do not forget to mark it as right answer.

from tkinter import *
from tkinter import *
import _thread
import time


def update():
    while True:
      t=time.strftime('%I:%M:%S',time.localtime())
      time_label['text'] = t



win = Tk()
win.geometry('200x200')

time_label = Label(win, text='0:0:0', font=('',15))
time_label.pack()


_thread.start_new_thread(update,())

win.mainloop()

SQLAlchemy default DateTime

The default keyword parameter should be given to the Column object.

Example:

Column(u'timestamp', TIMESTAMP(timezone=True), primary_key=False, nullable=False, default=time_now),

The default value can be a callable, which here I defined like the following.

from pytz import timezone
from datetime import datetime

UTC = timezone('UTC')

def time_now():
    return datetime.now(UTC)

IIS: Idle Timeout vs Recycle

I have inherited a desktop app that makes calls to a series of Web Services on IIS. The web services (also) have to be able to run timed processes, independently (without having the client on). Hence they all have timers. The web service timers were shutting down (memory leak?) so we set the Idle time out to 0 and timers stay on.

Log4j: How to configure simplest possible file logging?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

   <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
      <param name="Threshold" value="INFO" />
      <param name="File" value="sample.log"/>
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d %-5p  [%c{1}] %m %n" />
      </layout>
   </appender>

  <root> 
    <priority value ="debug" /> 
    <appender-ref ref="fileAppender" /> 
  </root> 

</log4j:configuration>

Log4j can be a bit confusing. So lets try to understand what is going on in this file: In log4j you have two basic constructs appenders and loggers.

Appenders define how and where things are appended. Will it be logged to a file, to the console, to a database, etc.? In this case you are specifying that log statements directed to fileAppender will be put in the file sample.log using the pattern specified in the layout tags. You could just as easily create a appender for the console or the database. Where the console appender would specify things like the layout on the screen and the database appender would have connection details and table names.

Loggers respond to logging events as they bubble up. If an event catches the interest of a specific logger it will invoke its attached appenders. In the example below you have only one logger the root logger - which responds to all logging events by default. In addition to the root logger you can specify more specific loggers that respond to events from specific packages. These loggers can have their own appenders specified using the appender-ref tags or will otherwise inherit the appenders from the root logger. Using more specific loggers allows you to fine tune the logging level on specific packages or to direct certain packages to other appenders.

So what this file is saying is:

  1. Create a fileAppender that logs to file sample.log
  2. Attach that appender to the root logger.
  3. The root logger will respond to any events at least as detailed as 'debug' level
  4. The appender is configured to only log events that are at least as detailed as 'info'

The net out is that if you have a logger.debug("blah blah") in your code it will get ignored. A logger.info("Blah blah"); will output to sample.log.

The snippet below could be added to the file above with the log4j tags. This logger would inherit the appenders from <root> but would limit the all logging events from the package org.springframework to those logged at level info or above.

  <!-- Example Package level Logger -->
    <logger name="org.springframework">
        <level value="info"/>
    </logger>   

successful/fail message pop up box after submit?

You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.

Also, remove the onclick="alert()" from your submit. This is the cause for your first undefined message.

<?php
  $posted = false;
  if( $_POST ) {
    $posted = true;

    // Database stuff here...
    // $result = mysql_query( ... )
    $result = $_POST['name'] == "danny"; // Dummy result
  }
?>

<html>
  <head></head>
  <body>

  <?php
    if( $posted ) {
      if( $result ) 
        echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
      else
        echo "<script type='text/javascript'>alert('failed!')</script>";
    }
  ?>
    <form action="" method="post">
      Name:<input type="text" id="name" name="name"/>
      <input type="submit" value="submit" name="submit"/>
    </form>
  </body>
</html>

Viewing local storage contents on IE

Since localStorage is a global object, you can add a watch in the dev tools. Just enter the dev tools, goto "watch", click on "Click to add..." and type in "localStorage".

Maven Error: Could not find or load main class

I got it too, for me the problem got resolved after deleting the m2 folder (C:\Users\username.m2) and updating the maven project.

Python: Find in list

Another alternative: you can check if an item is in a list with if item in list:, but this is order O(n). If you are dealing with big lists of items and all you need to know is whether something is a member of your list, you can convert the list to a set first and take advantage of constant time set lookup:

my_set = set(my_list)
if item in my_set:  # much faster on average than using a list
    # do something

Not going to be the correct solution in every case, but for some cases this might give you better performance.

Note that creating the set with set(my_list) is also O(n), so if you only need to do this once then it isn't any faster to do it this way. If you need to repeatedly check membership though, then this will be O(1) for every lookup after that initial set creation.

Create patch or diff file from git repository and apply it to another different git repository

To produce patch for several commits, you should use format-patch git command, e.g.

git format-patch -k --stdout R1..R2

This will export your commits into patch file in mailbox format.

To generate patch for the last commit, run:

git format-patch -k --stdout HEAD^

Then in another repository apply the patch by am git command, e.g.

git am -3 -k file.patch

See: man git-format-patch and git-am.

Get data from JSON file with PHP

Use json_decode to transform your JSON into a PHP array. Example:

$json = '{"a":"b"}';
$array = json_decode($json, true);
echo $array['a']; // b

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

Although this is valid in HTML, you can't use an ID starting with an integer in CSS selectors.

As pointed out, you can use getElementById instead, but you can also still achieve the same with a querySelector:

document.querySelector("[id='22']")

How do you access a website running on localhost from iPhone browser

  1. Firstly, your have to confirm that you also access server api via your mac ip on mac browser. If not, make sure your server allow do that instead of just localhost (127.0.0.1) by runing your server on 0.0.0.0
  2. Go to safari on iphone and make a get request by api your server serve: ex http://0.0.0.0/st. Safari auto redirect to server your mac runing (at your mac ip)
  3. If you want to make request on your iphone app. It shoud be repalce requet 0.0.0.0 by [your mac/server ip]

oracle.jdbc.driver.OracleDriver ClassNotFoundException

You can add a JAR which having above specified class exist e.g.ojdbc jar which supported by installed java version, also make sure that you have added it into classpath.

PHP Error: Cannot use object of type stdClass as array (array and object issues)

$blog is an object not an array

try using $blog->id instead of $blog['id']

Why can I not create a wheel in python?

I also ran into this all of a sudden, after it had previously worked, and it was because I was inside a virtualenv, and wheel wasn’t installed in the virtualenv.

How to change pivot table data source in Excel?

In order to change the data source from the ribbon in excel 2007...

Click on your pivot table in the worksheet. Go to the ribbon where it says Pivot Table Tools, Options Tab. Select the Change Data Source button. A dialog box will appear.

To get the right range and avoid an error message... select the contents of the existing field and delete it, then switch to the new data source worksheet and highlight the data area (the dialog box will stay on top of all windows). Once you've selected the new data source correctly, it will fill in the blank field (which you deleted before) in the dialog box. Click OK. Switch back to your pivot table and it should have updated with the new data from the new source.

ruby LoadError: cannot load such file

The directory where st.rb lives is most likely not on your load path.

Assuming that st.rb is located in a directory called lib relative to where you invoke irb, you can add that lib directory to the list of directories that ruby uses to load classes or modules with this:

$: << 'lib'

For example, in order to call the module called 'foobar' (foobar.rb) that lives in the lib directory, I would need to first add the lib directory to the list of load path. Here, I am just appending the lib directory to my load path:

irb(main):001:0> require 'foobar'
LoadError: no such file to load -- foobar
        from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `gem_original_require'
        from /usr/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:36:in `require'
        from (irb):1
irb(main):002:0> $:
=> ["/usr/lib/ruby/gems/1.8/gems/spoon-0.0.1/lib", "/usr/lib/ruby/gems/1.8/gems/interactive_editor-0.0.10/lib", "/usr/lib/ruby/site_ruby/1.8", "/usr/lib/ruby/site_ruby/1.8/i386-cygwin", "/usr/lib/ruby/site_ruby", "/usr/lib/ruby/vendor_ruby/1.8", "/usr/lib/ruby/vendor_ruby/1.8/i386-cygwin", "/usr/lib/ruby/vendor_ruby", "/usr/lib/ruby/1.8", "/usr/lib/ruby/1.8/i386-cygwin", "."]
irb(main):004:0> $: << 'lib'
=> ["/usr/lib/ruby/gems/1.8/gems/spoon-0.0.1/lib", "/usr/lib/ruby/gems/1.8/gems/interactive_editor-0.0.10/lib", "/usr/lib/ruby/site_ruby/1.8", "/usr/lib/ruby/site_ruby/1.8/i386-cygwin", "/usr/lib/ruby/site_ruby", "/usr/lib/ruby/vendor_ruby/1.8", "/usr/lib/ruby/vendor_ruby/1.8/i386-cygwin", "/usr/lib/ruby/vendor_ruby", "/usr/lib/ruby/1.8", "/usr/lib/ruby/1.8/i386-cygwin", ".", "lib"]
irb(main):005:0> require 'foobar'
=> true

EDIT Sorry, I completely missed the fact that you are using ruby 1.9.x. All accounts report that your current working directory has been removed from LOAD_PATH for security reasons, so you will have to do something like in irb:

$: << "."

How to format a phone number with jQuery

An alternative solution:

_x000D_
_x000D_
function numberWithSpaces(value, pattern) {_x000D_
  var i = 0,_x000D_
    phone = value.toString();_x000D_
  return pattern.replace(/#/g, _ => phone[i++]);_x000D_
}_x000D_
_x000D_
console.log(numberWithSpaces('2124771000', '###-###-####'));
_x000D_
_x000D_
_x000D_

Can you change a path without reloading the controller in AngularJS?

There is simple way to change path without reloading

URL is - http://localhost:9000/#/edit_draft_inbox/1457

Use this code to change URL, Page will not be redirect

Second parameter "false" is very important.

$location.path('/edit_draft_inbox/'+id, false);

Rotating x axis labels in R for barplot

You can use ggplot2 to rotate the x-axis label adding an additional layer

theme(axis.text.x = element_text(angle = 90, hjust = 1))

Can clearInterval() be called inside setInterval()?

Yes you can. You can even test it:

_x000D_
_x000D_
var i = 0;_x000D_
var timer = setInterval(function() {_x000D_
  console.log(++i);_x000D_
  if (i === 5) clearInterval(timer);_x000D_
  console.log('post-interval'); //this will still run after clearing_x000D_
}, 200);
_x000D_
_x000D_
_x000D_

In this example, this timer clears when i reaches 5.

ImportError: No module named psycopg2

Use psycopg2-binary instead of psycopg2.

pip install psycopg2-binary

Or you will get the warning below:

UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: http://initd.org/psycopg/docs/install.html#binary-install-from-pypi.

Reference: Psycopg 2.7.4 released | Psycopg

Table variable error: Must declare the scalar variable "@temp"

You could stil use @TEMP if you quote the identifier "@TEMP":

declare @TEMP table (ID int, Name varchar(max));
insert into @temp SELECT 1 AS ID, 'a' Name;

SELECT * FROM @TEMP WHERE "@TEMP".ID  = 1 ;   

db<>fiddle demo

How to evaluate a math expression given in string form?

It's too late to answer but I came across same situation to evaluate expression in java, it might help someone

MVEL does runtime evaluation of expressions, we can write a java code in String to get it evaluated in this.

    String expressionStr = "x+y";
    Map<String, Object> vars = new HashMap<String, Object>();
    vars.put("x", 10);
    vars.put("y", 20);
    ExecutableStatement statement = (ExecutableStatement) MVEL.compileExpression(expressionStr);
    Object result = MVEL.executeExpression(statement, vars);

Error: "Could Not Find Installable ISAM"

Try putting single quotes around the data source:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\ptdb\Program Tracking Database.mdb';

The problem tends to be white space which does have meaning to the parser.

If you had other attributes (e.g., Extended Properties), their values may also have to be enclosed in single quotes:

Provider=Microsoft.Jet.OLEDB.4.0;Data Source='D:\ptdb\Program Tracking Database.mdb'; Extended Properties='Excel 8.0;HDR=YES;IMEX=1;';

You could equally well use double quotes; however, you'll probably have to escape them, and I find that more of a Pain In The Algorithm than using singles.

Catching an exception while using a Python 'with' statement

Differentiating between the possible origins of exceptions raised from a compound with statement

Differentiating between exceptions that occur in a with statement is tricky because they can originate in different places. Exceptions can be raised from either of the following places (or functions called therein):

  • ContextManager.__init__
  • ContextManager.__enter__
  • the body of the with
  • ContextManager.__exit__

For more details see the documentation about Context Manager Types.

If we want to distinguish between these different cases, just wrapping the with into a try .. except is not sufficient. Consider the following example (using ValueError as an example but of course it could be substituted with any other exception type):

try:
    with ContextManager():
        BLOCK
except ValueError as err:
    print(err)

Here the except will catch exceptions originating in all of the four different places and thus does not allow to distinguish between them. If we move the instantiation of the context manager object outside the with, we can distinguish between __init__ and BLOCK / __enter__ / __exit__:

try:
    mgr = ContextManager()
except ValueError as err:
    print('__init__ raised:', err)
else:
    try:
        with mgr:
            try:
                BLOCK
            except TypeError:  # catching another type (which we want to handle here)
                pass
    except ValueError as err:
        # At this point we still cannot distinguish between exceptions raised from
        # __enter__, BLOCK, __exit__ (also BLOCK since we didn't catch ValueError in the body)
        pass

Effectively this just helped with the __init__ part but we can add an extra sentinel variable to check whether the body of the with started to execute (i.e. differentiating between __enter__ and the others):

try:
    mgr = ContextManager()  # __init__ could raise
except ValueError as err:
    print('__init__ raised:', err)
else:
    try:
        entered_body = False
        with mgr:
            entered_body = True  # __enter__ did not raise at this point
            try:
                BLOCK
            except TypeError:  # catching another type (which we want to handle here)
                pass
    except ValueError as err:
        if not entered_body:
            print('__enter__ raised:', err)
        else:
            # At this point we know the exception came either from BLOCK or from __exit__
            pass

The tricky part is to differentiate between exceptions originating from BLOCK and __exit__ because an exception that escapes the body of the with will be passed to __exit__ which can decide how to handle it (see the docs). If however __exit__ raises itself, the original exception will be replaced by the new one. To deal with these cases we can add a general except clause in the body of the with to store any potential exception that would have otherwise escaped unnoticed and compare it with the one caught in the outermost except later on - if they are the same this means the origin was BLOCK or otherwise it was __exit__ (in case __exit__ suppresses the exception by returning a true value the outermost except will simply not be executed).

try:
    mgr = ContextManager()  # __init__ could raise
except ValueError as err:
    print('__init__ raised:', err)
else:
    entered_body = exc_escaped_from_body = False
    try:
        with mgr:
            entered_body = True  # __enter__ did not raise at this point
            try:
                BLOCK
            except TypeError:  # catching another type (which we want to handle here)
                pass
            except Exception as err:  # this exception would normally escape without notice
                # we store this exception to check in the outer `except` clause
                # whether it is the same (otherwise it comes from __exit__)
                exc_escaped_from_body = err
                raise  # re-raise since we didn't intend to handle it, just needed to store it
    except ValueError as err:
        if not entered_body:
            print('__enter__ raised:', err)
        elif err is exc_escaped_from_body:
            print('BLOCK raised:', err)
        else:
            print('__exit__ raised:', err)

Alternative approach using the equivalent form mentioned in PEP 343

PEP 343 -- The "with" Statement specifies an equivalent "non-with" version of the with statement. Here we can readily wrap the various parts with try ... except and thus differentiate between the different potential error sources:

import sys

try:
    mgr = ContextManager()
except ValueError as err:
    print('__init__ raised:', err)
else:
    try:
        value = type(mgr).__enter__(mgr)
    except ValueError as err:
        print('__enter__ raised:', err)
    else:
        exit = type(mgr).__exit__
        exc = True
        try:
            try:
                BLOCK
            except TypeError:
                pass
            except:
                exc = False
                try:
                    exit_val = exit(mgr, *sys.exc_info())
                except ValueError as err:
                    print('__exit__ raised:', err)
                else:
                    if not exit_val:
                        raise
        except ValueError as err:
            print('BLOCK raised:', err)
        finally:
            if exc:
                try:
                    exit(mgr, None, None, None)
                except ValueError as err:
                    print('__exit__ raised:', err)

Usually a simpler approach will do just fine

The need for such special exception handling should be quite rare and normally wrapping the whole with in a try ... except block will be sufficient. Especially if the various error sources are indicated by different (custom) exception types (the context managers need to be designed accordingly) we can readily distinguish between them. For example:

try:
    with ContextManager():
        BLOCK
except InitError:  # raised from __init__
    ...
except AcquireResourceError:  # raised from __enter__
    ...
except ValueError:  # raised from BLOCK
    ...
except ReleaseResourceError:  # raised from __exit__
    ...

How to move git repository with all branches from bitbucket to github?

There is the Importing a repository with GitHub Importer

If you have a project hosted on another version control system as Mercurial, you can automatically import it to GitHub using the GitHub Importer tool.

  1. In the upper-right corner of any page, click , and then click Import repository.
  2. Under "Your old repository's clone URL", type the URL of the project you want to import.
  3. Choose your user account or an organization to own the repository, then type a name for the repository on GitHub.
  4. Specify whether the new repository should be public or private.
    • Public repositories are visible to any user on GitHub, so you can benefit from GitHub's collaborative community.
    • Public or private repository radio buttonsPrivate repositories are only available to the repository owner, as well as any collaborators you choose to share with.
  5. Review the information you entered, then click Begin import.

You'll receive an email when the repository has been completely imported.

  1. https://help.github.com/categories/importing-your-projects-to-github
  2. https://help.github.com/articles/importing-a-repository-with-github-importer/

How can I send mail from an iPhone application

To send an email from iPhone application you need to do below list of task.

Step 1: Import #import <MessageUI/MessageUI.h> In your controller class where you want to send an email.

Step 2: Add the delegate to your controller like shown below

 @interface <yourControllerName> : UIViewController <MFMessageComposeViewControllerDelegate, MFMailComposeViewControllerDelegate>

Step 3: Add below method for send email.

 - (void) sendEmail {
 // Check if your app support the email.
 if ([MFMailComposeViewController canSendMail]) {
    // Create an object of mail composer.
    MFMailComposeViewController *mailComposer =      [[MFMailComposeViewController alloc] init];
    // Add delegate to your self.
    mailComposer.mailComposeDelegate = self;
    // Add recipients to mail if you do not want to add default recipient then remove below line.
    [mailComposer setToRecipients:@[<add here your recipient objects>]];
    // Write email subject.
    [mailComposer setSubject:@“<Your Subject Here>”];
    // Set your email body and if body contains HTML then Pass “YES” in isHTML.
    [mailComposer setMessageBody:@“<Your Message Body>” isHTML:NO];
    // Show your mail composer.
    [self presentViewController:mailComposer animated:YES completion:NULL];
 }
 else {
 // Here you can show toast to user about not support to sending email.
}
}

Step 4: Implement MFMailComposeViewController Delegate

- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(nullable NSError *)error {
[controller dismissViewControllerAnimated:TRUE completion:nil];


switch (result) {
   case MFMailComposeResultSaved: {
    // Add code on save mail to draft.
    break;
}
case MFMailComposeResultSent: {
    // Add code on sent a mail.
    break;
}
case MFMailComposeResultCancelled: {
    // Add code on cancel a mail.
    break;
}
case MFMailComposeResultFailed: {
    // Add code on failed to send a mail.
    break;
}
default:
    break;
}
}

Count number of occurrences for each unique value

You should change the query to:

SELECT time_col, COUNT(time_col) As Count
FROM time_table
WHERE activity_col = 3
GROUP BY time_col

This vl works correctly.

Git - How to use .netrc file on Windows to save user and password

You can also install Git Credential Manager for Windows to save Git passwords in Windows credentials manager instead of _netrc. This is a more secure way to store passwords.

How to delete Project from Google Developers Console

  1. Go to the developers console and pick the application from the dropdown
  2. Select the utilities icon (see image below) and click project settings
  3. Click on the the Delete Project link
  4. Enter the project ID and click Shutdown, project will be deleted in 7 days

enter image description here

GIT vs. Perforce- Two VCS will enter... one will leave

Apparently GitHub now offer git training courses to companies. Quoth their blog post about it:

I’ve been down to the Google campus a number of times in the last few weeks helping to train the Androids there in Git. I was asked by Shawn Pearce (you may know him from his Git and EGit/JGit glory – he is the hero that takes over maintanance when Junio is out of town) to come in to help him train the Google engineers working on Andriod in transitioning from Perforce to Git, so Android could be shared with the masses. I can tell you I was more than happy to do it.

[…]

Logical Awesome is now officially offering this type of custom training service to all companies, where we can help your organization with training and planning if you are thinking about switching to Git as well.

Emphasis mine.

MongoDB relationships: embed or reference?

In general, embed is good if you have one-to-one or one-to-many relationships between entities, and reference is good if you have many-to-many relationships.

C# send a simple SSH command

For .Net core i had many problems using SSH.net and also its deprecated. I tried a few other libraries, even for other programming languages. But i found a very good alternative. https://stackoverflow.com/a/64443701/8529170

Color theme for VS Code integrated terminal

In case you are color picky, use this code to customize every segment.

Step 1: Windows: Open user settings (ctrl + ,) Mac: Command + Shift + P

Step 2: Search for "workbench: color customizations" and select Edit in settings.json. Page the following code inside existing {} and customize as you like.

"workbench.colorCustomizations": {
    "terminal.background":"#131212",
    "terminal.foreground":"#dddad6",
    "terminal.ansiBlack":"#1D2021",
    "terminal.ansiBrightBlack":"#665C54",
    "terminal.ansiBrightBlue":"#0D6678",
    "terminal.ansiBrightCyan":"#8BA59B",
    "terminal.ansiBrightGreen":"#237e02",
    "terminal.ansiBrightMagenta":"#8F4673",
    "terminal.ansiBrightRed":"#FB543F",
    "terminal.ansiBrightWhite":"#FDF4C1",
    "terminal.ansiBrightYellow":"#FAC03B",
    "terminal.ansiCyan":"#8BA59B",
    "terminal.ansiGreen":"#95C085",
    "terminal.ansiMagenta":"#8F4673",
    "terminal.ansiRed":"#FB543F",
    "terminal.ansiWhite":"#A89984",
    "terminal.ansiYellow":"#FAC03B"
  }

New line character in VB.Net?

The proper way to do this in VB is to use on of the VB constants for newlines. The main three are

  • vbCrLf = "\r\n"
  • vbCr = "\r"
  • vbLf = "\n"

VB by default doesn't allow for any character escape codes in strings which is different than languages like C# and C++ which do. One of the reasons for doing this is ease of use when dealing with file paths.

  • C++ file path string: "c:\\foo\\bar.txt"
  • VB file path string: "c:\foo\bar.txt"
  • C# file path string: C++ way or @"c:\foo\bar.txt"

Sorting multiple keys with Unix sort

Use the -k option (or --key=POS1[,POS2]). It can appear multiple times and each key can have global options (such as n for numeric sort)

How to render an ASP.NET MVC view as a string?

Here's what I came up with, and it's working for me. I added the following method(s) to my controller base class. (You can always make these static methods somewhere else that accept a controller as a parameter I suppose)

MVC2 .ascx style

protected string RenderViewToString<T>(string viewPath, T model) {
  ViewData.Model = model;
  using (var writer = new StringWriter()) {
    var view = new WebFormView(ControllerContext, viewPath);
    var vdd = new ViewDataDictionary<T>(model);
    var viewCxt = new ViewContext(ControllerContext, view, vdd,
                                new TempDataDictionary(), writer);
    viewCxt.View.Render(viewCxt, writer);
    return writer.ToString();
  }
}

Razor .cshtml style

public string RenderRazorViewToString(string viewName, object model)
{
  ViewData.Model = model;
  using (var sw = new StringWriter())
  {
    var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                             viewName);
    var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                 ViewData, TempData, sw);
    viewResult.View.Render(viewContext, sw);
    viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
    return sw.GetStringBuilder().ToString();
  }
}

Edit: added Razor code.

JavaScript for detecting browser language preference

I had the same problem, and I wrote the following front-end only library that wraps up the code for multiple browsers. It's not much code, but nice to not have to copy and paste the same code across multiple websites.

Get it: acceptedlanguages.js

Use it:

<script src="acceptedlanguages.js"></script>
<script type="text/javascript">
  console.log('Accepted Languages:  ' + acceptedlanguages.accepted);
</script>

It always returns an array, ordered by users preference. In Safari & IE the array is always single length. In FF and Chrome it may be more than one language.

How can I create a keystore?

I followed this guide to create the debug keystore.

The command is:

keytool -genkeypair -alias androiddebugkey -keypass android -keystore debug.keystore -storepass android -dname "CN=Android Debug,O=Android,C=US" -validity 9999

Using an HTTP PROXY - Python

You can do it even without the HTTP_PROXY environment variable. Try this sample:

import urllib2

proxy_support = urllib2.ProxyHandler({"http":"http://61.233.25.166:80"})
opener = urllib2.build_opener(proxy_support)
urllib2.install_opener(opener)

html = urllib2.urlopen("http://www.google.com").read()
print html

In your case it really seems that the proxy server is refusing the connection.


Something more to try:

import urllib2

#proxy = "61.233.25.166:80"
proxy = "YOUR_PROXY_GOES_HERE"

proxies = {"http":"http://%s" % proxy}
url = "http://www.google.com/search?q=test"
headers={'User-agent' : 'Mozilla/5.0'}

proxy_support = urllib2.ProxyHandler(proxies)
opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler(debuglevel=1))
urllib2.install_opener(opener)

req = urllib2.Request(url, None, headers)
html = urllib2.urlopen(req).read()
print html

Edit 2014: This seems to be a popular question / answer. However today I would use third party requests module instead.

For one request just do:

import requests

r = requests.get("http://www.google.com", 
                 proxies={"http": "http://61.233.25.166:80"})
print(r.text)

For multiple requests use Session object so you do not have to add proxies parameter in all your requests:

import requests

s = requests.Session()
s.proxies = {"http": "http://61.233.25.166:80"}

r = s.get("http://www.google.com")
print(r.text)

How to beautifully update a JPA entity in Spring Data?

Simple JPA update..

Customer customer = em.find(id, Customer.class); //Consider em as JPA EntityManager
customer.setName(customerDto.getName);
em.merge(customer);

How to watch for a route change in AngularJS?

$rootScope.$on( "$routeChangeStart", function(event, next, current) {
  //..do something
  //event.stopPropagation();  //if you don't want event to bubble up 
});

Android Writing Logs to text File

You should take a look at microlog4android. They have a solution ready to log to a file.

http://code.google.com/p/microlog4android/

inserting characters at the start and end of a string

For completeness along with the other answers:

yourstring = "L%sLL" % yourstring

Or, more forward compatible with Python 3.x:

yourstring = "L{0}LL".format(yourstring)

Content is not allowed in Prolog SAXParserException

I faced the same issue. Our application running on four application servers and due to invalid schema location mentioned on one of the web service WSDL, hung threads are generated on the servers . The appliucations got down frequently. After corrected the schema Location , the issue got resolved.

cURL equivalent in Node.js?

Uses reqclient, it's a small client module on top of request that allows you to log all the activity with cURL style (optional, for development environments). Also has nice features like URL and parameters parsing, authentication integrations, cache support, etc.

For example, if you create a client object an do a request:

var RequestClient = require("reqclient").RequestClient;
var client = new RequestClient({
        baseUrl:"http://baseurl.com/api/v1.1",
        debugRequest:true, debugResponse:true
    });

var resp = client.post("client/orders", {"client":1234,"ref_id":"A987"}, {headers: {"x-token":"AFF01XX"}})

It will log within the console something like this:

[Requesting client/orders]-> -X POST http://baseurl.com/api/v1.1/client/orders -d '{"client": 1234, "ref_id": "A987"}' -H '{"x-token": "AFF01XX"}' -H Content-Type:application/json
[Response   client/orders]<- Status 200 - {"orderId": 1320934}

The request will return a Promise object, so you have to handle with then and catch what to do with the result.

reqclient is available with npm, you can install the module with: npm install reqclient.

Find all stored procedures that reference a specific column in some table

You can use ApexSQL Search, it's a free SSMS and Visual Studio add-in and it can list all objects that reference a specific table column. It can also find data stored in tables and views. You can easily filter the results to show a specific database object type that references the column

enter image description here

Disclaimer: I work for ApexSQL as a Support Engineer

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

You can use if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA) method to detect whether never ask is checked or not.

For more reference : Check this

To check for multiple permissions use:

  if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)
                                || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                                || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_FINE_LOCATION)
                                || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)) {
                            showDialogOK("Service Permissions are required for this app",
                                    new DialogInterface.OnClickListener() {
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            switch (which) {
                                                case DialogInterface.BUTTON_POSITIVE:
                                                    checkAndRequestPermissions();
                                                    break;
                                                case DialogInterface.BUTTON_NEGATIVE:
                                                    // proceed with logic by disabling the related features or quit the app.
                                                    finish();
                                                    break;
                                            }
                                        }
                                    });
                        }
                        //permission is denied (and never ask again is  checked)
                        //shouldShowRequestPermissionRationale will return false
                        else {
                            explain("You need to give some mandatory permissions to continue. Do you want to go to app settings?");
                            //                            //proceed with logic by disabling the related features or quit the app.
                        }

explain() method

private void explain(String msg){
        final android.support.v7.app.AlertDialog.Builder dialog = new android.support.v7.app.AlertDialog.Builder(this);
        dialog.setMessage(msg)
                .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        //  permissionsclass.requestPermission(type,code);
                        startActivity(new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:com.exampledemo.parsaniahardik.marshmallowpermission")));
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        finish();
                    }
                });
        dialog.show();
    }

Above code will also show dialog, which will redirect user to app settings screen from where he can give permission if had checked never ask again button.

Java FileWriter how to write to next Line

.newLine() is the best if your system property line.separator is proper . and sometime you don't want to change the property runtime . So alternative solution is appending \n

How to set an image's width and height without stretching it?

This is quite old question, but I have had the exact same annoying issue where everything worked fine for Chrome/Edge (with object-fit property) but same css property did not work in IE11 (since its unsupported in IE11), I ended up using HTML5 "figure" element which solved all my problems.

I personally did not use the outer DIV tag since that did not help at all in my case, so I avoided the outer DIV and simply replaced with 'figure' element.

The below code forces the image to reduce/scale down nicely (without changing the original aspect ratio).

<figure class="figure-class">
  <img class="image-class" src="{{photoURL}}" />
</figure>

and css classes:

.image-class {
    border: 6px solid #E8E8E8;
    max-width: 189px;
    max-height: 189px;
}

.figure-class {
    width: 189px;
    height: 189px;
}

Get element from within an iFrame

If iframe is not in the same domain such that you cannot get access to its internals from the parent but you can modify the source code of the iframe then you can modify the page displayed by the iframe to send messages to the parent window, which allows you to share information between the pages. Some sources:

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Rob Heiser suggested checking out your java version by using 'java -version'.

That will identify the Java version that will be commonly found and used. Doing dev work, you can often have more than one version installed (I currently have 2 JREs - 6 and 7 - and may soon have 8).

http://www.coderanch.com/t/453224/java/java/java-version-work-setting-path

java -version will look for java.exe in the System32 directory in Windows. That's where a JRE will install it.

I'm assuming that IE either simply looks for java and that automatically starts checking in System32 or it'll use the path and hit whichever java.exe comes first in your path (if you tamper with the path to point to another JRE).

Also from what SLaks said, I would disagree with one thing. There is likely slightly better performance out of 64-it IE in 64-bit environments. So there is some reason for using it.

How to parse the AndroidManifest.xml file inside an .apk package

Check this following WPF Project which decodes the properties correctly.

CSS values using HTML5 data attribute

There is, indeed, prevision for such feature, look http://www.w3.org/TR/css3-values/#attr-notation

This fiddle should work like what you need, but will not for now.

Unfortunately, it's still a draft, and isn't fully implemented on major browsers.

It does work for content on pseudo-elements, though.

How to generate XML from an Excel VBA macro?

You might like to consider ADO - a worksheet or range can be used as a table.

Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adPersistXML = 1

Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")

''It wuld probably be better to use the proper name, but this is
''convenient for notes
strFile = Workbooks(1).FullName

''Note HDR=Yes, so you can use the names in the first row of the set
''to refer to columns, note also that you will need a different connection
''string for >=2007
strCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFile _
        & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=1"";"


cn.Open strCon
rs.Open "Select * from [Sheet1$]", cn, adOpenStatic, adLockOptimistic

If Not rs.EOF Then
    rs.MoveFirst
    rs.Save "C:\Docs\Table1.xml", adPersistXML
End If

rs.Close
cn.Close

How to do what head, tail, more, less, sed do in Powershell?

more.exe exists on Windows, ports of less are easily found (and the PowerShell Community Extensions, PSCX, includes one).

PowerShell doesn't really provide any alternative to separate programs for either, but for structured data Out-Grid can be helpful.

Head and Tail can both be emulated with Select-Object using the -First and -Last parameters respectively.

Sed functions are all available but structured rather differently. The filtering options are available in Where-Object (or via Foreach-Object and some state for ranges). Other, transforming, operations can be done with Select-Object and Foreach-Object.

However as PowerShell passes (.NET) objects – with all their typed structure, eg. dates remain DateTime instances – rather than just strings, which each command needs to parse itself, much of sed and other such programs are redundant.

Java: Clear the console

Try the following :

System.out.print("\033\143");

This will work fine in Linux environment

Change image in HTML page every few seconds

Change setTimeout("changeImage()", 30000); to setInterval("changeImage()", 30000); and remove var timerid = setInterval(changeImage, 30000);.

How do I convert an Array to a List<object> in C#?

This allow you to send an object:

private List<object> ConvertArrayToList(dynamic array)

How can I get the current user directory?

$env:USERPROFILE = "C:\\Documents and Settings\\[USER]\\"

&& (AND) and || (OR) in IF statements

All the answers here are great but, just to illustrate where this comes from, for questions like this it's good to go to the source: the Java Language Specification.

Section 15:23, Conditional-And operator (&&), says:

The && operator is like & (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is true. [...] At run time, the left-hand operand expression is evaluated first [...] if the resulting value is false, the value of the conditional-and expression is false and the right-hand operand expression is not evaluated. If the value of the left-hand operand is true, then the right-hand expression is evaluated [...] the resulting value becomes the value of the conditional-and expression. Thus, && computes the same result as & on boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

And similarly, Section 15:24, Conditional-Or operator (||), says:

The || operator is like | (§15.22.2), but evaluates its right-hand operand only if the value of its left-hand operand is false. [...] At run time, the left-hand operand expression is evaluated first; [...] if the resulting value is true, the value of the conditional-or expression is true and the right-hand operand expression is not evaluated. If the value of the left-hand operand is false, then the right-hand expression is evaluated; [...] the resulting value becomes the value of the conditional-or expression. Thus, || computes the same result as | on boolean or Boolean operands. It differs only in that the right-hand operand expression is evaluated conditionally rather than always.

A little repetitive, maybe, but the best confirmation of exactly how they work. Similarly the conditional operator (?:) only evaluates the appropriate 'half' (left half if the value is true, right half if it's false), allowing the use of expressions like:

int x = (y == null) ? 0 : y.getFoo();

without a NullPointerException.

Math functions in AngularJS bindings

I think the best way to do it is by creating a filter, like this:

myModule.filter('ceil', function() {
    return function(input) {
        return Math.ceil(input);
    };
});

then the markup looks like this:

<p>The percentage is {{ (100*count/total) | ceil }}%</p>

Updated fiddle: http://jsfiddle.net/BB4T4/

Can an int be null in Java?

instead of declaring as int i declare it as Integer i then we can do i=null;

Integer i;
i=null;

Uploading a file in Rails

In your intiallizer/carrierwave.rb

if Rails.env.development? || Rails.env.test?
    config.storage = :file
    config.root = "#{Rails.root}/public"
    if Rails.env.test?
      CarrierWave.configure do |config|
        config.storage = :file
        config.enable_processing = false
      end
    end
 end

use this to store in a file while running on local

Android transparent status bar and actionbar

I'm developing an app that needs to look similar in all devices with >= API14 when it comes to actionbar and statusbar customization. I've finally found a solution and since it took a bit of my time I'll share it to save some of yours. We start by using an appcompat-21 dependency.

Transparent Actionbar:

values/styles.xml:

<style name="AppTheme" parent="Theme.AppCompat.Light">
...
</style>

<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
    <item name="android:windowContentOverlay">@null</item>
    <item name="windowActionBarOverlay">true</item>
    <item name="colorPrimary">@android:color/transparent</item>
</style>

<style name="AppTheme.ActionBar" parent="AppTheme">
    <item name="windowActionBarOverlay">false</item>
    <item name="colorPrimary">@color/default_yellow</item>
</style>


values-v21/styles.xml:

<style name="AppTheme" parent="Theme.AppCompat.Light">
    ...
</style>

<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
    <item name="colorPrimary">@android:color/transparent</item>
</style>

<style name="AppTheme.ActionBar" parent="AppTheme">
    <item name="colorPrimaryDark">@color/bg_colorPrimaryDark</item>
    <item name="colorPrimary">@color/default_yellow</item>
</style>

Now you can use these themes in your AndroidManifest.xml to specify which activities will have a transparent or colored ActionBar:

    <activity
            android:name=".MyTransparentActionbarActivity"
            android:theme="@style/AppTheme.ActionBar.Transparent"/>

    <activity
            android:name=".MyColoredActionbarActivity"
            android:theme="@style/AppTheme.ActionBar"/>

enter image description here enter image description here enter image description here enter image description here enter image description here

Note: in API>=21 to get the Actionbar transparent you need to get the Statusbar transparent too, otherwise will not respect your colour styles and will stay light-grey.



Transparent Statusbar (only works with API>=19):
This one it's pretty simple just use the following code:

protected void setStatusBarTranslucent(boolean makeTranslucent) {
        if (makeTranslucent) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

But you'll notice a funky result: enter image description here

This happens because when the Statusbar is transparent the layout will use its height. To prevent this we just need to:

SOLUTION ONE:
Add this line android:fitsSystemWindows="true" in your layout view container of whatever you want to be placed bellow the Actionbar:

    ...
        <LinearLayout
                android:fitsSystemWindows="true"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
            ...
        </LinearLayout>
    ...

SOLUTION TWO:
Add a few lines to our previous method:

protected void setStatusBarTranslucent(boolean makeTranslucent) {
        View v = findViewById(R.id.bellow_actionbar);
        if (v != null) {
            int paddingTop = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? MyScreenUtils.getStatusBarHeight(this) : 0;
            TypedValue tv = new TypedValue();
            getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, tv, true);
            paddingTop += TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
            v.setPadding(0, makeTranslucent ? paddingTop : 0, 0, 0);
        }

        if (makeTranslucent) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

Where R.id.bellow_actionbar will be the layout container view id of whatever we want to be placed bellow the Actionbar:

...
    <LinearLayout
            android:id="@+id/bellow_actionbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        ...
    </LinearLayout>
...

enter image description here

So this is it, it think I'm not forgetting something. In this example I didn't use a Toolbar but I think it'll have the same result. This is how I customize my Actionbar:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        View vg = getActionBarView();
        getWindow().requestFeature(vg != null ? Window.FEATURE_ACTION_BAR : Window.FEATURE_NO_TITLE);

        super.onCreate(savedInstanceState);
        setContentView(getContentView());

        if (vg != null) {
            getSupportActionBar().setCustomView(vg, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            getSupportActionBar().setDisplayShowCustomEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(false);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
            getSupportActionBar().setDisplayUseLogoEnabled(false);
        }
        setStatusBarTranslucent(true);
    }

Note: this is an abstract class that extends ActionBarActivity
Hope it helps!

Why is there an unexplainable gap between these inline-block div elements?

simply add a border: 2px solid #e60000; to your 2nd div tag CSS.

Definitely it works

#Div2Id {
    border: 2px solid #e60000; --> color is your preference
}

M_PI works with math.h but not with cmath in Visual Studio

This is still an issue in VS Community 2015 and 2017 when building either console or windows apps. If the project is created with precompiled headers, the precompiled headers are apparently loaded before any of the #includes, so even if the #define _USE_MATH_DEFINES is the first line, it won't compile. #including math.h instead of cmath does not make a difference.

The only solutions I can find are either to start from an empty project (for simple console or embedded system apps) or to add /Y- to the command line arguments, which turns off the loading of precompiled headers.

For information on disabling precompiled headers, see for example https://msdn.microsoft.com/en-us/library/1hy7a92h.aspx

It would be nice if MS would change/fix this. I teach introductory programming courses at a large university, and explaining this to newbies never sinks in until they've made the mistake and struggled with it for an afternoon or so.

What Does 'zoom' do in CSS?

Only IE and WebKit support zoom, and yes, in theory it does exactly what you're saying.

Try it out on an image to see it's full effect :)

How to configure Spring Security to allow Swagger URL to be accessed without authentication

I am using Spring Boot 5. I have this controller that I want an unauthenticated user to invoke.

  //Builds a form to send to devices   
@RequestMapping(value = "/{id}/ViewFormit", method = RequestMethod.GET)
@ResponseBody
String doFormIT(@PathVariable String id) {
    try
    {
        //Get a list of forms applicable to the current user
        FormService parent = new FormService();

Here is what i did in the configuuration.

  @Override
   protected void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers(
                    "/registration**",
                    "/{^[\\\\d]$}/ViewFormit",

Hope this helps....

How does lock work exactly?

The part within the lock statement can only be executed by one thread, so all other threads will wait indefinitely for it the thread holding the lock to finish. This can result in a so-called deadlock.

How can I do an asc and desc sort using underscore.js?

Descending order using underscore can be done by multiplying the return value by -1.

//Ascending Order:
_.sortBy([2, 3, 1], function(num){
    return num;
}); // [1, 2, 3]


//Descending Order:
_.sortBy([2, 3, 1], function(num){
    return num * -1;
}); // [3, 2, 1]

If you're sorting by strings not numbers, you can use the charCodeAt() method to get the unicode value.

//Descending Order Strings:
_.sortBy(['a', 'b', 'c'], function(s){ 
    return s.charCodeAt() * -1;
});

Bootstrap 4 Dropdown Menu not working?

It's an issue with popper.js file. What I found at the official site was that bundle files include popper in itself but not jquery. I managed to fix it by adding link to these files:

bootstrap.bundle.js
bootstrap.bundle.min.js

I removed popper.js however since it comes within the bundle file.

Website screenshots

If you don't want to use any third party tools, I have come across to simple solution that is using Google Page Insight api.

Just need to call it's api with params screenshot=true.

https://www.googleapis.com/pagespeedonline/v1/runPagespeed?
url=https://stackoverflow.com/&key={your_api_key}&screenshot=true

For mobile site view pass &strategy=mobile in params,

https://www.googleapis.com/pagespeedonline/v1/runPagespeed?
url=http://stackoverflow.com/&key={your_api_key}&screenshot=true&strategy=mobile

DEMO.

How to compare two JSON have the same properties without order?

This code will verify the json independently of param object order.

_x000D_
_x000D_
var isEqualsJson = (obj1,obj2)=>{
    keys1 = Object.keys(obj1);
    keys2 = Object.keys(obj2);

    //return true when the two json has same length and all the properties has same value key by key
    return keys1.length === keys2.length && Object.keys(obj1).every(key=>obj1[key]==obj2[key]);
}

var obj1 = {a:1,b:2,c:3};
var obj2 = {a:1,b:2,c:3}; 

console.log("json is equals: "+ isEqualsJson(obj1,obj2));
alert("json is equals: "+ isEqualsJson(obj1,obj2));
_x000D_
_x000D_
_x000D_

Differences between dependencyManagement and dependencies in Maven

Sorry I am very late to the party.

Let me try to explain the difference using mvn dependency:tree command

Consider the below example

Parent POM - My Project

<modules>
    <module>app</module>
    <module>data</module>
</modules>

<dependencies>
    <dependency>
        <groupId>com.google.guava</groupId>
        <artifactId>guava</artifactId>
        <version>19.0</version>
    </dependency>
</dependencies>

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.9</version>
        </dependency>
    </dependencies>
</dependencyManagement>

Child POM - data module

<dependencies>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
    </dependency>
</dependencies>

Child POM - app module (has no extra dependency, so leaving dependencies empty)

 <dependencies>
</dependencies>

On running mvn dependency:tree command, we get following result

Scanning for projects...
------------------------------------------------------------------------
Reactor Build Order:

MyProject
app
data

------------------------------------------------------------------------
Building MyProject 1.0-SNAPSHOT
------------------------------------------------------------------------

--- maven-dependency-plugin:2.8:tree (default-cli) @ MyProject ---
com.iamvickyav:MyProject:pom:1.0-SNAPSHOT
\- com.google.guava:guava:jar:19.0:compile

------------------------------------------------------------------------
Building app 1.0-SNAPSHOT
------------------------------------------------------------------------

--- maven-dependency-plugin:2.8:tree (default-cli) @ app ---
com.iamvickyav:app:jar:1.0-SNAPSHOT
\- com.google.guava:guava:jar:19.0:compile

------------------------------------------------------------------------
Building data 1.0-SNAPSHOT
------------------------------------------------------------------------

--- maven-dependency-plugin:2.8:tree (default-cli) @ data ---
com.iamvickyav:data:jar:1.0-SNAPSHOT
+- org.apache.commons:commons-lang3:jar:3.9:compile
\- com.google.guava:guava:jar:19.0:compile

Google guava is listed as dependency in every module (including parent), whereas the apache commons is listed as dependency only in data module (not even in parent module)

How can I copy a file on Unix using C?

#include <unistd.h>
#include <string.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>

#define    print_err(format, args...)   printf("[%s:%d][error]" format "\n", __func__, __LINE__, ##args)
#define    DATA_BUF_SIZE                (64 * 1024)    //limit to read maximum 64 KB data per time

int32_t get_file_size(const char *fname){
    struct stat sbuf;

    if (NULL == fname || strlen(fname) < 1){
        return 0;
    }

    if (stat(fname, &sbuf) < 0){
        print_err("%s, %s", fname, strerror(errno));
        return 0;
    }

    return sbuf.st_size; /* off_t shall be signed interge types, used for file size */
}

bool copyFile(CHAR *pszPathIn, CHAR *pszPathOut)
{
    INT32 fdIn, fdOut;
    UINT32 ulFileSize_in = 0;
    UINT32 ulFileSize_out = 0;
    CHAR *szDataBuf;

    if (!pszPathIn || !pszPathOut)
    {
        print_err(" Invalid param!");
        return false;
    }

    if ((1 > strlen(pszPathIn)) || (1 > strlen(pszPathOut)))
    {
        print_err(" Invalid param!");
        return false;
    }

    if (0 != access(pszPathIn, F_OK))
    {
        print_err(" %s, %s!", pszPathIn, strerror(errno));
        return false;
    }

    if (0 > (fdIn = open(pszPathIn, O_RDONLY)))
    {
        print_err("open(%s, ) failed, %s", pszPathIn, strerror(errno));
        return false;
    }

    if (0 > (fdOut = open(pszPathOut, O_CREAT | O_WRONLY | O_TRUNC, 0777)))
    {
        print_err("open(%s, ) failed, %s", pszPathOut, strerror(errno));
        close(fdIn);
        return false;
    }

    szDataBuf = malloc(DATA_BUF_SIZE);
    if (NULL == szDataBuf)
    {
        print_err("malloc() failed!");
        return false;
    }

    while (1)
    {
        INT32 slSizeRead = read(fdIn, szDataBuf, sizeof(szDataBuf));
        INT32 slSizeWrite;
        if (slSizeRead <= 0)
        {
            break;
        }

        slSizeWrite = write(fdOut, szDataBuf, slSizeRead);
        if (slSizeWrite < 0)
        {
            print_err("write(, , slSizeRead) failed, %s", slSizeRead, strerror(errno));
            break;
        }

        if (slSizeWrite != slSizeRead) /* verify wheter write all byte data successfully */
        {
            print_err(" write(, , %d) failed!", slSizeRead);
            break;
        }
    }

    close(fdIn);
    fsync(fdOut); /* causes all modified data and attributes to be moved to a permanent storage device */
    close(fdOut);

    ulFileSize_in = get_file_size(pszPathIn);
    ulFileSize_out = get_file_size(pszPathOut);
    if (ulFileSize_in == ulFileSize_out) /* verify again wheter write all byte data successfully */
    {
        free(szDataBuf);
        return true;
    }
    free(szDataBuf);
    return false;
}

400 BAD request HTTP error code meaning?

First check the URL it might be wrong, if it is correct then check the request body which you are sending, the possible cause is request that you are sending is missing right syntax.

To elaborate , check for special characters in the request string. If it is (special char) being used this is the root cause of this error.

try copying the request and analyze each and every tags data.

Sorted collection in Java

If you want to maintain a sorted list which you will frequently modify (i.e. a structure which, in addition to being sorted, allows duplicates and whose elements can be efficiently referenced by index), then use an ArrayList but when you need to insert an element, always use Collections.binarySearch() to determine the index at which you add a given element. The latter method tells you the index you need to insert at to keep your list in sorted order.

YouTube Autoplay not working

mute=1 or muted=1 as suggested by @Fab will work. However, if you wish to enable autoplay with sound you should add allow="autoplay" to your embedded <iframe>.

<iframe type="text/html" src="https://www.youtube.com/embed/-ePDPGXkvlw?autoplay=1" frameborder="0" allow="autoplay"></iframe>

This is officially supported and documented in Google's Autoplay Policy Changes 2017 post

Iframe delegation A feature policy allows developers to selectively enable and disable use of various browser features and APIs. Once an origin has received autoplay permission, it can delegate that permission to cross-origin iframes with a new feature policy for autoplay. Note that autoplay is allowed by default on same-origin iframes.

<!-- Autoplay is allowed. -->
<iframe src="https://cross-origin.com/myvideo.html" allow="autoplay">

<!-- Autoplay and Fullscreen are allowed. -->
<iframe src="https://cross-origin.com/myvideo.html" allow="autoplay; fullscreen">

When the feature policy for autoplay is disabled, calls to play() without a user gesture will reject the promise with a NotAllowedError DOMException. And the autoplay attribute will also be ignored.

COALESCE with Hive SQL

Since 0.11 hive has a NVL function nvl(T value, T default_value)

which says Returns default value if value is null else returns value

How to open the terminal in Atom?

For Windows follow the below steps

(1)go to file>setting and click on install enter image description here

(2) then type "platformio-ide-terminal" in packages and hit install enter image description here (3) after finish install restart atom and press

 ctrl + ~ for opening the terminal `~` is the key below `Esc`

enter image description here

welcome ;-)

Update multiple rows in same query using PostgreSQL

Based on the solution of @Roman, you can set multiple values:

update users as u set -- postgres FTW
  email = u2.email,
  first_name = u2.first_name,
  last_name = u2.last_name
from (values
  (1, '[email protected]', 'Hollis', 'O\'Connell'),
  (2, '[email protected]', 'Robert', 'Duncan')
) as u2(id, email, first_name, last_name)
where u2.id = u.id;

How to SELECT WHERE NOT EXIST using LINQ?

How about..

var result = (from s in context.Shift join es in employeeshift on s.shiftid equals es.shiftid where es.empid == 57 select s)

Edit: This will give you shifts where there is an associated employeeshift (because of the join). For the "not exists" I'd do what @ArsenMkrt or @hyp suggest

Find the PID of a process that uses a port on Windows

If you want to do this programmatically you can use some of the options given to you as follows in a PowerShell script:

$processPID =  $($(netstat -aon | findstr "9999")[0] -split '\s+')[-1]
taskkill /f /pid $processPID

However; be aware that the more accurate you can be the more precise your PID result will be. If you know which host the port is supposed to be on you can narrow it down a lot. netstat -aon | findstr "0.0.0.0:9999" will only return one application and most llikely the correct one. Only searching on the port number may cause you to return processes that only happens to have 9999 in it, like this:

TCP    0.0.0.0:9999                        0.0.0.0:0       LISTENING       15776
UDP    [fe80::81ad:9999:d955:c4ca%2]:1900  *:*                             12331

The most likely candidate usually ends up first, but if the process has ended before you run your script you may end up with PID 12331 instead and killing the wrong process.

Angularjs: Get element in controller

I dont know what do you exactly mean but hope it help you.
by this directive you can access the DOM element inside controller
this is sample that help you to focus element inside controller

.directive('scopeElement', function () {
    return {
        restrict:"A", // E-Element A-Attribute C-Class M-Comments
        replace: false,
        link: function($scope, elem, attrs) {
            $scope[attrs.scopeElement] = elem[0];
        }
    };
})

now, inside HTML

<input scope-element="txtMessage" >

then, inside controller :

.controller('messageController', ['$scope', function ($scope) {
    $scope.txtMessage.focus();
}])

How to install PyQt5 on Windows?

It can be installed with below simple command:

pip3 install pyqt5

Find the most popular element in int[] array

Array elements value should be less than the array length for this one:

public void findCounts(int[] arr, int n) {
    int i = 0;

    while (i < n) {
        if (arr[i] <= 0) {
            i++;
            continue;
        }

        int elementIndex = arr[i] - 1;

        if (arr[elementIndex] > 0) {
            arr[i] = arr[elementIndex];
            arr[elementIndex] = -1;
        }
        else {
            arr[elementIndex]--;
            arr[i] = 0;
            i++;
        }
    }

    Console.WriteLine("Below are counts of all elements");

    for (int j = 0; j < n; j++) {
        Console.WriteLine(j + 1 + "->" + Math.Abs(arr[j]));
    }
}

Time complexity of this will be O(N) and space complexity will be O(1).

String to HashMap JAVA

USING JAVA 8:

Map<String, String> headerMap = Arrays.stream(header.split(","))
                    .map(s -> s.split(":"))
                    .collect(Collectors.toMap(s -> s[0], s -> s[1]));

How to extract this specific substring in SQL Server?

Assuming they always exist and are not part of your data, this will work:

declare @string varchar(8000) = '23;chair,red [$3]'
select substring(@string, charindex(';', @string) + 1, charindex(' [', @string) - charindex(';', @string) - 1)

Using %f with strftime() in Python to get microseconds

This should do the work

import datetime
datetime.datetime.now().strftime("%H:%M:%S.%f")

It will print

HH:MM:SS.microseconds like this e.g 14:38:19.425961

sendKeys() in Selenium web driver

The simplest solution is Go to Build Path > Configure Build Path > Java Compiler and then select the 'Compiler compliance level:' to the latest one from 1.4 (probably you have this).

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

None of these worked for me (I didn't even try the hacks like manually editing the repo file).

However it worked after a simple yum update -y

C++ static virtual members?

This question is over a decade old, but it looks like it gets a good amount of traffic, so I wanted to post an alternative using modern C++ features that I haven't seen anywhere else.

This solution uses CRTP and SFINAE to perform static dispatching. That, in itself, is nothing new, but all such implementations I've found lack strict signature checking for "overrides." This implementation requires that the "overriding" method signature exactly matches that of the "overridden" method. This behavior more closely resembles that of virtual functions, while also allowing us to effectively overload and "override" a static method.

Note that I put override in quotes because, strictly speaking, we're not technically overriding anything. Instead, we're calling a dispatch method X with signature Y that forwards all of its arguments to T::X, where T is to the first type among a list of types such that T::X exists with signature Y. This list of types considered for dispatching can be anything, but generally would include a default implementation class and the derived class.

Implementation

#include <experimental/type_traits>

template <template <class...> class Op, class... Types>
struct dispatcher;

template <template <class...> class Op, class T>
struct dispatcher<Op, T> : std::experimental::detected_t<Op, T> {};

template <template <class...> class Op, class T, class... Types>
struct dispatcher<Op, T, Types...>
  : std::experimental::detected_or_t<
    typename dispatcher<Op, Types...>::type, Op, T> {};


// Helper to convert a signature to a function pointer
template <class Signature> struct function_ptr;

template <class R, class... Args> struct function_ptr<R(Args...)> {
    using type = R (*)(Args...);
};


// Macro to simplify creation of the dispatcher
// NOTE: This macro isn't smart enough to handle creating an overloaded
//       dispatcher because both dispatchers will try to use the same
//       integral_constant type alias name. If you want to overload, do it
//       manually or make a smarter macro that can somehow put the signature in
//       the integral_constant type alias name.
#define virtual_static_method(name, signature, ...)                            \
    template <class VSM_T>                                                     \
    using vsm_##name##_type = std::integral_constant<                          \
        function_ptr<signature>::type, &VSM_T::name>;                          \
                                                                               \
    template <class... VSM_Args>                                               \
    static auto name(VSM_Args&&... args)                                       \
    {                                                                          \
        return dispatcher<vsm_##name##_type, __VA_ARGS__>::value(              \
            std::forward<VSM_Args>(args)...);                                  \
    }

Example Usage

#include <iostream>

template <class T>
struct Base {
    // Define the default implementations
    struct defaults {
        static std::string alpha() { return "Base::alpha"; };
        static std::string bravo(int) { return "Base::bravo"; }
    };

    // Create the dispatchers
    virtual_static_method(alpha, std::string(void), T, defaults);
    virtual_static_method(bravo, std::string(int), T, defaults);
    
    static void where_are_the_turtles() {
        std::cout << alpha() << std::endl;  // Derived::alpha
        std::cout << bravo(1) << std::endl; // Base::bravo
    }
};

struct Derived : Base<Derived> {
    // Overrides Base::alpha
    static std::string alpha(){ return "Derived::alpha"; }

    // Does not override Base::bravo because signatures differ (even though
    // int is implicitly convertible to bool)
    static std::string bravo(bool){ return "Derived::bravo"; }
};

int main() {
    Derived::where_are_the_turtles();
}

How to filter rows containing a string pattern from a Pandas dataframe

>>> mask = df['ids'].str.contains('ball')    
>>> mask
0     True
1     True
2    False
3     True
Name: ids, dtype: bool

>>> df[mask]
     ids  vals
0  aball     1
1  bball     2
3  fball     4

Subtracting time.Duration from time in Go

In response to Thomas Browne's comment, because lnmx's answer only works for subtracting a date, here is a modification of his code that works for subtracting time from a time.Time type.

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    fmt.Println("now:", now)

    count := 10
    then := now.Add(time.Duration(-count) * time.Minute)
    // if we had fix number of units to subtract, we can use following line instead fo above 2 lines. It does type convertion automatically.
    // then := now.Add(-10 * time.Minute)
    fmt.Println("10 minutes ago:", then)
}

Produces:

now: 2009-11-10 23:00:00 +0000 UTC
10 minutes ago: 2009-11-10 22:50:00 +0000 UTC

Not to mention, you can also use time.Hour or time.Second instead of time.Minute as per your needs.

Playground: https://play.golang.org/p/DzzH4SA3izp

Add directives from directive in AngularJS

In cases where you have multiple directives on a single DOM element and where the order in which they’re applied matters, you can use the priority property to order their application. Higher numbers run first. The default priority is 0 if you don’t specify one.

EDIT: after the discussion, here's the complete working solution. The key was to remove the attribute: element.removeAttr("common-things");, and also element.removeAttr("data-common-things"); (in case users specify data-common-things in the html)

angular.module('app')
  .directive('commonThings', function ($compile) {
    return {
      restrict: 'A',
      replace: false, 
      terminal: true, //this setting is important, see explanation below
      priority: 1000, //this setting is important, see explanation below
      compile: function compile(element, attrs) {
        element.attr('tooltip', '{{dt()}}');
        element.attr('tooltip-placement', 'bottom');
        element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
        element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html

        return {
          pre: function preLink(scope, iElement, iAttrs, controller) {  },
          post: function postLink(scope, iElement, iAttrs, controller) {  
            $compile(iElement)(scope);
          }
        };
      }
    };
  });

Working plunker is available at: http://plnkr.co/edit/Q13bUt?p=preview

Or:

angular.module('app')
  .directive('commonThings', function ($compile) {
    return {
      restrict: 'A',
      replace: false,
      terminal: true,
      priority: 1000,
      link: function link(scope,element, attrs) {
        element.attr('tooltip', '{{dt()}}');
        element.attr('tooltip-placement', 'bottom');
        element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
        element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html

        $compile(element)(scope);
      }
    };
  });

DEMO

Explanation why we have to set terminal: true and priority: 1000 (a high number):

When the DOM is ready, angular walks the DOM to identify all registered directives and compile the directives one by one based on priority if these directives are on the same element. We set our custom directive's priority to a high number to ensure that it will be compiled first and with terminal: true, the other directives will be skipped after this directive is compiled.

When our custom directive is compiled, it will modify the element by adding directives and removing itself and use $compile service to compile all the directives (including those that were skipped).

If we don't set terminal:true and priority: 1000, there is a chance that some directives are compiled before our custom directive. And when our custom directive uses $compile to compile the element => compile again the already compiled directives. This will cause unpredictable behavior especially if the directives compiled before our custom directive have already transformed the DOM.

For more information about priority and terminal, check out How to understand the `terminal` of directive?

An example of a directive that also modifies the template is ng-repeat (priority = 1000), when ng-repeat is compiled, ng-repeat make copies of the template element before other directives get applied.

Thanks to @Izhaki's comment, here is the reference to ngRepeat source code: https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js

Adding placeholder attribute using Jquery

This line of code might not work in IE 8 because of native support problems.

$(".hidden").attr("placeholder", "Type here to search");

You can try importing a JQuery placeholder plugin for this task. Simply import it to your libraries and initiate from the sample code below.

$('input, textarea').placeholder();

Which sort algorithm works best on mostly sorted data?

Dijkstra's smoothsort is a great sort on already-sorted data. It's a heapsort variant that runs in O(n lg n) worst-case and O(n) best-case. I wrote an analysis of the algorithm, in case you're curious how it works.

Natural mergesort is another really good one for this - it's a bottom-up mergesort variant that works by treating the input as the concatenation of multiple different sorted ranges, then using the merge algorithm to join them together. You repeat this process until all of the input range is sorted. This runs in O(n) time if the data is already sorted and O(n lg n) worst-case. It's very elegant, though in practice it isn't as good as some other adaptive sorts like Timsort or smoothsort.

How can I write data attributes using Angular?

About access

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

And

get_data(event) {
   console.log(event.target.dataset.sectionvalue)
}

IF... OR IF... in a windows batch file

Realizing this is a bit of an old question, the responses helped me come up with a solution to testing command line arguments to a batch file; so I wanted to post my solution as well in case anyone else was looking for a similar solution.

First thing that I should point out is that I was having trouble getting IF ... ELSE statements to work inside of a FOR ... DO clause. Turns out (thanks to dbenham for inadvertently pointing this out in his examples) the ELSE statement cannot be on a separate line from the closing parens.

So instead of this:

FOR ... DO (
    IF ... (
    )
    ELSE (
    )
)

Which is my preference for readability and aesthetic reasons, you have to do this:

FOR ... DO (
    IF ... (
    ) ELSE (
    )
)

Now the ELSE statement doesn't return as an unrecognized command.

Finally, here's what I was attempting to do - I wanted to be able to pass several arguments to a batch file in any order, ignoring case, and reporting/failing on undefined arguments passed in. So here's my solution...

@ECHO OFF
SET ARG1=FALSE
SET ARG2=FALSE
SET ARG3=FALSE
SET ARG4=FALSE
SET ARGS=(arg1 Arg1 ARG1 arg2 Arg2 ARG2 arg3 Arg3 ARG3)
SET ARG=

FOR %%A IN (%*) DO (
    SET TRUE=
    FOR %%B in %ARGS% DO (
        IF [%%A] == [%%B] SET TRUE=1
        )
    IF DEFINED TRUE (
        SET %%A=TRUE
        ) ELSE (
        SET ARG=%%A
        GOTO UNDEFINED
        )
    )

ECHO %ARG1%
ECHO %ARG2%
ECHO %ARG3%
ECHO %ARG4%
GOTO END

:UNDEFINED
ECHO "%ARG%" is not an acceptable argument.
GOTO END

:END

Note, this will only report on the first failed argument. So if the user passes in more than one unacceptable argument, they will only be told about the first until it's corrected, then the second, etc.

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

I tried using phyatt's AspectRatioPixmapLabel class, but experienced a few problems:

  • Sometimes my app entered an infinite loop of resize events. I traced this back to the call of QLabel::setPixmap(...) inside the resizeEvent method, because QLabel actually calls updateGeometry inside setPixmap, which may trigger resize events...
  • heightForWidth seemed to be ignored by the containing widget (a QScrollArea in my case) until I started setting a size policy for the label, explicitly calling policy.setHeightForWidth(true)
  • I want the label to never grow more than the original pixmap size
  • QLabel's implementation of minimumSizeHint() does some magic for labels containing text, but always resets the size policy to the default one, so I had to overwrite it

That said, here is my solution. I found that I could just use setScaledContents(true) and let QLabel handle the resizing. Of course, this depends on the containing widget / layout honoring the heightForWidth.

aspectratiopixmaplabel.h

#ifndef ASPECTRATIOPIXMAPLABEL_H
#define ASPECTRATIOPIXMAPLABEL_H

#include <QLabel>
#include <QPixmap>

class AspectRatioPixmapLabel : public QLabel
{
    Q_OBJECT
public:
    explicit AspectRatioPixmapLabel(const QPixmap &pixmap, QWidget *parent = 0);
    virtual int heightForWidth(int width) const;
    virtual bool hasHeightForWidth() { return true; }
    virtual QSize sizeHint() const { return pixmap()->size(); }
    virtual QSize minimumSizeHint() const { return QSize(0, 0); }
};

#endif // ASPECTRATIOPIXMAPLABEL_H

aspectratiopixmaplabel.cpp

#include "aspectratiopixmaplabel.h"

AspectRatioPixmapLabel::AspectRatioPixmapLabel(const QPixmap &pixmap, QWidget *parent) :
    QLabel(parent)
{
    QLabel::setPixmap(pixmap);
    setScaledContents(true);
    QSizePolicy policy(QSizePolicy::Maximum, QSizePolicy::Maximum);
    policy.setHeightForWidth(true);
    this->setSizePolicy(policy);
}

int AspectRatioPixmapLabel::heightForWidth(int width) const
{
    if (width > pixmap()->width()) {
        return pixmap()->height();
    } else {
        return ((qreal)pixmap()->height()*width)/pixmap()->width();
    }
}

How to navigate back to the last cursor position in Visual Studio Code?

?+U Undo last cursor operation

You can also try ctrl+-

BTW all the shortcuts is here https://code.visualstudio.com/shortcuts/keyboard-shortcuts-macos.pdf This is really useful!

How do I set a background-color for the width of text, not the width of the entire element, using CSS?

Try this one:

h1 {
    text-align: center;
    background-color: green;
    visibility: hidden;
}

h1:after {
    content:'The Last Will and Testament of Eric Jones';
    visibility: visible;
    display: block;
    position: absolute;
    background-color: inherit;
    padding: 5px;
    top: 10px;
    left: calc(30% - 5px);
}

Please note that calc is not compatible to all browsers :) Just want to be consistent with the alignment in the original post.

https://jsfiddle.net/richardferaro/ssyc04o4/

jQuery UI Datepicker - Multiple Date Selections

Use this plugin http://multidatespickr.sourceforge.net

  • Select date ranges.
  • Pick multiple dates not in secuence.
  • Define a maximum number of pickable dates.
  • Define a range X days from where it is possible to select Y dates. Define unavailable dates

jquery to change style attribute of a div class

if you just want to set the style attribute use

$('.handle').attr('style','left: 300px');

Or you can use css method of jQuery to set only one css style property

$('.handle').css('left', '300px');

OR same as key value

$('.handle').css({'left': '300px', position});

More info on W3schools

How to send json data in POST request using C#

This works for me.

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://url");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
using (var streamWriter = new 

StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
                {
                    Username = "myusername",
                    Password = "password"
                });

    streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

ng-mouseover and leave to toggle item using mouse in angularjs

Angular solution

You can fix it like this:

$scope.hoverIn = function(){
    this.hoverEdit = true;
};

$scope.hoverOut = function(){
    this.hoverEdit = false;
};

Inside of ngMouseover (and similar) functions context is a current item scope, so this refers to the current child scope.

Also you need to put ngRepeat on li:

<ul>
    <li ng-repeat="task in tasks" ng-mouseover="hoverIn()" ng-mouseleave="hoverOut()">
        {{task.name}}
        <span ng-show="hoverEdit">
            <a>Edit</a>
        </span>
    </li>
</ul>

Demo

CSS solution

However, when possible try to do such things with CSS only, this would be the optimal solution and no JS required:

ul li span {display: none;}
ul li:hover span {display: inline;}

How do I run Redis on Windows?

I am using Memurai which is Redis-compatible cache and datastore for Windows. It is also recommended by Microsoft open tech as it written on their former project here.

This project is no longer being actively maintained. If you are looking for a Windows version of Redis, you may want to check out Memurai. Please note that Microsoft is not officially endorsing this product in any way.

What represents a double in sql server?

float

Or if you want to go old-school:

real

You can also use float(53), but it means the same thing as float.

("real" is equivalent to float(24), not float/float(53).)

The decimal(x,y) SQL Server type is for when you want exact decimal numbers rather than floating point (which can be approximations). This is in contrast to the C# "decimal" data type, which is more like a 128-bit floating point number.

MSSQL's float type is equivalent to the 64-bit double type in .NET. (My original answer from 2011 said there could be a slight difference in mantissa, but I've tested this in 2020 and they appear to be 100% compatible in their binary representation of both very small and very large numbers -- see https://dotnetfiddle.net/wLX5Ox for my test).

To make things more confusing, a "float" in C# is only 32-bit, so it would be more equivalent in SQL to the real/float(24) type in MSSQL than float/float(53).

In your specific use case... All you need is 5 places after the decimal point to represent latitude and longitude within about one-meter precision, and you only need up to three digits before the decimal point for the degrees. Float(24) or decimal(8,5) will best fit your needs in MSSQL, and using float in C# is good enough, you don't need double. In fact, your users will probably thank you for rounding to 5 decimal places rather than having a bunch of insignificant digits coming along for the ride.

How to let PHP to create subdomain automatically for each user?

I just wanted to add, that if you use CloudFlare (free), you can use their API to manage your dns with ease.

How to percent-encode URL parameters in Python?

Python 2

From the docs:

urllib.quote(string[, safe])

Replace special characters in string using the %xx escape. Letters, digits, and the characters '_.-' are never quoted. By default, this function is intended for quoting the path section of the URL.The optional safe parameter specifies additional characters that should not be quoted — its default value is '/'

That means passing '' for safe will solve your first issue:

>>> urllib.quote('/test')
'/test'
>>> urllib.quote('/test', safe='')
'%2Ftest'

About the second issue, there is a bug report about it here. Apparently it was fixed in python 3. You can workaround it by encoding as utf8 like this:

>>> query = urllib.quote(u"Müller".encode('utf8'))
>>> print urllib.unquote(query).decode('utf8')
Müller

By the way have a look at urlencode

Python 3

The same, except replace urllib.quote with urllib.parse.quote.

Regular expression for a hexadecimal number?

If you are looking for an specific hex character in the middle of the string, you can use "\xhh" where hh is the character in hexadecimal. I've tried and it works. I use framework for C++ Qt but it can solve problems in other cases, depends on the flavor you need to use (php, javascript, python , golang, etc.).

This answer was taken from:http://ult-tex.net/info/perl/

How can I use a search engine to search for special characters?

This search engine was made to solve exactly the kind of problem you're having: http://symbolhound.com/

I am the developer of SymbolHound.

Insert multiple rows with one query MySQL

While inserting multiple rows with a single INSERT statement is generally faster, it leads to a more complicated and often unsafe code. Below I present the best practices when it comes to inserting multiple records in one go using PHP.

To insert multiple new rows into the database at the same time, one needs to follow the following 3 steps:

  1. Start transaction (disable autocommit mode)
  2. Prepare INSERT statement
  3. Execute it multiple times

Using database transactions ensures that the data is saved in one piece and significantly improves performance.

How to properly insert multiple rows using PDO

PDO is the most common choice of database extension in PHP and inserting multiple records with PDO is quite simple.

$pdo = new \PDO("mysql:host=localhost;dbname=test;charset=utf8mb4", 'user', 'password', [
    \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES => false
]);

// Start transaction
$pdo->beginTransaction();

// Prepare statement
$stmt = $pdo->prepare('INSERT 
    INTO `pxlot` (realname,email,address,phone,status,regtime,ip) 
    VALUES (?,?,?,?,?,?,?)');

// Perform execute() inside a loop
// Sample data coming from a fictitious data set, but the data can come from anywhere
foreach ($dataSet as $data) {
    // All seven parameters are passed into the execute() in a form of an array
    $stmt->execute([$data['name'], $data['email'], $data['address'], getPhoneNo($data['name']), '0', $data['regtime'], $data['ip']]);
}

// Commit the data into the database
$pdo->commit();

How to properly insert multiple rows using mysqli

The mysqli extension is a little bit more cumbersome to use but operates on very similar principles. The function names are different and take slightly different parameters.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'user', 'password', 'database');
$mysqli->set_charset('utf8mb4');

// Start transaction
$mysqli->begin_transaction();

// Prepare statement
$stmt = $mysqli->prepare('INSERT 
    INTO `pxlot` (realname,email,address,phone,status,regtime,ip) 
    VALUES (?,?,?,?,?,?,?)');

// Perform execute() inside a loop
// Sample data coming from a fictitious data set, but the data can come from anywhere
foreach ($dataSet as $data) {
    // mysqli doesn't accept bind in execute yet, so we have to bind the data first
    // The first argument is a list of letters denoting types of parameters. It's best to use 's' for all unless you need a specific type
    // bind_param doesn't accept an array so we need to unpack it first using '...'
    $stmt->bind_param('sssssss', ...[$data['name'], $data['email'], $data['address'], getPhoneNo($data['name']), '0', $data['regtime'], $data['ip']]);
    $stmt->execute();
}

// Commit the data into the database
$mysqli->commit();

Performance

Both extensions offer the ability to use transactions. Executing prepared statement with transactions greatly improves performance, but it's still not as good as a single SQL query. However, the difference is so negligible that for the sake of conciseness and clean code it is perfectly acceptable to execute prepared statements multiple times. If you need a faster option to insert many records into the database at once, then chances are that PHP is not the right tool.

Command output redirect to file and terminal

Yes, if you redirect the output, it won't appear on the console. Use tee.

ls 2>&1 | tee /tmp/ls.txt

Update Tkinter Label from variable

Maybe I'm not understanding the question but here is my simple solution that works -

# I want to Display total heads bent this machine so I define a label -
TotalHeadsLabel3 = Label(leftFrame)
TotalHeadsLabel3.config(font=Helv12,fg='blue',text="Total heads " + str(TotalHeads))
TotalHeadsLabel3.pack(side=TOP)

# I update the int variable adding the quantity bent -
TotalHeads = TotalHeads + headQtyBent # update ready to write to file & display
TotalHeadsLabel3.config(text="Total Heads "+str(TotalHeads)) # update label with new qty

I agree that labels are not automatically updated but can easily be updated with the

<label name>.config(text="<new text>" + str(<variable name>))

That just needs to be included in your code after the variable is updated.

How to add include and lib paths to configure/make cycle?

This took a while to get right. I had this issue when cross-compiling in Ubuntu for an ARM target. I solved it with:

PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib ./autogen.sh --build=`config.guess` --host=armv5tejl-unknown-linux-gnueabihf

Notice CFLAGS is not used with autogen.sh/configure, using it gave me the error: "configure: error: C compiler cannot create executables". In the build environment I was using an autogen.sh script was provided, if you don't have an autogen.sh script substitute ./autogen.sh with ./configure in the command above. I ran config.guess on the target system to get the --host parameter.

After successfully running autogen.sh/configure, compile with:

PATH=$PATH:/ccpath/bin CC=ccname-gcc AR=ccname-ar LD=ccname-ld CPPFLAGS="-nostdinc -I/ccrootfs/usr/include ..." LDFLAGS=-L/ccrootfs/usr/lib CFLAGS="-march=... -mcpu=... etc." make

The CFLAGS I chose to use were: "-march=armv5te -fno-tree-vectorize -mthumb-interwork -mcpu=arm926ej-s". It will take a while to get all of the include directories set up correctly: you might want some includes pointing to your cross-compiler and some pointing to your root file system includes, and there will likely be some conflicts.

I'm sure this is not the perfect answer. And I am still seeing some include directories pointing to / and not /ccrootfs in the Makefiles. Would love to know how to correct this. Hope this helps someone.

One line if-condition-assignment

If one line code is definitely going to happen for you, Python 3.8 introduces assignment expressions affectionately known as “the walrus operator”.

:=

someBoolValue and (num := 20)

The 20 will be assigned to num if the first boolean expression is True. The assignment must be inside parentheses here otherwise you will get a syntax error.

num = 10
someBoolValue = True

someBoolValue and (num := 20)
print(num) # 20

num = 10
someBoolValue = False

someBoolValue and (num := 20)
print(num) # 10

JSLint is suddenly reporting: Use the function form of "use strict"

This is how simple it is: If you want to be strict with all your code, add "use strict"; at the start of your JavaScript.

But if you only want to be strict with some of your code, use the function form. Anyhow, I would recomend you to use it at the beginning of your JavaScript because this will help you be a better coder.

Error With Port 8080 already in use

It has been long time, but I faced the same Issue, and solved it as follow: 1. tried shutting down the application server using the shutdown.bat/.bash which might be in your application Server / bin/shutdown..

  1. My Issue, was that more than 1 instance of java was running, I was changing ports, and not looking back, so it kept running other java processes, with that specific port. for windows users, : ALT+Shift+Esc, and end java processes that you are not using and now you should be able to re-use your port 8080