Programs & Examples On #Ultracombo

Component of the Infragistics NetAdvantage suite to provide the same functionality as a ComboBox control but provides a grid like drop-down list that allows for multiple columns of data to be shown.

Changing all files' extensions in a folder with one command on Windows

on CMD

type

ren *.* *.jpg

. will select all files, and rename to * (what ever name they have) plus extension to jpg

android.view.InflateException: Binary XML file: Error inflating class fragment

I think the basic problem is with "android:targetSdkVersion" which is defined in AndroidManifest.xml. In my case, the initial value which I have defined as:

android:targetSdkVersion=16

I changed it to:

android:targetSdkVersion=22

which resolved my all of the error. So, setting up the correct "targetSdkVersion" is also important before building an android app.

"message failed to fetch from registry" while trying to install any module

I had this issue with npm v1.1.4 (and node v0.6.12), which are the Ubuntu 12.04 repository versions.

It looks like that version of npm isn't supported any more, updating node (and npm with it) resolved the issue.

First, uninstall the outdated version (optional, but I think this fixed an issue I was having with global modules not being pathed in).

sudo apt-get purge nodejs npm

Then enable nodesource's repo and install:

curl -sL https://deb.nodesource.com/setup | sudo bash -
sudo apt-get install -y nodejs

Note - the previous advice was to use Chris Lea's repo, he's now migrated that to nodesource, see:

From: here

How to get file_get_contents() to work with HTTPS?

In my case, the issue was due to WAMP using a different php.ini for CLI than Apache, so your settings made through the WAMP menu don't apply to CLI. Just modify the CLI php.ini and it works.

Build fails with "Command failed with a nonzero exit code"

For me cleaning the project (Command + Shift + K) and restarting xCode worked for me

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

mysql -> insert into tbl (select from another table) and some default values

If you want to insert all the columns then

insert into def select * from abc;

here the number of columns in def should be equal to abc.

if you want to insert the subsets of columns then

insert into def (col1,col2, col3 ) select scol1,scol2,scol3 from abc; 

if you want to insert some hardcorded values then

insert into def (col1, col2,col3) select 'hardcoded value',scol2, scol3 from abc;

Java Currency Number format

I know this is an old question but...

import java.text.*;

public class FormatCurrency
{
    public static void main(String[] args)
    {
        double price = 123.4567;
        DecimalFormat df = new DecimalFormat("#.##");
        System.out.print(df.format(price));
    }
}

Join vs. sub-query

I just thinking about the same problem, but I am using subquery in the FROM part. I need connect and query from large tables, the "slave" table have 28 million record but the result is only 128 so small result big data! I am using MAX() function on it.

First I am using LEFT JOIN because I think that is the correct way, the mysql can optimalize etc. Second time just for testing, I rewrite to sub-select against the JOIN.

LEFT JOIN runtime: 1.12s SUB-SELECT runtime: 0.06s

18 times faster the subselect than the join! Just in the chokito adv. The subselect looks terrible but the result ...

Why is vertical-align:text-top; not working in CSS

vertical-align is only supposed to work on elements that are rendered as inline. <span> is rendered as inline by default, but not all elements are. The paragraph block element, <p>, is rendered as a block by default. Table render types (e.g. table-cell) will allow you to use vertical-align as well.

Some browsers may allow you to use the vertical-align CSS property on items such as the paragraph block, but they are not supposed to. Text denoted as a paragraph should be filled with written-language content or the mark-up is incorrect and should be using one of a number of other options instead.

I hope this helps!

How can I rotate an HTML <div> 90 degrees?

We can add the following to a particular tag in CSS:

-webkit-transform: rotate(90deg);
-moz-transform: rotate(90deg);
-o-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);

In case of half rotation change 90 to 45.

Warning: mysqli_query() expects at least 2 parameters, 1 given. What?

The issue is that you're not saving the mysqli connection. Change your connect to:

$aVar = mysqli_connect('localhost','tdoylex1_dork','dorkk','tdoylex1_dork');

And then include it in your query:

$query1 = mysqli_query($aVar, "SELECT name1 FROM users
    ORDER BY RAND()
    LIMIT 1");
$aName1 = mysqli_fetch_assoc($query1);
$name1 = $aName1['name1'];

Also don't forget to enclose your connections variables as strings as I have above. This is what's causing the error but you're using the function wrong, mysqli_query returns a query object but to get the data out of this you need to use something like mysqli_fetch_assoc http://php.net/manual/en/mysqli-result.fetch-assoc.php to actually get the data out into a variable as I have above.

Git fast forward VS no fast forward merge

The --no-ff option is useful when you want to have a clear notion of your feature branch. So even if in the meantime no commits were made, FF is possible - you still want sometimes to have each commit in the mainline correspond to one feature. So you treat a feature branch with a bunch of commits as a single unit, and merge them as a single unit. It is clear from your history when you do feature branch merging with --no-ff.

If you do not care about such thing - you could probably get away with FF whenever it is possible. Thus you will have more svn-like feeling of workflow.

For example, the author of this article thinks that --no-ff option should be default and his reasoning is close to that I outlined above:

Consider the situation where a series of minor commits on the "feature" branch collectively make up one new feature: If you just do "git merge feature_branch" without --no-ff, "it is impossible to see from the Git history which of the commit objects together have implemented a feature—you would have to manually read all the log messages. Reverting a whole feature (i.e. a group of commits), is a true headache [if --no-ff is not used], whereas it is easily done if the --no-ff flag was used [because it's just one commit]."

Graphic showing how --no-ff groups together all commits from feature branch into one commit on master branch

How to get user's high resolution profile picture on Twitter?

use this URL : "https://twitter.com/(userName)/profile_image?size=original"

If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient, using TWTRAuthSession.

This is the code snipe for iOS:

if let twitterId = session.userID{
   let twitterClient = TWTRAPIClient(userID: twitterId)
   twitterClient.loadUser(withID: twitterId) {(user, error) in
       if let userName = user?.screenName{
          let url = "https://twitter.com/\(userName)/profile_image?size=original")
       }
   }
}

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

For the benefit of searchers looking to solve a similar problem, you can get a similar error if your input is an empty string.

e.g.

var d = "";
var json = JSON.parse(d);

or if you are using AngularJS

var d = "";
var json = angular.fromJson(d);

In chrome it resulted in 'Uncaught SyntaxError: Unexpected end of input', but Firebug showed it as 'JSON.parse: unexpected end of data at line 1 column 1 of the JSON data'.

Sure most people won't be caught out by this, but I hadn't protected the method and it resulted in this error.

Auto detect mobile browser (via user-agent?)

for ANDROID , IPHONE, IPAD, BLACKBERRY, PALM, WINDOWS CE, PALM

 <script language="javascript"> <!--
     var mobile = (/iphone|ipad|ipod|android|blackberry|mini|windows\sce|palm/i.test(navigator.userAgent.toLowerCase()));
              if (mobile) {
                  alert("MOBILE DEVICE DETECTED");
                  document.write("<b>------------------------------------------<br>")
                  document.write("<b>" + navigator.userAgent + "<br>")
                  document.write("<b>------------------------------------------<br>")
                  var userAgent = navigator.userAgent.toLowerCase();
                  if ((userAgent.search("android") > -1) && (userAgent.search("mobile") > -1))
                         document.write("<b> ANDROID MOBILE <br>")
                   else if ((userAgent.search("android") > -1) && !(userAgent.search("mobile") > -1))
                       document.write("<b> ANDROID TABLET <br>")
                   else if ((userAgent.search("blackberry") > -1))
                       document.write("<b> BLACKBERRY DEVICE <br>")
                   else if ((userAgent.search("iphone") > -1))
                       document.write("<b> IPHONE DEVICE <br>")              
                   else if ((userAgent.search("ipod") > -1))
                       document.write("<b> IPOD DEVICE <br>")
               else if ((userAgent.search("ipad") > -1))
                       document.write("<b> IPAD DEVICE <br>")
                       else
                   document.write("<b> UNKNOWN DEVICE <br>")
              }
              else
                  alert("NO MOBILE DEVICE DETECTED"); //--> </script>

Unable to show a Git tree in terminal

A solution is to create an Alias in your .gitconfig and call it easily:

[alias]
    tree = log --graph --decorate --pretty=oneline --abbrev-commit

And when you call it next time, you'll use:

git tree

To put it in your ~/.gitconfig without having to edit it, you can do:

git config --global alias.tree "log --graph --decorate --pretty=oneline --abbrev-commit"  

(If you don't use the --global it will put it in the .git/config of your current repo.)

Pip "Could not find a that satisfies the requirement"

pygame is not distributed via pip. See this link which provides windows binaries ready for installation.

  1. Install python
  2. Make sure you have python on your PATH
  3. Download the appropriate wheel from this link
  4. Install pip using this tutorial
  5. Finally, use these commands to install pygame wheel with pip

    • Python 2 (usually called pip)

      • pip install file.whl
    • Python 3 (usually called pip3)

      • pip3 install file.whl

Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit

What is the difference between signed and unsigned variables?

Unsigned variables can only be positive numbers, because they lack the ability to indicate that they are negative.

This ability is called the 'sign' or 'signing bit'.

A side effect is that without a signing bit, they have one more bit that can be used to represent the number, doubling the maximum number it can represent.

jquery onclick change css background image

Use your jquery like this

$('.home').css({'background-image':'url(images/tabs3.png)'});

Python code to remove HTML tags from a string

Note that this isn't perfect, since if you had something like, say, <a title=">"> it would break. However, it's about the closest you'd get in non-library Python without a really complex function:

import re

TAG_RE = re.compile(r'<[^>]+>')

def remove_tags(text):
    return TAG_RE.sub('', text)

However, as lvc mentions xml.etree is available in the Python Standard Library, so you could probably just adapt it to serve like your existing lxml version:

def remove_tags(text):
    return ''.join(xml.etree.ElementTree.fromstring(text).itertext())

How to correctly save instance state of Fragments in back stack?

On the latest support library none of the solutions discussed here are necessary anymore. You can play with your Activity's fragments as you like using the FragmentTransaction. Just make sure that your fragments can be identified either with an id or tag.

The fragments will be restored automatically as long as you don't try to recreate them on every call to onCreate(). Instead, you should check if savedInstanceState is not null and find the old references to the created fragments in this case.

Here is an example:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
        myFragment = MyFragment.newInstance();
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.my_container, myFragment, MY_FRAGMENT_TAG)
                .commit();
    } else {
        myFragment = (MyFragment) getSupportFragmentManager()
                .findFragmentByTag(MY_FRAGMENT_TAG);
    }
...
}

Note however that there is currently a bug when restoring the hidden state of a fragment. If you are hiding fragments in your activity, you will need to restore this state manually in this case.

How to sort an STL vector?

A pointer-to-member allows you to write a single comparator, which can work with any data member of your class:

#include <algorithm>
#include <vector>
#include <string>
#include <iostream>

template <typename T, typename U>
struct CompareByMember {
    // This is a pointer-to-member, it represents a member of class T
    // The data member has type U
    U T::*field;
    CompareByMember(U T::*f) : field(f) {}
    bool operator()(const T &lhs, const T &rhs) {
        return lhs.*field < rhs.*field;
    }
};

struct Test {
    int a;
    int b;
    std::string c;
    Test(int a, int b, std::string c) : a(a), b(b), c(c) {}
};

// for convenience, this just lets us print out a Test object
std::ostream &operator<<(std::ostream &o, const Test &t) {
    return o << t.c;
}

int main() {
    std::vector<Test> vec;
    vec.push_back(Test(1, 10, "y"));
    vec.push_back(Test(2, 9, "x"));

    // sort on the string field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,std::string>(&Test::c));
    std::cout << "sorted by string field, c: ";
    std::cout << vec[0] << " " << vec[1] << "\n";

    // sort on the first integer field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,int>(&Test::a));
    std::cout << "sorted by integer field, a: ";
    std::cout << vec[0] << " " << vec[1] << "\n";

    // sort on the second integer field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,int>(&Test::b));
    std::cout << "sorted by integer field, b: ";
    std::cout << vec[0] << " " << vec[1] << "\n";
}

Output:

sorted by string field, c: x y
sorted by integer field, a: y x
sorted by integer field, b: x y

How could I put a border on my grid control in WPF?

If someone is interested in the similar problem, but is not working with XAML, here's my solution:

var B1 = new Border();
B1.BorderBrush = Brushes.Black;
B1.BorderThickness = new Thickness(0, 1, 0, 0); // You can specify here which borders do you want
YourPanel.Children.Add(B1);

How to access session variables from any class in ASP.NET?

The problem with the solution suggested is that it can break some performance features built into the SessionState if you are using an out-of-process session storage. (either "State Server Mode" or "SQL Server Mode"). In oop modes the session data needs to be serialized at the end of the page request and deserialized at the beginning of the page request, which can be costly. To improve the performance the SessionState attempts to only deserialize what is needed by only deserialize variable when it is accessed the first time, and it only re-serializes and replaces variable which were changed. If you have alot of session variable and shove them all into one class essentially everything in your session will be deserialized on every page request that uses session and everything will need to be serialized again even if only 1 property changed becuase the class changed. Just something to consider if your using alot of session and an oop mode.

How do I make JavaScript beep?

Using CSS you can do it if you add the following style to a tag, but you will need a wav file:

<style type="text/css">
        .beep {cue: url("beep.wav") }
</style>

var body=document.getElementByTagName("body");
body.className=body.className + " " + "beep";

Is there a goto statement in Java?

James Gosling created the original JVM with support of goto statements, but then he removed this feature as needless. The main reason goto is unnecessary is that usually it can be replaced with more readable statements (like break/continue) or by extracting a piece of code into a method.

Source: James Gosling, Q&A session

'' is not recognized as an internal or external command, operable program or batch file

This is a very common question seen on Stackoverflow.

The important part here is not the command displayed in the error, but what the actual error tells you instead.

a Quick breakdown on why this error is received.

cmd.exe Being a terminal window relies on input and system Environment variables, in order to perform what you request it to do. it does NOT know the location of everything and it also does not know when to distinguish between commands or executable names which are separated by whitespace like space and tab or commands with whitespace as switch variables.

How do I fix this:

When Actual Command/executable fails

First we make sure, is the executable actually installed? If yes, continue with the rest, if not, install it first.

If you have any executable which you are attempting to run from cmd.exe then you need to tell cmd.exe where this file is located. There are 2 ways of doing this.

  1. specify the full path to the file.

    "C:\My_Files\mycommand.exe"

  2. Add the location of the file to your environment Variables.

Goto:
------> Control Panel-> System-> Advanced System Settings->Environment Variables

In the System Variables Window, locate path and select edit

Now simply add your path to the end of the string, seperated by a semicolon ; as:

;C:\My_Files\

Save the changes and exit. You need to make sure that ANY cmd.exe windows you had open are then closed and re-opened to allow it to re-import the environment variables. Now you should be able to run mycommand.exe from any path, within cmd.exe as the environment is aware of the path to it.

When C:\Program or Similar fails

This is a very simple error. Each string after a white space is seen as a different command in cmd.exe terminal, you simply have to enclose the entire path in double quotes in order for cmd.exe to see it as a single string, and not separate commands.

So to execute C:\Program Files\My-App\Mobile.exe simply run as:

"C:\Program Files\My-App\Mobile.exe"

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

I tried this in my Angular project and it worked fine without jQuery.

<input type='text' ng-paste='preventPaste($event)'>

And in script part:

$scope.preventPaste = function(e){
   e.preventDefault();
   return false;
};

In non angular project, use 'onPaste' instead of 'ng-paste' and 'event' instesd of '$event'.

How to suppress "error TS2533: Object is possibly 'null' or 'undefined'"?

This is rather verbose and don't like it but it's the only thing that worked for me:

if (inputFile && inputFile.current) {
        ((inputFile.current as never) as HTMLInputElement).click()
}

only

if (inputFile && inputFile.current) {
        inputFile.current.click() // also with ! or ? didn't work
}

didn't work for me. Typesript version: 3.9.7 with eslint and recommended rules.

ORACLE: Updating multiple columns at once

I guess the issue here is that you are updating INV_DISCOUNT and the INV_TOTAL uses the INV_DISCOUNT. so that is the issue here. You can use returning clause of update statement to use the new INV_DISCOUNT and use it to update INV_TOTAL.

this is a generic example let me know if this explains the point i mentioned

CREATE OR REPLACE PROCEDURE SingleRowUpdateReturn
IS
    empName VARCHAR2(50);
    empSalary NUMBER(7,2);      
BEGIN
    UPDATE emp
    SET sal = sal + 1000
    WHERE empno = 7499
    RETURNING ename, sal
    INTO empName, empSalary;

    DBMS_OUTPUT.put_line('Name of Employee: ' || empName);
    DBMS_OUTPUT.put_line('New Salary: ' || empSalary);
END;

Asp.net - <customErrors mode="Off"/> error when trying to access working webpage

For example in my case I accidentaly changed role of some users to incorrect, and my application got error during starting (NullReferenceException). When I fixed it - the app starts fine.

Is there a "previous sibling" selector?

Removing the styles of next siblings on hover, so that it looks like only previous siblings have styles added on hover.

_x000D_
_x000D_
ul li {
  color: red;
  cursor: pointer;
}

ul:hover li {
  color: blue;
}

ul:hover li:hover ~ li{
  color: red;
}
_x000D_
<ul>
    <li>item 1</li>
    <li>item 2</li>
    <li>item 3</li>
</ul>
_x000D_
_x000D_
_x000D_

How to create empty data frame with column names specified in R?

Perhaps:

> data.frame(aname=NA, bname=NA)[numeric(0), ]
[1] aname bname
<0 rows> (or 0-length row.names)

SQL query to make all data in a column UPPER CASE?

Permanent:

UPDATE
  MyTable
SET
  MyColumn = UPPER(MyColumn)

Temporary:

SELECT
  UPPER(MyColumn) AS MyColumn
FROM
  MyTable

Babel command not found

This is what I've done to automatically add my local project node_modules/.bin path to PATH. In ~/.profile I added:

if [ -d "$PWD/node_modules/.bin" ]; then 
    PATH="$PWD/node_modules/.bin"
fi

Then reload your bash profile: source ~/.profile

Cordova - Error code 1 for command | Command failed for

I removed android platforms and installed again then worked. I wrote these lines in command window:

cordova platform remove android
then
cordova platform add android

Trim leading and trailing spaces from a string in awk

just use a regex as a separator:

', *' - for leading spaces

' *,' - for trailing spaces

for both leading and trailing:

awk -F' *,? *' '{print $1","$2}' input.txt

Percentage width in a RelativeLayout

You cannot use percentages to define the dimensions of a View inside a RelativeLayout. The best ways to do it is to use LinearLayout and weights, or a custom Layout.

Add row to query result using select

You use it like this:

SELECT  age, name
FROM    users
UNION
SELECT  25 AS age, 'Betty' AS name

Use UNION ALL to allow duplicates: if there is a 25-years old Betty among your users, the second query will not select her again with mere UNION.

How do I disable a jquery-ui draggable?

I have a simpler and elegant solution that doesn't mess up with classes, styles, opacities and stuff.

For the draggable element - you add 'start' event which will execute every time you try to move the element somewhere. You will have a condition which move is not legal. For the moves that are illegal - prevent them with 'e.preventDefault();' like in the code below.

    $(".disc").draggable({
        revert: "invalid", 
        cursor: "move",
        start: function(e, ui){                
            console.log("element is moving");

            if(SOME_CONDITION_FOR_ILLEGAL_MOVE){
                console.log("illegal move");
                //This will prevent moving the element from it's position
                e.preventDefault();
            }    

        }
    });

You are welcome :)

How can I tell if a DOM element is visible in the current viewport?

For a similar challenge, I really enjoyed this gist which exposes a polyfill for scrollIntoViewIfNeeded().

All the necessary Kung Fu needed to answer is within this block:

var parent = this.parentNode,
    parentComputedStyle = window.getComputedStyle(parent, null),
    parentBorderTopWidth = parseInt(parentComputedStyle.getPropertyValue('border-top-width')),
    parentBorderLeftWidth = parseInt(parentComputedStyle.getPropertyValue('border-left-width')),
    overTop = this.offsetTop - parent.offsetTop < parent.scrollTop,
    overBottom = (this.offsetTop - parent.offsetTop + this.clientHeight - parentBorderTopWidth) > (parent.scrollTop + parent.clientHeight),
    overLeft = this.offsetLeft - parent.offsetLeft < parent.scrollLeft,
    overRight = (this.offsetLeft - parent.offsetLeft + this.clientWidth - parentBorderLeftWidth) > (parent.scrollLeft + parent.clientWidth),
    alignWithTop = overTop && !overBottom;

this refers to the element that you want to know if it is, for example, overTop or overBottom - you just should get the drift...

PreparedStatement setNull(..)

You could also consider using preparedStatement.setObject(index,value,type);

Solr vs. ElasticSearch

I see some of the above answers are now a bit out of date. From my perspective, and I work with both Solr(Cloud and non-Cloud) and ElasticSearch on a daily basis, here are some interesting differences:

  • Community: Solr has a bigger, more mature user, dev, and contributor community. ES has a smaller, but active community of users and a growing community of contributors
  • Maturity: Solr is more mature, but ES has grown rapidly and I consider it stable
  • Performance: hard to judge. I/we have not done direct performance benchmarks. A person at LinkedIn did compare Solr vs. ES vs. Sensei once, but the initial results should be ignored because they used non-expert setup for both Solr and ES.
  • Design: People love Solr. The Java API is somewhat verbose, but people like how it's put together. Solr code is unfortunately not always very pretty. Also, ES has sharding, real-time replication, document and routing built-in. While some of this exists in Solr, too, it feels a bit like an after-thought.
  • Support: there are companies providing tech and consulting support for both Solr and ElasticSearch. I think the only company that provides support for both is Sematext (disclosure: I'm Sematext founder)
  • Scalability: both can be scaled to very large clusters. ES is easier to scale than pre-Solr 4.0 version of Solr, but with Solr 4.0 that's no longer the case.

For more thorough coverage of Solr vs. ElasticSearch topic have a look at https://sematext.com/blog/solr-vs-elasticsearch-part-1-overview/ . This is the first post in the series of posts from Sematext doing direct and neutral Solr vs. ElasticSearch comparison. Disclosure: I work at Sematext.

JavaScript loop through json array?

It is working. I just added square brackets to JSON data. The data is:

var data = [
    { 
        "id": "1",
        "msg": "hi", 
        "tid": "2013-05-05 23:35", 
        "fromWho": "[email protected]" 
    }, 
    { 
        "id": "2", 
        "msg": "there", 
        "tid": "2013-05-05 23:45", 
        "fromWho": "[email protected]"
    }
]

And the loop is:

for (var key in data) {
   if (data.hasOwnProperty(key)) {
         alert(data[key].id);
   }
} 

JRE installation directory in Windows

Not as a command, but this information is in the registry:

  • Open the key HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  • Read the CurrentVersion REG_SZ
  • Open the subkey under Java Runtime Environment named with the CurrentVersion value
  • Read the JavaHome REG_SZ to get the path

For example on my workstation i have

HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment
  CurrentVersion = "1.6"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.5
  JavaHome = "C:\Program Files\Java\jre1.5.0_20"
HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Java Runtime Environment\1.6
  JavaHome = "C:\Program Files\Java\jre6"

So my current JRE is in C:\Program Files\Java\jre6

Parsing JSON Object in Java

There are many JSON libraries available in Java.

The most notorious ones are: Jackson, GSON, Genson, FastJson and org.json.

There are typically three things one should look at for choosing any library:

  1. Performance
  2. Ease of use (code is simple to write and legible) - that goes with features.
  3. For mobile apps: dependency/jar size

Specifically for JSON libraries (and any serialization/deserialization libs), databinding is also usually of interest as it removes the need of writing boiler-plate code to pack/unpack the data.

For 1, see this benchmark: https://github.com/fabienrenaud/java-json-benchmark I did using JMH which compares (jackson, gson, genson, fastjson, org.json, jsonp) performance of serializers and deserializers using stream and databind APIs. For 2, you can find numerous examples on the Internet. The benchmark above can also be used as a source of examples...

Quick takeaway of the benchmark: Jackson performs 5 to 6 times better than org.json and more than twice better than GSON.

For your particular example, the following code decodes your json with jackson:

public class MyObj {

    private List<Interest> interests;

    static final class Interest {
        private String interestKey;
    }

    private static final ObjectMapper MAPPER = new ObjectMapper();
    public static void main(String[] args) throws IOException {
        MyObj o = JACKSON.readValue("{\"interests\": [{\"interestKey\": \"Dogs\"}, {\"interestKey\": \"Cats\" }]}", MyObj.class);
    }
}

Let me know if you have any questions.

intl extension: installing php_intl.dll

If you read error message, "icuuc36.dll" is missing. The problem is that you don't have the PHP dir in your PATH, or you can copy all "intl" files from php directory to apache\bin directory. They are : icudt36.dll icuin36.dll icuio36.dll icule36.dll iculx36.dll icutu36.dll icuuc36.dll

HTML5 Video tag not working in Safari , iPhone and iPad

What helped in my case was dropping the audio track. It was silent before, but it had to be gone completely.

On ubuntu:

ffmpeg -i input.mp4 -vcodec copy -an output.mp4

And safari/desktop start to play the video

Python loop to run for certain amount of seconds

try this:

import time
import os

n = 0
for x in range(10): #enter your value here
    print(n)
    time.sleep(1) #to wait a second
    os.system('cls') #to clear previous number
                     #use ('clear') if you are using linux or mac!
    n = n + 1

two divs the same line, one dynamic width, one fixed

So left div style depends on the presence of right div. I can't think of a CSS selector allowing that kind of behavior yet.

Thus it seems to me that you'll need to programmatically add a class server side (or in JS) on parent div or left div to do that.

<div id="parent twocols">
  <div class="left"></div>
  <div class="right"></div>
</div>

or

<div id="parent">
  <div class="left"></div>
</div>

So right style is always :

.right {
    float: right;
    width: 200px; /* or whatever value you need */
    /* margin and padding at your discretion */
}

and left style is :

.parent.twocols .left {
    margin-right: 200px; /* according to right div width + margin + padding*/
}

CSS Background image not loading

for me following line is working for me , I put it in the css of my body ( where image is in same folder in which my css and .html files ) :

background: url('test.jpg');

Other thing that you must care about is , be careful about image extension , be sure that your image has .jpeg or .jpg extension. Thanks

How do I make a text input non-editable?

<input type="text" value="3" class="field left" readonly>

No styling necessary.

See <input> on MDN https://developer.mozilla.org/en/docs/Web/HTML/Element/input#Attributes

SQL multiple columns in IN clause

In Oracle you can do this:

SELECT * FROM table1 WHERE (col_a,col_b) IN (SELECT col_x,col_y FROM table2)

JavaScript - Getting HTML form values

Quick solution to serialize a form without any libraries

_x000D_
_x000D_
function serializeIt(form) {_x000D_
  return (_x000D_
    Array.apply(0, form.elements).map(x => _x000D_
      (_x000D_
        (obj => _x000D_
          (_x000D_
            x.type == "radio" ||_x000D_
            x.type == "checkbox"_x000D_
          ) ?_x000D_
            x.checked ? _x000D_
              obj_x000D_
            : _x000D_
              null_x000D_
          :_x000D_
            obj_x000D_
        )(_x000D_
          {_x000D_
            [x.name]:x.value_x000D_
          }_x000D_
        )_x000D_
      )_x000D_
    ).filter(x => x)_x000D_
  );_x000D_
}_x000D_
_x000D_
function whenSubmitted(e) {_x000D_
  e.preventDefault()_x000D_
  console.log(_x000D_
    JSON.stringify(_x000D_
      serializeIt(document.forms[0]),_x000D_
      4, 4, 4_x000D_
    )_x000D_
  )_x000D_
}
_x000D_
<form onsubmit="whenSubmitted(event)">_x000D_
<input type=text name=hiThere value=nothing>_x000D_
<input type=radio name=okRadioHere value=nothin>_x000D_
<input type=radio name=okRadioHere1 value=nothinElse>_x000D_
<input type=radio name=okRadioHere2 value=nothinStill>_x000D_
_x000D_
<input type=checkbox name=justAcheckBox value=checkin>_x000D_
<input type=checkbox name=justAcheckBox1 value=checkin1>_x000D_
<input type=checkbox name=justAcheckBox2 value=checkin2>_x000D_
_x000D_
<select name=selectingSomething>_x000D_
<option value="hiThere">Hi</option>_x000D_
<option value="hiThere1">Hi1</option>_x000D_
<option value="hiThere2">Hi2</option>_x000D_
<option value="hiThere3">Hi3</option>_x000D_
</select>_x000D_
<input type=submit value="click me!" name=subd>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Automatic Preferred Max Layout Width is not available on iOS versions prior to 8.0

To summarize, for me following the two instructions above to change any instances where numberOfLines = 0 to 1 or greater, and manually adding preferredMaxLayoutWidth="0" to each instance of a label inside the storyboard source fixed all of my warnings.

Log4j: How to configure simplest possible file logging?

I have one generic log4j.xml file for you:

<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration debug="false">

    <appender name="default.console" class="org.apache.log4j.ConsoleAppender">
        <param name="target" value="System.out" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <appender name="default.file" class="org.apache.log4j.FileAppender">
        <param name="file" value="/log/mylogfile.log" />
        <param name="append" value="false" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <appender name="another.file" class="org.apache.log4j.FileAppender">
        <param name="file" value="/log/anotherlogfile.log" />
        <param name="append" value="false" />
        <param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ISO8601} %-5p [%c{1}] - %m%n" />
        </layout>
    </appender>

    <logger name="com.yourcompany.SomeClass" additivity="false">
        <level value="debug" />
        <appender-ref ref="another.file" />
    </logger>

    <root>
        <priority value="info" />
        <appender-ref ref="default.console" />
        <appender-ref ref="default.file" />
    </root>
</log4j:configuration>

with one console, two file appender and one logger poiting to the second file appender instead of the first.

EDIT

In one of the older projects I have found a simple log4j.properties file:

# For the general syntax of property based configuration files see
# the documentation of org.apache.log4j.PropertyConfigurator.

# The root category uses two appenders: default.out and default.file.
# The first one gathers all log output, the latter only starting with 
# the priority INFO.
# The root priority is DEBUG, so that all classes can be logged unless 
# defined otherwise in more specific properties.
log4j.rootLogger=DEBUG, default.out, default.file

# System.out.println appender for all classes
log4j.appender.default.out=org.apache.log4j.ConsoleAppender
log4j.appender.default.out.threshold=DEBUG
log4j.appender.default.out.layout=org.apache.log4j.PatternLayout
log4j.appender.default.out.layout.ConversionPattern=%-5p %c: %m%n

log4j.appender.default.file=org.apache.log4j.FileAppender
log4j.appender.default.file.append=true
log4j.appender.default.file.file=/log/mylogfile.log
log4j.appender.default.file.threshold=INFO
log4j.appender.default.file.layout=org.apache.log4j.PatternLayout
log4j.appender.default.file.layout.ConversionPattern=%-5p %c: %m%n

For the description of all the layout arguments look here: log4j PatternLayout arguments

Is there a better way to compare dictionary values

If the true intent of the question is the comparison between dicts (rather than printing differences), the answer is

dict1 == dict2

This has been mentioned before, but I felt it was slightly drowning in other bits of information. It might appear superficial, but the value comparison of dicts has actually powerful semantics. It covers

  • number of keys (if they don't match, the dicts are not equal)
  • names of keys (if they don't match, they're not equal)
  • value of each key (they have to be '==', too)

The last point again appears trivial, but is acutally interesting as it means that all of this applies recursively to nested dicts as well. E.g.

 m1 = {'f':True}
 m2 = {'f':True}
 m3 = {'a':1, 2:2, 3:m1}
 m4 = {'a':1, 2:2, 3:m2}
 m3 == m4  # True

Similar semantics exist for the comparison of lists. All of this makes it a no-brainer to e.g. compare deep Json structures, alone with a simple "==".

Detecting an "invalid date" Date instance in JavaScript

// check whether date is valid
var t = new Date('2011-07-07T11:20:00.000+00:00x');
valid = !isNaN(t.valueOf());

Jquery Ajax Posting json to webservice

I have query,

$("#login-button").click(function(e){ alert("hiii");

        var username = $("#username-field").val();
        var password = $("#username-field").val();

        alert(username);
        alert("password" + password);



        var markers = { "userName" : "admin","password" : "admin123"};
        $.ajax({
            type: "POST",
            url: url,
            // The key needs to match your method's input parameter (case-sensitive).
            data: JSON.stringify(markers),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(data){alert("got the data"+data);},
            failure: function(errMsg) {
                alert(errMsg);
            }
        });

    });

I'm posting the the login details in json and getting a string as "Success",but I'm not getting the response.

Initialise numpy array of unknown length

You can do this:

a = np.array([])
for x in y:
    a = np.append(a, x)

How to execute Table valued function

A TVF (table-valued function) is supposed to be SELECTed FROM. Try this:

select * from FN('myFunc')

Ignore .classpath and .project from Git

Use a .gitignore file. This allows you to ignore certain files. http://git-scm.com/docs/gitignore

Here's an example Eclipse one, which handles your classpath and project files: https://github.com/github/gitignore/blob/master/Global/Eclipse.gitignore

React : difference between <Route exact path="/" /> and <Route path="/" />

In this example, nothing really. The exact param comes into play when you have multiple paths that have similar names:

For example, imagine we had a Users component that displayed a list of users. We also have a CreateUser component that is used to create users. The url for CreateUsers should be nested under Users. So our setup could look something like this:

<Switch>
  <Route path="/users" component={Users} />
  <Route path="/users/create" component={CreateUser} />
</Switch>

Now the problem here, when we go to http://app.com/users the router will go through all of our defined routes and return the FIRST match it finds. So in this case, it would find the Users route first and then return it. All good.

But, if we went to http://app.com/users/create, it would again go through all of our defined routes and return the FIRST match it finds. React router does partial matching, so /users partially matches /users/create, so it would incorrectly return the Users route again!

The exact param disables the partial matching for a route and makes sure that it only returns the route if the path is an EXACT match to the current url.

So in this case, we should add exact to our Users route so that it will only match on /users:

<Switch>
  <Route exact path="/users" component={Users} />
  <Route path="/users/create" component={CreateUser} />
</Switch>

The docs explain exact in detail and give other examples.

C# - Substring: index and length must refer to a location within the string

Try This:

 int positionOfJPG=url.IndexOf(".jpg");
 string newString = url.Substring(18, url.Length - positionOfJPG);

Difference between socket and websocket?

To answer your questions.

  1. Even though they achieve (in general) similar things, yes, they are really different. WebSockets typically run from browsers connecting to Application Server over a protocol similar to HTTP that runs over TCP/IP. So they are primarily for Web Applications that require a permanent connection to its server. On the other hand, plain sockets are more powerful and generic. They run over TCP/IP but they are not restricted to browsers or HTTP protocol. They could be used to implement any kind of communication.
  2. No. There is no reason.

pip install returning invalid syntax

You need to run pip install in the command prompt, outside from a python interpreter ! Try to exit python and re try :)

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

You are trying to run a Python 2 codebase with Python 3. xrange() was renamed to range() in Python 3.

Run the game with Python 2 instead. Don't try to port it unless you know what you are doing, most likely there will be more problems beyond xrange() vs. range().

For the record, what you are seeing is not a syntax error but a runtime exception instead.


If you do know what your are doing and are actively making a Python 2 codebase compatible with Python 3, you can bridge the code by adding the global name to your module as an alias for range. (Take into account that you may have to update any existing range() use in the Python 2 codebase with list(range(...)) to ensure you still get a list object in Python 3):

try:
    # Python 2
    xrange
except NameError:
    # Python 3, xrange is now named range
    xrange = range

# Python 2 code that uses xrange(...) unchanged, and any
# range(...) replaced with list(range(...))

or replace all uses of xrange(...) with range(...) in the codebase and then use a different shim to make the Python 3 syntax compatible with Python 2:

try:
    # Python 2 forward compatibility
    range = xrange
except NameError:
    pass

# Python 2 code transformed from range(...) -> list(range(...)) and
# xrange(...) -> range(...).

The latter is preferable for codebases that want to aim to be Python 3 compatible only in the long run, it is easier to then just use Python 3 syntax whenever possible.

How to get disk capacity and free space of remote computer

Much simpler solution:

Get-PSDrive C | Select-Object Used,Free

and for remote computers (needs Powershell Remoting)

Invoke-Command -ComputerName SRV2 {Get-PSDrive C} | Select-Object PSComputerName,Used,Free

How to echo out the values of this array?

you need the set key and value in foreach loop for that:

foreach($item AS $key -> $value) {
echo $value;
}

this should do the trick :)

Difference between Git and GitHub

Git- Git is a version control software that you install on your local system. For an individual working on a project alone, Git proves to be excellent software.

GitHub- As mentioned earlier, Git is a version control system that tracks code changes, while GitHub is a web-based Git version control repository hosting service. It provides all of the distributed version control and source code management (SCM) functionalities of Git while topping it with a few of its own features.

Android Studio: Application Installation Failed

I also got same problem while generating signed APK. Just select APK signature scheme v1, not v2 (introduced in in Android 7.0). If you select v2 scheme it won't work on devices that use Android versions older than 7.0.

Is there a kind of Firebug or JavaScript console debug for Android?

We are following the below steps in our project for debugging a website on mobile.

  1. Install mobogenie software on mobile and desktop (both have the same version).
  2. Open your site in mobile Google Chrome browser.
  3. Open Google Chrome on desktop. Go to Option --> More Options --> Inspect Device.
  4. Here you find a list of sites which are open on mobile and click on inspect and you get the JavaScript console which you want.

Python unittest passing arguments

Even if the test gurus say that we should not do it: I do. In some context it makes a lot of sense to have parameters to drive the test in the right direction, for example:

  • which of the dozen identical USB cards should I use for this test now?
  • which server should I use for this test now?
  • which XXX should I use?

For me, the use of the environment variable is good enough for this puprose because you do not have to write dedicated code to pass your parameters around; it is supported by Python. It is clean and simple.

Of course, I'm not advocating for fully parametrizable tests. But we have to be pragmatic and, as I said, in some context you need a parameter or two. We should not abouse of it :)

import os
import unittest


class MyTest(unittest.TestCase):
    def setUp(self):
        self.var1 = os.environ["VAR1"]
        self.var2 = os.environ["VAR2"]

    def test_01(self):
        print("var1: {}, var2: {}".format(self.var1, self.var2))

Then from the command line (tested on Linux)

$ export VAR1=1
$ export VAR2=2
$ python -m unittest MyTest
var1: 1, var2: 2
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

How to check if an appSettings key exists?

var isAlaCarte = 
    ConfigurationManager.AppSettings.AllKeys.Contains("IsALaCarte") && 
    bool.Parse(ConfigurationManager.AppSettings.Get("IsALaCarte"));

How do I use two submit buttons, and differentiate between which one was used to submit the form?

Give name and values to those submit buttons like:

    <td>
    <input type="submit" name='mybutton' class="noborder" id="save" value="save" alt="Save" tabindex="4" />
    </td>
    <td>
    <input type="submit" name='mybutton' class="noborder" id="publish" value="publish" alt="Publish" tabindex="5" />
    </td>

and then in your php script you could check

if($_POST['mybutton'] == 'save')
{
  ///do save processing
}
elseif($_POST['mybutton'] == 'publish')
{
  ///do publish processing here
}

HTML image not showing in Gmail

I know Gmail already fix all the problem above, the alt and stuff now.

And this is unrelated to the question but probably someone experiences the same as me.

So my web designer use "image" tag instead of "img", but the symptom was the same. It works on outlook but not Gmail.
It takes me an hour to realize. Sigh, such a waste of time.

So make sure the tag is "img" not "image" as well.

Missing styles. Is the correct theme chosen for this layout?

This is very late but i like to share my experience this same issue. i face the same issue in Android studio i tried to some other solution that i found in internet but nothing works for me unless i REBUILD THE PROJECT and it solve my issue.

Hope this will works for you too.

Happy coding.

How to locate the Path of the current project directory in Java (IDE)?

This is a code snippet to retrieve the path of the current running web application project in java.

public String getPath() throws UnsupportedEncodingException {

    String path = this.getClass().getClassLoader().getResource("").getPath();
    String fullPath = URLDecoder.decode(path, "UTF-8");
    String pathArr[] = fullPath.split("/WEB-INF/classes/");
    System.out.println(fullPath);
    System.out.println(pathArr[0]);
    fullPath = pathArr[0];

    return fullPath;

}

Source: https://dzone.com/articles/get-current-web-application

What is the proper way to format a multi-line dict in Python?

Generally, you would not include the comma after the final entry, but Python will correct that for you.

Python "SyntaxError: Non-ASCII character '\xe2' in file"

\xe2 is the '-' character, it appears in some copy and paste it uses a different equal looking '-' that causes encoding errors. Replace the '-'(from copy paste) with the correct '-' (from you keyboard button).

How to make an HTTP request + basic auth in Swift

In Swift 2:

extension NSMutableURLRequest {
    func setAuthorizationHeader(username username: String, password: String) -> Bool {
        guard let data = "\(username):\(password)".dataUsingEncoding(NSUTF8StringEncoding) else { return false }

        let base64 = data.base64EncodedStringWithOptions([])
        setValue("Basic \(base64)", forHTTPHeaderField: "Authorization")
        return true
    }
}

using favicon with css

If (1) you need a favicon that is different for some parts of the domain, or (2) you want this to work with IE 8 or older (haven't tested any newer version), then you have to edit the html to specify the favicon

Select all child elements recursively in CSS

Use a white space to match all descendants of an element:

div.dropdown * {
    color: red;
}

x y matches every element y that is inside x, however deeply nested it may be - children, grandchildren and so on.

The asterisk * matches any element.

Official Specification: CSS 2.1: Chapter 5.5: Descendant Selectors

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

How to cast List<Object> to List<MyClass>

That's because although a Customer is an Object, a List of Customers is not a List of Objects. If it was, then you could put any object in a list of Customers.

REST API Token-based Authentication

A pure RESTful API should use the underlying protocol standard features:

  1. For HTTP, the RESTful API should comply with existing HTTP standard headers. Adding a new HTTP header violates the REST principles. Do not re-invent the wheel, use all the standard features in HTTP/1.1 standards - including status response codes, headers, and so on. RESTFul web services should leverage and rely upon the HTTP standards.

  2. RESTful services MUST be STATELESS. Any tricks, such as token based authentication that attempts to remember the state of previous REST requests on the server violates the REST principles. Again, this is a MUST; that is, if you web server saves any request/response context related information on the server in attempt to establish any sort of session on the server, then your web service is NOT Stateless. And if it is NOT stateless it is NOT RESTFul.

Bottom-line: For authentication/authorization purposes you should use HTTP standard authorization header. That is, you should add the HTTP authorization / authentication header in each subsequent request that needs to be authenticated. The REST API should follow the HTTP Authentication Scheme standards.The specifics of how this header should be formatted are defined in the RFC 2616 HTTP 1.1 standards – section 14.8 Authorization of RFC 2616, and in the RFC 2617 HTTP Authentication: Basic and Digest Access Authentication.

I have developed a RESTful service for the Cisco Prime Performance Manager application. Search Google for the REST API document that I wrote for that application for more details about RESTFul API compliance here. In that implementation, I have chosen to use HTTP "Basic" Authorization scheme. - check out version 1.5 or above of that REST API document, and search for authorization in the document.

data.frame Group By column

I would recommend having a look at the plyr package. It might not be as fast as data.table or other packages, but it is quite instructive, especially when starting with R and having to do some data manipulation.

> DF <- data.frame(A = c("1", "1", "2", "3", "3"), B = c(2, 3, 3, 5, 6))
> library(plyr)
> DF.sum <- ddply(DF, c("A"), summarize, B = sum(B))
> DF.sum
  A  B
1 1  5
2 2  3
3 3 11

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

None of the other solution worked for me.

Even if I don't think its the best practice, I Had to add it into the code like this

configuration.addAnnotatedClass(com.myOrg.entities.Person.class);

here

public static SessionFactory getSessionFactory() {
    Configuration configuration = new Configuration().configure();

    configuration.addAnnotatedClass(com.myOrg.entities.Person.class);

    StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
            .applySettings(configuration.getProperties());
    SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
    return sessionFactory;
}

Angular 2 - View not updating after model changes

It might be that the code in your service somehow breaks out of Angular's zone. This breaks change detection. This should work:

import {Component, OnInit, NgZone} from 'angular2/core';

export class RecentDetectionComponent implements OnInit {

    recentDetections: Array<RecentDetection>;

    constructor(private zone:NgZone, // <== added
        private recentDetectionService: RecentDetectionService) {
        this.recentDetections = new Array<RecentDetection>();
    }

    getRecentDetections(): void {
        this.recentDetectionService.getJsonFromApi()
            .subscribe(recent => { 
                 this.zone.run(() => { // <== added
                     this.recentDetections = recent;
                     console.log(this.recentDetections[0].macAddress) 
                 });
        });
    }

    ngOnInit() {
        this.getRecentDetections();
        let timer = Observable.timer(2000, 5000);
        timer.subscribe(() => this.getRecentDetections());
    }
}

For other ways to invoke change detection see Triggering change detection manually in Angular

Alternative ways to invoke change detection are

ChangeDetectorRef.detectChanges()

to immediately run change detection for the current component and its children

ChangeDetectorRef.markForCheck()

to include the current component the next time Angular runs change detection

ApplicationRef.tick()

to run change detection for the whole application

How can I get list of values from dict?

You can use * operator to unpack dict_values:

>>> d = {1: "a", 2: "b"}
>>> [*d.values()]
['a', 'b']

or list object

>>> d = {1: "a", 2: "b"}
>>> list(d.values())
['a', 'b']

How to get the first item from an associative PHP array?

Test if the a variable is an array before getting the first element. When dynamically creating the array if it is set to null you get an error.

For Example:

if(is_array($array))
{
  reset($array);
  $first = key($array);
}

How to debug in Django, the good way?

For those that can accidentally add pdb into live commits, I can suggest this extension of #Koobz answer:

@register.filter 
def pdb(element):
    from django.conf import settings
    if settings.DEBUG:    
        import pdb
        pdb.set_trace()
    return element

Android: Create spinner programmatically from array

this work for me:-

String[] array = {"A", "B", "C"};
String abc = "";


Spinner spinner = new Spinner(getContext());
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, array); //selected item will look like a spinner set from XML
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(spinnerArrayAdapter);

I am using a Fragment.

Original purpose of <input type="hidden">?

The values of form elements including type='hidden' are submitted to the server when the form is posted. input type="hidden" values are not visible in the page. Maintaining User IDs in hidden fields, for example, is one of the many uses.

SO uses a hidden field for the upvote click.

<input value="16293741" name="postId" type="hidden">

Using this value, the server-side script can store the upvote.

How to generate classes from wsdl using Maven and wsimport?

I see some people prefer to generate sources into the target via jaxws-maven-plugin AND make this classes visible in source via build-helper-maven-plugin. As an argument for this structure

the version management system (svn/etc.) would always notice changed sources

With git it is not true. So you can just configure jaxws-maven-plugin to put them into your sources, but not under the target folder. Next time you build your project, git will not mark these generated files as changed. Here is the simple solution with only one plugin:

      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jaxws-maven-plugin</artifactId>
        <version>2.6</version>

    <dependencies>
      <dependency>
        <groupId>org.jvnet.jaxb2_commons</groupId>
        <artifactId>jaxb2-fluent-api</artifactId>
        <version>3.0</version>
      </dependency>
      <dependency>
        <groupId>com.sun.xml.ws</groupId>
        <artifactId>jaxws-tools</artifactId>
        <version>2.3.0</version>
      </dependency>
    </dependencies>

    <executions>
      <execution>
        <goals>
          <goal>wsimport</goal>
        </goals>
        <configuration>
          <packageName>som.path.generated</packageName>
          <xjcArgs>
            <xjcArg>-Xfluent-api</xjcArg>
          </xjcArgs>
          <verbose>true</verbose>
          <keep>true</keep> <!--used by default-->
          <sourceDestDir>${project.build.sourceDirectory}</sourceDestDir>
          <wsdlDirectory>src/main/resources/META-INF/wsdl</wsdlDirectory>
          <wsdlLocation>META-INF/wsdl/soap.wsdl</wsdlLocation>
        </configuration>
      </execution>
    </executions>
  </plugin>

Additionally (just to note) in this example SOAP classes are generated with Fluent API, so you can create them like:

A a = new A()
  .withField1(value1)
  .withField2(value2);

Bigger Glyphicons

If you are using bootstrap 3, use tag, like this <small><span class="glyphicon glyphicon-send"></span></small> It works perfect for Bootstrap 3.
You can even use multiple <small> tags to set the size more smaller.
Code:
<small><small><span class="glyphicon glyphicon-send"></span></small></small>

ObjectiveC Parse Integer from String

Keep in mind that international users may be using a decimal separator other than . in which case values can get mixed up or just become nil when using intValue on a string.

For example, in the UK 1.23 is written 1,23, so the number 1.777 would be input by user as 1,777, which, as .intValue, will be 1777 not 1 (truncated).


I've made a macro that will convert input text to an NSNumber based on a locale argument which can be nil (if nil it uses device current locale).

#define stringToNumber(__string, __nullable_locale) (\
(^NSNumber *(void){\
NSLocale *__locale = __nullable_locale;\
if (!__locale) {\
__locale = [NSLocale currentLocale];\
}\
NSString *__string_copy = [__string stringByReplacingOccurrencesOfString:__locale.groupingSeparator withString:@""];\
__string_copy = [__string_copy stringByReplacingOccurrencesOfString:__locale.decimalSeparator withString:@"."];\
return @([__string_copy doubleValue]);\
})()\
)

Unrecognized attribute 'targetFramework'. Note that attribute names are case-sensitive

It could be that you have your own MSBUILD proj file and are using the <AspNetCompiler> task. In which case you should add the ToolPath for .NET4.

<AspNetCompiler
    VirtualPath="/MyFacade"
    PhysicalPath="$(MSBuildProjectDirectory)\MyFacade\"
    TargetPath="$(MSBuildProjectDirectory)\Release\MyFacade"
    Updateable="true"
    Force="true"
    Debug="false"
    Clean="true"
    ToolPath="C:\Windows\Microsoft.NET\Framework\v4.0.30319\">      
</AspNetCompiler>

Regex to remove all special characters from string?

Depending on your definition of "special character", I think "[^a-zA-Z0-9]" would probably do the trick. That would find anything that is not a small letter, a capital letter, or a digit.

Gradle proxy configuration

An update to @sourcesimian 's and @kunal-b's answer which dynamically sets the username and password if configured in the system properties.

The following sets the username and password if provided or just adds the host and port if no username and password is set.

task setHttpProxyFromEnv {
    def map = ['HTTP_PROXY': 'http', 'HTTPS_PROXY': 'https']
    for (e in System.getenv()) {
        def key = e.key.toUpperCase()
        if (key in map) {
            def base = map[key]
            //Get proxyHost,port, username, and password from http system properties 
            // in the format http://username:password@proxyhost:proxyport
            def (val1,val2) = e.value.tokenize( '@' )
            def (val3,val4) = val1.tokenize( '//' )
            def(userName, password) = val4.tokenize(':')
            def url = e.value.toURL()
            //println " - systemProp.${base}.proxy=${url.host}:${url.port}"
            System.setProperty("${base}.proxyHost", url.host.toString())
            System.setProperty("${base}.proxyPort", url.port.toString())
            System.setProperty("${base}.proxyUser", userName.toString())
            System.setProperty("${base}.proxyPassword", password.toString())
        }
    }
}

Parsing JSON with Unix tools

There are a number of tools specifically designed for the purpose of manipulating JSON from the command line, and will be a lot easier and more reliable than doing it with Awk, such as jq:

curl -s 'https://api.github.com/users/lambda' | jq -r '.name'

You can also do this with tools that are likely already installed on your system, like Python using the json module, and so avoid any extra dependencies, while still having the benefit of a proper JSON parser. The following assume you want to use UTF-8, which the original JSON should be encoded in and is what most modern terminals use as well:

Python 3:

curl -s 'https://api.github.com/users/lambda' | \
    python3 -c "import sys, json; print(json.load(sys.stdin)['name'])"

Python 2:

export PYTHONIOENCODING=utf8
curl -s 'https://api.github.com/users/lambda' | \
    python2 -c "import sys, json; print json.load(sys.stdin)['name']"

Frequently Asked Questions

Why not a pure shell solution?

The standard POSIX/Single Unix Specification shell is a very limited language which doesn't contain facilities for representing sequences (list or arrays) or associative arrays (also known as hash tables, maps, dicts, or objects in some other languages). This makes representing the result of parsing JSON somewhat tricky in portable shell scripts. There are somewhat hacky ways to do it, but many of them can break if keys or values contain certain special characters.

Bash 4 and later, zsh, and ksh have support for arrays and associative arrays, but these shells are not universally available (macOS stopped updating Bash at Bash 3, due to a change from GPLv2 to GPLv3, while many Linux systems don't have zsh installed out of the box). It's possible that you could write a script that would work in either Bash 4 or zsh, one of which is available on most macOS, Linux, and BSD systems these days, but it would be tough to write a shebang line that worked for such a polyglot script.

Finally, writing a full fledged JSON parser in shell would be a significant enough enough dependency that you might as well just use an existing dependency like jq or Python instead. It's not going to be a one-liner, or even small five-line snippet, to do a good implementation.

Why not use awk, sed, or grep?

It is possible to use these tools to do some quick extraction from JSON with a known shape and formatted in a known way, such as one key per line. There are several examples of suggestions for this in other answers.

However, these tools are designed for line based or record based formats; they are not designed for recursive parsing of matched delimiters with possible escape characters.

So these quick and dirty solutions using awk/sed/grep are likely to be fragile, and break if some aspect of the input format changes, such as collapsing whitespace, or adding additional levels of nesting to the JSON objects, or an escaped quote within a string. A solution that is robust enough to handle all JSON input without breaking will also be fairly large and complex, and so not too much different than adding another dependency on jq or Python.

I have had to deal with large amounts of customer data being deleted due to poor input parsing in a shell script before, so I never recommend quick and dirty methods that may be fragile in this way. If you're doing some one-off processing, see the other answers for suggestions, but I still highly recommend just using an existing tested JSON parser.

Historical notes

This answer originally recommended jsawk, which should still work, but is a little more cumbersome to use than jq, and depends on a standalone JavaScript interpreter being installed which is less common than a Python interpreter, so the above answers are probably preferable:

curl -s 'https://api.github.com/users/lambda' | jsawk -a 'return this.name'

This answer also originally used the Twitter API from the question, but that API no longer works, making it hard to copy the examples to test out, and the new Twitter API requires API keys, so I've switched to using the GitHub API which can be used easily without API keys. The first answer for the original question would be:

curl 'http://twitter.com/users/username.json' | jq -r '.text'

How To fix white screen on app Start up?

i also had the same problem in one of my project. I resolved it by adding some following parameters in the theme provided to the splash screen.

<item name="android:windowFullscreen">true</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowIsTranslucent">true</item>

You can find the reason and resolution in this blog post written by me. Hope it helps.

What is PAGEIOLATCH_SH wait type in SQL Server?

From Microsoft documentation:

PAGEIOLATCH_SH

Occurs when a task is waiting on a latch for a buffer that is in an I/O request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.

In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.

If your query is like this:

Select * from <table> where <col1> = <value> order by <PrimaryKey>

, check that you have a composite index on (col1, col_primary_key).

If you don't have one, then you'll need either a full INDEX SCAN if the PRIMARY KEY is chosen, or a SORT if an index on col1 is chosen.

Both of them are very disk I/O consuming operations on large tables.

How can I read inputs as numbers?

def dbz():
    try:
        r = raw_input("Enter number:")
        if r.isdigit():
            i = int(raw_input("Enter divident:"))
            d = int(r)/i
            print "O/p is -:",d
        else:
            print "Not a number"
    except Exception ,e:
        print "Program halted incorrect data entered",type(e)
dbz()

Or 

num = input("Enter Number:")#"input" will accept only numbers

What is the difference between UTF-8 and Unicode?

"Unicode" is unfortunately used in various different ways, depending on the context. Its most correct use (IMO) is as a coded character set - i.e. a set of characters and a mapping between the characters and integer code points representing them.

UTF-8 is a character encoding - a way of converting from sequences of bytes to sequences of characters and vice versa. It covers the whole of the Unicode character set. ASCII is encoded as a single byte per character, and other characters take more bytes depending on their exact code point (up to 4 bytes for all currently defined code points, i.e. up to U-0010FFFF, and indeed 4 bytes could cope with up to U-001FFFFF).

When "Unicode" is used as the name of a character encoding (e.g. as the .NET Encoding.Unicode property) it usually means UTF-16, which encodes most common characters as two bytes. Some platforms (notably .NET and Java) use UTF-16 as their "native" character encoding. This leads to hairy problems if you need to worry about characters which can't be encoded in a single UTF-16 value (they're encoded as "surrogate pairs") - but most developers never worry about this, IME.

Some references on Unicode:

How can we run a test method with multiple parameters in MSTest?

Not exactly the same as NUnit's Value (or TestCase) attributes, but MSTest has the DataSource attribute, which allows you to do a similar thing.

You can hook it up to database or XML file - it is not as straightforward as NUnit's feature, but it does the job.

JBoss AS 7: How to clean up tmp?

Files related for deployment (and others temporary items) are created in standalone/tmp/vfs (Virtual File System). You may add a policy at startup for evicting temporary files :

-Djboss.vfs.cache=org.jboss.virtual.plugins.cache.IterableTimedVFSCache 
-Djboss.vfs.cache.TimedPolicyCaching.lifetime=1440

Deprecated: mysql_connect()

<?php 
$link = mysqli_connect('localhost','root',''); 
if (!$link) { 
    die('Could not connect to MySQL: ' . mysqli_error()); 
} 
echo 'Connection OK'; mysqli_close($link); 
?>

This will solve your problem.

IOPub data rate exceeded in Jupyter notebook (when viewing image)

I ran into this using networkx and bokeh

This works for me in Windows 7 (taken from here):

  1. To create a jupyter_notebook_config.py file, with all the defaults commented out, you can use the following command line:

    $ jupyter notebook --generate-config

  2. Open the file and search for c.NotebookApp.iopub_data_rate_limit

  3. Comment out the line c.NotebookApp.iopub_data_rate_limit = 1000000 and change it to a higher default rate. l used c.NotebookApp.iopub_data_rate_limit = 10000000

This unforgiving default config is popping up in a lot of places. See git issues:

It looks like it might get resolved with the 5.1 release

Update:

Jupyter notebook is now on release 5.2.2. This problem should have been resolved. Upgrade using conda or pip.

scroll image with continuous scrolling using marquee tag

Marquee (<marquee>) is a deprecated and not a valid HTML tag. You can use many jQuery plugins to do. One of it, is jQuery News Ticker. There are many more!

Trim specific character from a string

One line is enough:

_x000D_
_x000D_
var x = '|f|oo||';
var y = x.replace(/^\|+|\|+$/g, '');
document.write(x + '<br />' + y);
_x000D_
_x000D_
_x000D_

^\|+   beginning of the string, pipe, one or more times
|      or
\|+$   pipe, one or more times, end of the string

A general solution:

_x000D_
_x000D_
function trim (s, c) {
  if (c === "]") c = "\\]";
  if (c === "\\") c = "\\\\";
  return s.replace(new RegExp(
    "^[" + c + "]+|[" + c + "]+$", "g"
  ), "");
}

chars = ".|]\\";
for (c of chars) {
  s = c + "foo" + c + c + "oo" + c + c + c;
  console.log(s, "->", trim(s, c));
}
_x000D_
_x000D_
_x000D_

<button> vs. <input type="button" />. Which to use?

There is a big difference if you are using jQuery. jQuery is aware of more events on inputs than it does on buttons. On buttons, jQuery is only aware of 'click' events. On inputs, jQuery is aware of 'click', 'focus', and 'blur' events.

You could always bind events to your buttons as needed, but just be aware that the events that jQuery automatically is aware of are different. For example, if you created a function that was executed whenever there was a 'focusin' event on your page, an input would trigger the function but a button would not.

How can I connect to MySQL on a WAMP server?

Try opening Port 3306, and using that in the connection string not 8080.

How do I make jQuery wait for an Ajax call to finish before it returns?

since async ajax is deprecated try using nested async functions with a Promise. There may be syntax errors.


async function fetch_my_data(_url, _dat) {

   async function promised_fetch(_url, _dat) {

      return new Promise((resolve, reject) => {
         $.ajax({
            url:  _url,
            data: _dat,
            type: 'POST',
            success: (response) => {
               resolve(JSON.parse(response));
            },
            error: (response) => {
               reject(response);
            }
         });
      });
   }

   var _data = await promised_fetch(_url, _dat);
   
   return _data;
}

var _my_data = fetch_my_data('server.php', 'get_my_data=1');

How to resolve Nodejs: Error: ENOENT: no such file or directory

[this is a helpful link on multer github][1]

but for me i have to create a public folder in the server folder also its like -cb(null,'public/'). [1]: https://github.com/expressjs/multer/issues/513

How to redirect in a servlet filter?

If you also want to keep hash and get parameter, you can do something like this (fill redirectMap at filter init):

String uri = request.getRequestURI();

String[] uriParts = uri.split("[#?]");
String path = uriParts[0];
String rest = uri.substring(uriParts[0].length());

if(redirectMap.containsKey(path)) {
    response.sendRedirect(redirectMap.get(path) + rest);
} else {
    chain.doFilter(request, response);
}

Visual Studio debugging/loading very slow

One time, after a power outage, I had to face the same slowness problem each time a breakpoint was hit or a Exception was thrown.

I had the vague remembering that the "suo" file (in the same directory as the "sln" solution file) can be corrupted and make everything slow down.

enter image description here

I deleted my "suo" files and everything was ok. The .suo files deletion is harmless and only implies to recreate my windows layout plus the starting project and a few other non critical customizations.

Conditionally hide CommandField or ButtonField in Gridview

<asp:GridView ID="gv_Document" CssClass="gridstyle" runat="server" OnRowDataBound="gv_Document_RowDataBound" AutoGenerateColumns="false" DataKeyNames="SourceGUID,Source,FilePath" ShowHeaderWhenEmpty="false" OnRowDeleting="gv_Document_RowDeleting">
   <Columns>
       <asp:BoundField HeaderText="ItemID" DataField="ItemID" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
       <asp:BoundField HeaderText="SourceGUID" DataField="SourceGUID" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
       <asp:BoundField HeaderText="Source" DataField="Source" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
           <asp:TemplateField HeaderText="">
               <ItemTemplate>
                    <asp:HyperLink ID="hyperLink" runat="server" Target="_blank" NavigateUrl='<%# Bind("FilePath")%>'
                                                                Text='<%# Bind("FileName")%>'>  </asp:HyperLink>
               </ItemTemplate>
           </asp:TemplateField>
      <asp:BoundField HeaderText="Type" DataField="FileExtension" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
      <asp:BoundField HeaderText="Content type" DataField="FileMimeType" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
      <asp:BoundField HeaderText="File Path" DataField="FilePath" ItemStyle-CssClass="hidden-field" HeaderStyle-CssClass="hidden-field" />
      <asp:CommandField ShowDeleteButton="True" DeleteText="Delete" />
   </Columns>

Use this code to disable delete button in gridview from code behind.

protected void gv_Document_RowDataBound(object sender, GridViewRowEventArgs e)
{ 
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        ((LinkButton)e.Row.Cells[7].Controls[0]).Visible = false;            
    }
}

How to select an element by classname using jqLite?

angualr uses the lighter version of jquery called as jqlite which means it doesnt have all the features of jQuery. here is a reference in angularjs docs about what you can use from jquery. Angular Element docs

In your case you need to find a div with ID or class name. for class name you can use

var elems =$element.find('div') //returns all the div's in the $elements
    angular.forEach(elems,function(v,k)){
    if(angular.element(v).hasClass('class-name')){
     console.log(angular.element(v));
}}

or you can use much simpler way by query selector

angular.element(document.querySelector('#id'))

angular.element(elem.querySelector('.classname'))

it is not as flexible as jQuery but what

CSS horizontal scroll

You can use display:inline-block with white-space:nowrap. Write like this:

.scrolls {
    overflow-x: scroll;
    overflow-y: hidden;
    height: 80px;
    white-space:nowrap
}
.imageDiv img {
    box-shadow: 1px 1px 10px #999;
    margin: 2px;
    max-height: 50px;
    cursor: pointer;
    display:inline-block;
    *display:inline;/* For IE7*/
    *zoom:1;/* For IE7*/
    vertical-align:top;
 }

Check this http://jsfiddle.net/YbrX3/

What is difference between sleep() method and yield() method of multi threading?

Sleep causes thread to suspend itself for x milliseconds while yield suspends the thread and immediately moves it to the ready queue (the queue which the CPU uses to run threads).

DateTime2 vs DateTime in SQL Server

I think DATETIME2 is the better way to store the date, because it has more efficiency than the DATETIME. In SQL Server 2008 you can use DATETIME2, it stores a date and time, takes 6-8 bytes to store and has a precision of 100 nanoseconds. So anyone who needs greater time precision will want DATETIME2.

Why does Git say my master branch is "already up to date" even though it is not?

Any changes you commit, like deleting all your project files, will still be in place after a pull. All a pull does is merge the latest changes from somewhere else into your own branch, and if your branch has deleted everything, then at best you'll get merge conflicts when upstream changes affect files you've deleted. So, in short, yes everything is up to date.

If you describe what outcome you'd like to have instead of "all files deleted", maybe someone can suggest an appropriate course of action.

Update:

GET THE MOST RECENT OF THE CODE ON MY SYSTEM

What you don't seem to understand is that you already have the most recent code, which is yours. If what you really want is to see the most recent of someone else's work that's on the master branch, just do:

git fetch upstream
git checkout upstream/master

Note that this won't leave you in a position to immediately (re)start your own work. If you need to know how to undo something you've done or otherwise revert changes you or someone else have made, then please provide details. Also, consider reading up on what version control is for, since you seem to misunderstand its basic purpose.

C++: Converting Hexadecimal to Decimal

Here is a solution using strings and converting it to decimal with ASCII tables:

#include <iostream>
#include <string>
#include "math.h"
using namespace std;
unsigned long hex2dec(string hex)
{
    unsigned long result = 0;
    for (int i=0; i<hex.length(); i++) {
        if (hex[i]>=48 && hex[i]<=57)
        {
            result += (hex[i]-48)*pow(16,hex.length()-i-1);
        } else if (hex[i]>=65 && hex[i]<=70) {
            result += (hex[i]-55)*pow(16,hex.length( )-i-1);
        } else if (hex[i]>=97 && hex[i]<=102) {
            result += (hex[i]-87)*pow(16,hex.length()-i-1);
        }
    }
    return result;
}

int main(int argc, const char * argv[]) {
    string hex_str;
    cin >> hex_str;
    cout << hex2dec(hex_str) << endl;
    return 0;
}

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

Rename multiple files in a directory in Python

Assuming you are already in the directory, and that the "first 8 characters" from your comment hold true always. (Although "CHEESE_" is 7 characters... ? If so, change the 8 below to 7)

from glob import glob
from os import rename
for fname in glob('*.prj'):
    rename(fname, fname[8:])

How to make a round button?

It is

android.R.drawable.expander_ic_minimized

look into built in android drawables:

http://androiddrawableexplorer.appspot.com/

SELECT FOR UPDATE with SQL Server

You cannot have snapshot isolation and blocking reads at the same time. The purpose of snapshot isolation is to prevent blocking reads.

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

I had the same issue and resolved by adding "Connection Time" value in web.config file. locate the connectionStrings and add Connection Timeout=3600"

here is the sample

  <connectionStrings>
    <add name="MyConn" providerName="System.Data.SqlClient" connectionString="Data Source=MySQLServer;Initial Catalog=MyDB;User ID=sa;Password=123;Connection Timeout=3600" />
  </connectionStrings>

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

What is the Swift equivalent to Objective-C's "@synchronized"?

With Swift's property wrappers, this is what I'm using now:

@propertyWrapper public struct NCCSerialized<Wrapped> {
    private let queue = DispatchQueue(label: "com.nuclearcyborg.NCCSerialized_\(UUID().uuidString)")

    private var _wrappedValue: Wrapped
    public var wrappedValue: Wrapped {
        get { queue.sync { _wrappedValue } }
        set { queue.sync { _wrappedValue = newValue } }
    }

    public init(wrappedValue: Wrapped) {
        self._wrappedValue = wrappedValue
    }
}

Then you can just do:

@NCCSerialized var foo: Int = 10

or

@NCCSerialized var myData: [SomeStruct] = []

Then access the variable as you normally would.

How to POST using HTTPclient content type = application/x-www-form-urlencoded

I was using a .Net Core 2.1 API with the [FromBody] attribute and I had to use the following solution to successfully Post to it:

_apiClient =  new HttpClient();
_apiClient.BaseAddress = new Uri(<YOUR API>);
var MyObject myObject = new MyObject(){
    FirstName = "Me",
    LastName = "Myself"
};

var stringified = JsonConvert.SerializeObject(myObject);
var result = await _apiClient.PostAsync("api/appusers", new StringContent(stringified, Encoding.UTF8, "application/json"));

ASP.NET Forms Authentication failed for the request. Reason: The ticket supplied has expired

I've had the same issue after using a web.config from another machine. The problem was related with an invalid MachineKey. To solve the problem, I modified the web.config to use the correct MachineKey of my server.

This MSDN blog post shows how to generate a MachineKey.

how to exit a python script in an if statement

This works fine for me:

while True:
   answer = input('Do you want to continue?:')
   if answer.lower().startswith("y"):
      print("ok, carry on then")
   elif answer.lower().startswith("n"):
      print("sayonara, Robocop")
      exit()

edit: use input in python 3.2 instead of raw_input

how to use sqltransaction in c#

The following example creates a SqlConnection and a SqlTransaction. It also demonstrates how to use the BeginTransaction, Commit, and Rollback methods. The transaction is rolled back on any error, or if it is disposed without first being committed. Try/Catch error handling is used to handle any errors when attempting to commit or roll back the transaction.

private static void ExecuteSqlTransaction(string connectionString)
{
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();

        SqlCommand command = connection.CreateCommand();
        SqlTransaction transaction;

        // Start a local transaction.
        transaction = connection.BeginTransaction("SampleTransaction");

        // Must assign both transaction object and connection 
        // to Command object for a pending local transaction
        command.Connection = connection;
        command.Transaction = transaction;

        try
        {
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (100, 'Description')";
            command.ExecuteNonQuery();
            command.CommandText =
                "Insert into Region (RegionID, RegionDescription) VALUES (101, 'Description')";
            command.ExecuteNonQuery();

            // Attempt to commit the transaction.
            transaction.Commit();
            Console.WriteLine("Both records are written to database.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("Commit Exception Type: {0}", ex.GetType());
            Console.WriteLine("  Message: {0}", ex.Message);

            // Attempt to roll back the transaction. 
            try
            {
                transaction.Rollback();
            }
            catch (Exception ex2)
            {
                // This catch block will handle any errors that may have occurred 
                // on the server that would cause the rollback to fail, such as 
                // a closed connection.
                Console.WriteLine("Rollback Exception Type: {0}", ex2.GetType());
                Console.WriteLine("  Message: {0}", ex2.Message);
            }
        }
    }
}

See SqlTransaction Class

htaccess remove index.php from url

Assuming the existent url is

http://example.com/index.php/foo/bar

and we want to convert it into

 http://example.com/foo/bar

You can use the following rule :

RewriteEngine on
#1) redirect the client from "/index.php/foo/bar" to "/foo/bar"
RewriteCond %{THE_REQUEST} /index\.php/(.+)\sHTTP [NC]
RewriteRule ^ /%1 [NE,L,R]
#2)internally map "/foo/bar" to "/index.php/foo/bar"
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ /index.php/$1 [L]

In the spep #1 we first match against the request string and capture everything after the /index.php/ and the captured value is saved in %1 var. We then send the browser to a new url. The #2 processes the request internally. When the browser arrives at /foo/bar , #2rule rewrites the new url to the orignal location.

How to add a custom Ribbon tab using VBA?

I was able to accomplish this with VBA in Excel 2013. No special editors needed. All you need is the Visual Basic code editor which can be accessed on the Developer tab. The Developer tab is not visible by default so it needs to be enabled in File>Options>Customize Ribbon. On the Developer tab, click the Visual Basic button. The code editor will launch. Right click in the Project Explorer pane on the left. Click the insert menu and choose module. Add both subs below to the new module.

Sub LoadCustRibbon()

Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String

hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"

ribbonXML = "<mso:customUI      xmlns:mso='http://schemas.microsoft.com/office/2009/07/customui'>" & vbNewLine
ribbonXML = ribbonXML + "  <mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + "    <mso:qat/>" & vbNewLine
ribbonXML = ribbonXML + "    <mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + "      <mso:tab id='reportTab' label='Reports' insertBeforeQ='mso:TabFormat'>" & vbNewLine
ribbonXML = ribbonXML + "        <mso:group id='reportGroup' label='Reports' autoScale='true'>" & vbNewLine
ribbonXML = ribbonXML + "          <mso:button id='runReport' label='PTO' "   & vbNewLine
ribbonXML = ribbonXML + "imageMso='AppointmentColor3'      onAction='GenReport'/>" & vbNewLine
ribbonXML = ribbonXML + "        </mso:group>" & vbNewLine
ribbonXML = ribbonXML + "      </mso:tab>" & vbNewLine
ribbonXML = ribbonXML + "    </mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + "  </mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + "</mso:customUI>"

ribbonXML = Replace(ribbonXML, """", "")

Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile

End Sub

Sub ClearCustRibbon()

Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String

hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"

ribbonXML = "<mso:customUI           xmlns:mso=""http://schemas.microsoft.com/office/2009/07/customui"">" & _
"<mso:ribbon></mso:ribbon></mso:customUI>"

Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile

End Sub

Call LoadCustRibbon sub in the Wookbook open even and call the ClearCustRibbon sub in the Before_Close Event of the ThisWorkbook code file.

Redis: How to access Redis log file

vi /usr/local/etc/redis.conf

Look for dir, logfile

# The working directory.
#
# The DB will be written inside this directory, with the filename specified
# above using the 'dbfilename' configuration directive.
#
# The Append Only File will also be created inside this directory.
#
# Note that you must specify a directory here, not a file name.
dir /usr/local/var/db/redis/



# Specify the log file name. Also the empty string can be used to force
# Redis to log on the standard output. Note that if you use standard
# output for logging but daemonize, logs will be sent to /dev/null 
logfile "redis_log"

So the log file is created at /usr/local/var/db/redis/redis_log with the name redis_log

You can also try MONITOR command from redis-cli to review the number of commands executed.

C# getting the path of %AppData%

For ASP.NET, the Load User Profile setting needs to be set on the app pool but that's not enough. There is a hidden setting named setProfileEnvironment in \Windows\System32\inetsrv\Config\applicationHost.config, which for some reason is turned off by default, instead of on as described in the documentation. You can either change the default or set it on your app pool. All the methods on the Environment class will then return proper values.

How to start MySQL with --skip-grant-tables?

I had the same problem as the title of this question, so incase anyone else googles upon this question and wants to start MySql in 'skip-grant-tables' mode on Windows, here is what I did.

Stop the MySQL service through Administrator tools, Services.

Modify the my.ini configuration file (assuming default paths)

C:\Program Files\MySQL\MySQL Server 5.5\my.ini

or for MySQL version >= 5.6

C:\ProgramData\MySQL\MySQL Server 5.6\my.ini 

In the SERVER SECTION, under [mysqld], add the following line:

skip-grant-tables

so that you have

# SERVER SECTION
# ----------------------------------------------------------------------
#
# The following options will be read by the MySQL Server. Make sure that
# you have installed the server correctly (see above) so it reads this 
# file.
#
[mysqld]

skip-grant-tables

Start the service again and you should be able to log into your database without a password.

php how to go one level up on dirname(__FILE__)

You could use PHP's dirname function. <?php echo dirname(__DIR__); ?>. That will give you the name of the parent directory of __DIR__, which stores the current directory.

"Cannot evaluate expression because the code of the current method is optimized" in Visual Studio 2010

It sounds like you are debugging an optimised / release build, despite having the optimised box un-checked. Things you can try are:

  • Do a complete rebuild of your solution file (right click on the solution and select Rebuild all)
  • While debugging open up the modules window (Debug -> Windows -> Modules) and find your assembly in the list of loaded modules. Check that the Path listed against your loaded assembly is what you expect it to be, and that the modified timestamp of the file indicates that the assembly was actually rebuilt.
  • The modules window should also tell you whether or not the loaded module is optimised or not - make sure that the modules window indicates that it is not optimised.

If you cant't see the Modules menu item in the Debug -> Windows menu then you may need to add it in the "Customise..." menu.

How to get a substring between two strings in PHP?

A bit improved code from GarciaWebDev and Henry Wang. If empty $start or $end is given, function returns values from the beginning or to the end of the $string. Also Inclusive option is available, whether we want to include search result or not:

function get_string_between ($string, $start, $end, $inclusive = false){
    $string = " ".$string;

    if ($start == "") { $ini = 0; }
    else { $ini = strpos($string, $start); }

    if ($end == "") { $len = strlen($string); }
    else { $len = strpos($string, $end, $ini) - $ini;}

    if (!$inclusive) { $ini += strlen($start); }
    else { $len += strlen($end); }

    return substr($string, $ini, $len);
}

How can I count the occurrences of a string within a file?

if you just want the number of occurences then you can do this, $ grep -c "string_to_count" file_name

Is there shorthand for returning a default value if None in Python?

return "default" if x is None else x

try the above.

how to call a variable in code behind to aspx page

Make sure that you have compiled your *.cs file before browsing the ASPX page.

Keylistener in Javascript

The code is

document.addEventListener('keydown', function(event){
    alert(event.keyCode);
} );

This return the ascii code of the key. If you need the key representation, use event.key (This will return 'a', 'o', 'Alt'...)

Regex to get NUMBER only from String

\d+

\d represents any digit, + for one or more. If you want to catch negative numbers as well you can use -?\d+.

Note that as a string, it should be represented in C# as "\\d+", or @"\d+"

Xcode5 "No matching provisioning profiles found issue" (but good at xcode4)

Here's a simpler solution that worked for me:

In XCode5, double-click on your app's target. This brings up the Info pane for the target. In the "Build Settings" section, check the "code signing" section for any old profiles and replace with the correct one. update the value of "code signing identity" and "provisioning profile"

Can't change z-index with JQuery

That's invalid Javascript syntax; a property name cannot have a -.

Use either zIndex or "z-index".

How to accept Date params in a GET request to Spring MVC Controller?

This is what I did to get formatted date from front end

  @RequestMapping(value = "/{dateString}", method = RequestMethod.GET)
  @ResponseBody
  public HttpStatus getSomething(@PathVariable @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) String dateString) {
   return OK;
  }

You can use it to get what you want.

What type of hash does WordPress use?

include_once('../../../wp-config.php');

global $wpdb;

$password = wp_hash_password("your password");

Disable button after click in JQuery

*Updated

jQuery version would be something like below:

function load(recieving_id){
    $('#roommate_but').prop('disabled', true);
    $.get('include.inc.php?i=' + recieving_id, function(data) {
        $("#roommate_but").html(data);
    });
}

Deserialize JSON array(or list) in C#

This code works for me:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;

namespace Json
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(DeserializeNames());
            Console.ReadLine();
        }

        public static string DeserializeNames()
        {
            var jsonData = "{\"name\":[{\"last\":\"Smith\"},{\"last\":\"Doe\"}]}";

            JavaScriptSerializer ser = new JavaScriptSerializer();

            nameList myNames = ser.Deserialize<nameList>(jsonData);

            return ser.Serialize(myNames);
        }

        //Class descriptions

        public class name
        {
            public string last { get; set; }
        }

        public class nameList
        {
            public List<name> name { get; set; }
        }
    }
}

Missing `server' JVM (Java\jre7\bin\server\jvm.dll.)

To Fix The "Missing "server" JVM at C:\Program Files\Java\jre7\bin\server\jvm­­.dll, please install or use the JRE or JDK that contains these missing components.

Follow these steps:

Go to oracle.com and install Java JRE7 (Check if Java 6 is not installed already)

After that, go to C:/Program files/java/jre7/bin

Here, create an folder called Server

Now go into the C:/Program files/java/jre7/bin/client folder

Copy all the data in this folder into the new C:/Program files/java/jre7/bin/Server folder

VLook-Up Match first 3 characters of one column with another column

=VLOOKUP(LEFT(A1,3),LEFT(B$2:B$22,3), 1,FALSE)

LEFT() truncates the first n character of a string, and you need to do it in both columns. The third parameter of VLOOKUP is the number of the column to return with. So if your range is not only B$2:B$22 but B$2:C$22 you can choose to return with column B value (1) or column C value (2)

How can I update window.location.hash without jumping the document?

I'm not sure if you can alter the original element but how about switch from using the id attr to something else like data-id? Then just read the value of data-id for your hash value and it won't jump.

Javascript: How to check if a string is empty?

But for a better check:

if(str === null || str === '')
{
    //enter code here
}

How to get the hostname of the docker host from inside a docker container on that host without env vars

You can pass in the hostname as an environment variable. You could also mount /etc so you can cat /etc/hostname. But I agree with Vitaly, this isn't the intended use case for containers IMO.

Split string into string array of single characters

You can just use String.ToCharArray() and then treat each char as a string in your code.

Here's an example:

    foreach (char c in s.ToCharArray())
        Debug.Log("one character ... " +c);

Simulate limited bandwidth from within Chrome?

As suggested on the Chrome Mobile Emulation page, you can use Clumsy on Windows, Network Link Conditioner on Mac OS X and dummynet on Linux.

How to catch SQLServer timeout exceptions

Whats the value for the SqlException.ErrorCode property? Can you work with that?

When having timeouts, it may be worth checking the code for -2146232060.

I would set this up as a static const in your data code.

Best way to check if object exists in Entity Framework?

I had to manage a scenario where the percentage of duplicates being provided in the new data records was very high, and so many thousands of database calls were being made to check for duplicates (so the CPU sent a lot of time at 100%). In the end I decided to keep the last 100,000 records cached in memory. This way I could check for duplicates against the cached records which was extremely fast when compared to a LINQ query against the SQL database, and then write any genuinely new records to the database (as well as add them to the data cache, which I also sorted and trimmed to keep its length manageable).

Note that the raw data was a CSV file that contained many individual records that had to be parsed. The records in each consecutive file (which came at a rate of about 1 every 5 minutes) overlapped considerably, hence the high percentage of duplicates.

In short, if you have timestamped raw data coming in, pretty much in order, then using a memory cache might help with the record duplication check.

Skip Git commit hooks

Maybe (from git commit man page):

git commit --no-verify

-n  
--no-verify

This option bypasses the pre-commit and commit-msg hooks. See also githooks(5).

As commented by Blaise, -n can have a different role for certain commands.
For instance, git push -n is actually a dry-run push.
Only git push --no-verify would skip the hook.


Note: Git 2.14.x/2.15 improves the --no-verify behavior:

See commit 680ee55 (14 Aug 2017) by Kevin Willford (``).
(Merged by Junio C Hamano -- gitster -- in commit c3e034f, 23 Aug 2017)

commit: skip discarding the index if there is no pre-commit hook

"git commit" used to discard the index and re-read from the filesystem just in case the pre-commit hook has updated it in the middle; this has been optimized out when we know we do not run the pre-commit hook.


Davi Lima points out in the comments the git cherry-pick does not support --no-verify.
So if a cherry-pick triggers a pre-commit hook, you might, as in this blog post, have to comment/disable somehow that hook in order for your git cherry-pick to proceed.
The same process would be necessary in case of a git rebase --continue, after a merge conflict resolution.

String field value length in mongoDB

I had a similar kind of scenario, but in my case string is not a 1st level attribute. It is inside an object. In here I couldn't find a suitable answer for it. So I thought to share my solution with you all(Hope this will help anyone with a similar kind of problem).

Parent Collection 

{
"Child":
{
"name":"Random Name",
"Age:"09"
}
}

Ex: If we need to get only collections that having child's name's length is higher than 10 characters.

 db.getCollection('Parent').find({$where: function() { 
for (var field in this.Child.name) { 
    if (this.Child.name.length > 10) 
        return true;

}
}})

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");

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

Here is an easy way with String output (I created a method to do this):

public static String (String input){
    String output = "";
    try {
        /* From ISO-8859-1 to UTF-8 */
        output = new String(input.getBytes("ISO-8859-1"), "UTF-8");
        /* From UTF-8 to ISO-8859-1 */
        output = new String(input.getBytes("UTF-8"), "ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return output;
}
// Example
input = "Música";
output = "Música";

Remove characters from C# string

I make it extension method and with string array, I think string[] is more useful than char[] because char can also be string:

public static class Helper
{
    public static string RemoverStrs(this string str, string[] removeStrs)
    {
        foreach (var removeStr in removeStrs)
            str = str.Replace(removeStr, "");
        return str;
    }
}

then you can use it anywhere:

string myname = "My name @is ,Wan.;'; Wan";
string result = myname.RemoveStrs(new[]{ "@", ",", ".", ";", "\\"});

What primitive data type is time_t?

You could always use something like mktime to create a known time (midnight, last night) and use difftime to get a double-precision time difference between the two. For a platform-independant solution, unless you go digging into the details of your libraries, you're not going to do much better than that. According to the C spec, the definition of time_t is implementation-defined (meaning that each implementation of the library can define it however they like, as long as library functions with use it behave according to the spec.)

That being said, the size of time_t on my linux machine is 8 bytes, which suggests a long int or a double. So I did:

int main()
{
    for(;;)
    {
        printf ("%ld\n", time(NULL));
        printf ("%f\n", time(NULL));
        sleep(1);
    }
    return 0;
}

The time given by the %ld increased by one each step and the float printed 0.000 each time. If you're hell-bent on using printf to display time_ts, your best bet is to try your own such experiment and see how it work out on your platform and with your compiler.

Is there an eval() function in Java?

There is no standard Java class or method that will do what you want. Your options include:

  • Select and use some third-party expression evaluation library. For example JEL or any of the half dozen libraries listed here.

  • Wrap the expression in the Java source code for a class with an eval method, send that to the Java compiler, and then load the resulting compiled class.

  • Use some scripting language that can be called from Java as an expression evaluator. Possibilities include Javascript, BeanShell, and so on.

  • Write your own expression evaluator from scratch.

The first approach is probably simplest. The second and third approaches are a potential security risk if you get the expression to be evaluated from an untrusted user. (Think code injection.)

REST API Best practice: How to accept list of parameter values as input

First case:

A normal product lookup would look like this

http://our.api.com/product/1

So Im thinking that best practice would be for you to do this

http://our.api.com/Product/101404,7267261

Second Case

Search with querystring parameters - fine like this. I would be tempted to combine terms with AND and OR instead of using [].

PS This can be subjective, so do what you feel comfortable with.

The reason for putting the data in the url is so the link can pasted on a site/ shared between users. If this isnt an issue, by all means use a JSON/ POST instead.

EDIT: On reflection I think this approach suits an entity with a compound key, but not a query for multiple entities.

How to make tesseract to recognize only numbers, when they are mixed with letters?

For tesseract 3, the command is simpler tesseract imagename outputbase digits according to the FAQ. But it doesn't work for me very well.

I turn to try different psm options and find -psm 6 works best for my case.

man tesseract for details.

PHP calculate age

You can use the Carbon library, which is an API extension for DateTime.

You can:

function calculate_age($date) {
    $date = new \Carbon\Carbon($date);
    return (int) $date->diffInYears();
}

or:

$age = (new \Carbon\Carbon($date))->age;

Process escape sequences in a string in Python

The (currently) accepted answer by Jerub is correct for python2, but incorrect and may produce garbled results (as Apalala points out in a comment to that solution), for python3. That's because the unicode_escape codec requires its source to be coded in latin-1, not utf-8, as per the official python docs. Hence, in python3 use:

>>> myString="špåm\\nëðþ\\x73"
>>> print(myString)
špåm\nëðþ\x73
>>> decoded_string = myString.encode('latin-1','backslashreplace').decode('unicode_escape')
>>> print(decoded_string)
špåm
ëðþs

This method also avoids the extra unnecessary roundtrip between strings and bytes in metatoaster's comments to Jerub's solution (but hats off to metatoaster for recognizing the bug in that solution).

Enabling error display in PHP via htaccess only

.htaccess:

php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag  log_errors on
php_value error_log  /home/path/public_html/domain/PHP_errors.log

Entity framework left join

For 2 and more left joins (left joining creatorUser and initiatorUser )

IQueryable<CreateRequestModel> queryResult = from r in authContext.Requests
                                             join candidateUser in authContext.AuthUsers
                                             on r.CandidateId equals candidateUser.Id
                                             join creatorUser in authContext.AuthUsers
                                             on r.CreatorId equals creatorUser.Id into gj
                                             from x in gj.DefaultIfEmpty()
                                             join initiatorUser in authContext.AuthUsers
                                             on r.InitiatorId equals initiatorUser.Id into init
                                             from x1 in init.DefaultIfEmpty()

                                             where candidateUser.UserName.Equals(candidateUsername)
                                             select new CreateRequestModel
                                             {
                                                 UserName = candidateUser.UserName,
                                                 CreatorId = (x == null ? String.Empty : x.UserName),
                                                 InitiatorId = (x1 == null ? String.Empty : x1.UserName),
                                                 CandidateId = candidateUser.UserName
                                             };

Check which element has been clicked with jQuery

The basis of jQuery is the ability to find items in the DOM through selectors, and then checking properties on those selectors. Read up on Selectors here:

http://api.jquery.com/category/selectors/

However, it would make more sense to create event handlers for the click events for the different functionality that should occur based on what is clicked.

Tkinter example code for multiple windows, why won't buttons load correctly?

I tried to use more than two windows using the Rushy Panchal example above. The intent was to have the change to call more windows with different widgets in them. The butnew function creates different buttons to open different windows. You pass as argument the name of the class containing the window (the second argument is nt necessary, I put it there just to test a possible use. It could be interesting to inherit from another window the widgets in common.

import tkinter as tk

class Demo1:
    def __init__(self, master):
        self.master = master
        self.master.geometry("400x400")
        self.frame = tk.Frame(self.master)
        self.butnew("Window 1", "ONE", Demo2)
        self.butnew("Window 2", "TWO", Demo3)
        self.frame.pack()

    def butnew(self, text, number, _class):
        tk.Button(self.frame, text = text, width = 25, command = lambda: self.new_window(number, _class)).pack()

    def new_window(self, number, _class):
        self.newWindow = tk.Toplevel(self.master)
        _class(self.newWindow, number)


class Demo2:
    def __init__(self, master, number):
        self.master = master
        self.master.geometry("400x400+400+400")
        self.frame = tk.Frame(self.master)
        self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.label = tk.Label(master, text=f"this is window number {number}")
        self.label.pack()
        self.quitButton.pack()
        self.frame.pack()

    def close_windows(self):
        self.master.destroy()

class Demo3:
    def __init__(self, master, number):
        self.master = master
        self.master.geometry("400x400+400+400")
        self.frame = tk.Frame(self.master)
        self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25, command = self.close_windows)
        self.label = tk.Label(master, text=f"this is window number {number}")
        self.label.pack()
        self.label2 = tk.Label(master, text="THIS IS HERE TO DIFFERENTIATE THIS WINDOW")
        self.label2.pack()
        self.quitButton.pack()
        self.frame.pack()

    def close_windows(self):
        self.master.destroy()




def main(): 
    root = tk.Tk()
    app = Demo1(root)
    root.mainloop()

if __name__ == '__main__':
    main()

Open the new window only once

To avoid having the chance to press multiple times the button having multiple windows... that are the same window, I made this script (take a look at this page too)

import tkinter as tk


def new_window1():
    global win1
    try:
        if win1.state() == "normal": win1.focus()
    except:
        win1 = tk.Toplevel()
        win1.geometry("300x300+500+200")
        win1["bg"] = "navy"
        lb = tk.Label(win1, text="Hello")
        lb.pack()


win = tk.Tk()
win.geometry("200x200+200+100")
button = tk.Button(win, text="Open new Window")
button['command'] = new_window1
button.pack()
win.mainloop()

Gradients in Internet Explorer 9

IE9 currently lacks CSS3 gradient support. However, here is a nice workaround solution using PHP to return an SVG (vertical linear) gradient instead, which allows us to keep our design in our stylesheets.

<?php

$from_stop = isset($_GET['from']) ? $_GET['from'] : '000000';
$to_stop = isset($_GET['to']) ? $_GET['to'] : '000000';

header('Content-type: image/svg+xml; charset=utf-8');

echo '<?xml version="1.0"?>
';

?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%">
    <defs>
        <linearGradient id="linear-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
            <stop offset="0%" stop-color="#<?php echo $from_stop; ?>" stop-opacity="1"/>
            <stop offset="100%" stop-color="#<?php echo $to_stop; ?>" stop-opacity="1"/>
        </linearGradient>
    </defs>
    <rect width="100%" height="100%" fill="url(#linear-gradient)"/>
</svg>

Simply upload it to your server and call the URL like so:

gradient.php?from=f00&to=00f

This can be used in conjunction with your CSS3 gradients like this:

.my-color {
    background-color: #f00;
    background-image: url(gradient.php?from=f00&to=00f);
    background-image: -webkit-gradient(linear, left top, left bottom, from(#f00), to(#00f));
    background-image: -webkit-linear-gradient(top, #f00, #00f);
    background-image: -moz-linear-gradient(top, #f00, #00f);
    background-image: linear-gradient(top, #f00, #00f);
}

If you need to target below IE9, you can still use the old proprietary 'filter' method:

.ie7 .my-color, .ie8 .my-color {
    filter: progid:DXImageTransform.Microsoft.Gradient(startColorStr="#ff0000", endColorStr="#0000ff");
}

Of course you can amend the PHP code to add more stops on the gradient, or make it more sophisticated (radial gradients, transparency etc.) but this is great for those simple (vertical) linear gradients.

trace a particular IP and port

You can use the default traceroute command for this purpose, then there will be nothing to install.

traceroute -T -p 9100 <IP address/hostname>

The -T argument is required so that the TCP protocol is used instead of UDP.

In the rare case when traceroute isn't available, you can also use ncat.

nc -Czvw 5 <IP address/hostname> 9100

How to create the branch from specific commit in different branch

You have the arguments in the wrong order:

git branch <branch-name> <commit>

and for that, it doesn't matter what branch is checked out; it'll do what you say. (If you omit the commit argument, it defaults to creating a branch at the same place as the current one.)

If you want to check out the new branch as you create it:

git checkout -b <branch> <commit>

with the same behavior if you omit the commit argument.

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

More simply in one line:

proxy=192.168.2.1:8080;curl -v example.com

eg. $proxy=192.168.2.1:8080;curl -v example.com

xxxxxxxxx-ASUS:~$ proxy=192.168.2.1:8080;curl -v https://google.com|head -c 15 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0

  • Trying 172.217.163.46:443...
  • TCP_NODELAY set
  • Connected to google.com (172.217.163.46) port 443 (#0)
  • ALPN, offering h2
  • ALPN, offering http/1.1
  • successfully set certificate verify locations:
  • CAfile: /etc/ssl/certs/ca-certificates.crt CApath: /etc/ssl/certs } [5 bytes data]
  • TLSv1.3 (OUT), TLS handshake, Client hello (1): } [512 bytes data]

Getting time span between two times in C#?

string startTime = "7:00 AM";
string endTime = "2:00 PM";

TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));

Console.WriteLine(duration);
Console.ReadKey();

Will output: 07:00:00.

It also works if the user input military time:

string startTime = "7:00";
string endTime = "14:00";

TimeSpan duration = DateTime.Parse(endTime).Subtract(DateTime.Parse(startTime));

Console.WriteLine(duration);
Console.ReadKey();

Outputs: 07:00:00.

To change the format: duration.ToString(@"hh\:mm")

More info at: http://msdn.microsoft.com/en-us/library/ee372287.aspx

Addendum:

Over the years it has somewhat bothered me that this is the most popular answer I have ever given; the original answer never actually explained why the OP's code didn't work despite the fact that it is perfectly valid. The only reason it gets so many votes is because the post comes up on Google when people search for a combination of the terms "C#", "timespan", and "between".

WHERE vs HAVING

Having is only used with aggregation but where with non aggregation statements If you have where word put it before aggregation (group by)

Delete statement in SQL is very slow

Check execution plan of this delete statement. Have a look if index seek is used. Also what is data type of col?

If you are using wrong data type, change update statement (like from '1' to 1 or N'1').

If index scan is used consider using some query hint..

Suppress warning messages using mysql from within Terminal, but password written in bash script

Another solution (from a script, for example):

 sed -i'' -e "s/password=.*\$/password=$pass/g" ~/.my.cnf
 mysql -h $host -u $user $db_name -e "$sql_cmd"

The -i'' option is here for compatibility with Mac OS X. Standard UNIX OSes can use straight -i

How do I prevent people from doing XSS in Spring MVC?

**To avoid XSS security threat in spring application**

solution to the XSS issue is to filter all the textfields in the form at the time of submitting the form.

    It needs XML entry in the web.xml file & two simple classes.

        java code :-
        The code for the  first class named CrossScriptingFilter.java is :

        package com.filter;

        import java.io.IOException;
        import javax.servlet.Filter;
        import javax.servlet.FilterChain;
        import javax.servlet.FilterConfig;
        import javax.servlet.ServletException;
        import javax.servlet.ServletRequest;
        import javax.servlet.ServletResponse;
        import javax.servlet.http.HttpServletRequest;
        import org.apache.log4j.Logger;

        public class CrossScriptingFilter implements Filter {
            private static Logger logger = Logger.getLogger(CrossScriptingFilter.class);
            private FilterConfig filterConfig;

            public void init(FilterConfig filterConfig) throws ServletException {
                this.filterConfig = filterConfig;
            }

            public void destroy() {
                this.filterConfig = null;
            }

            public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
                logger.info("Inlter CrossScriptingFilter  ...............");
                chain.doFilter(new RequestWrapper((HttpServletRequest) request), response);
                logger.info("Outlter CrossScriptingFilter ...............");
            }

        }

The code second class named RequestWrapper.java is :

package com.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.log4j.Logger;

public final class RequestWrapper extends HttpServletRequestWrapper {
    private static Logger logger = Logger.getLogger(RequestWrapper.class);
    public RequestWrapper(HttpServletRequest servletRequest) {
        super(servletRequest);
    }

    public String[] getParameterValues(String parameter) {
        logger.info("InarameterValues .. parameter .......");
        String[] values = super.getParameterValues(parameter);
        if (values == null) {
            return null;
        }
        int count = values.length;
        String[] encodedValues = new String[count];
        for (int i = 0; i < count; i++) {
            encodedValues[i] = cleanXSS(values[i]);
        }
        return encodedValues;
    }

    public String getParameter(String parameter) {
        logger.info("Inarameter .. parameter .......");
        String value = super.getParameter(parameter);
        if (value == null) {
            return null;
        }
        logger.info("Inarameter RequestWrapper ........ value .......");
        return cleanXSS(value);
    }

    public String getHeader(String name) {
        logger.info("Ineader .. parameter .......");
        String value = super.getHeader(name);
        if (value == null)
            return null;
        logger.info("Ineader RequestWrapper ........... value ....");
        return cleanXSS(value);
    }

    private String cleanXSS(String value) {
        // You'll need to remove the spaces from the html entities below
        logger.info("InnXSS RequestWrapper ..............." + value);
        //value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
        //value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
        //value = value.replaceAll("'", "& #39;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");

        value = value.replaceAll("(?i)<script.*?>.*?<script.*?>", "");
        value = value.replaceAll("(?i)<script.*?>.*?</script.*?>", "");
        value = value.replaceAll("(?i)<.*?javascript:.*?>.*?</.*?>", "");
        value = value.replaceAll("(?i)<.*?\\s+on.*?>.*?</.*?>", "");
        //value = value.replaceAll("<script>", "");
        //value = value.replaceAll("</script>", "");
        logger.info("OutnXSS RequestWrapper ........ value ......." + value);
        return value;
    }

The only thing remained is the XML entry in the web.xml file:

        <filter>
        <filter-name>XSS</filter-name>
        <display-name>XSS</display-name>
        <description></description>
        <filter-class>com.filter.CrossScriptingFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>XSS</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

The /* indicates that for every request made from browser, it will call CrossScriptingFilter class. Which will parse all the components/elements came from the request & will replace all the javascript tags put by hacker with empty string i.e

How can I scale an image in a CSS sprite

Set the width and height to wrapper element of the sprite image. Use this css.

{
    background-size: cover;
}

Download a file from NodeJS Server using Express

Use res.download()

It transfers the file at path as an “attachment”. For instance:

var express = require('express');
var router = express.Router();

// ...

router.get('/:id/download', function (req, res, next) {
    var filePath = "/my/file/path/..."; // Or format the path using the `id` rest param
    var fileName = "report.pdf"; // The default name the browser will use

    res.download(filePath, fileName);    
});

How to make CREATE OR REPLACE VIEW work in SQL Server?

Here is another method, where you don't have to duplicate the contents of the view:

IF (NOT EXISTS (SELECT 1 FROM sys.views WHERE name = 'data_VVV'))
BEGIN
    EXECUTE('CREATE VIEW data_VVVV as SELECT 1 as t');
END;

GO

ALTER VIEW data_VVVV AS 
    SELECT VCV.xxxx, VCV.yyyy AS yyyy, VCV.zzzz AS zzzz FROM TABLE_A ;

The first checks for the existence of the view (there are other ways to do this). If it doesn't exist, then create it with something simple and dumb. If it does, then just move on to the alter view statement.

How to remove td border with html?

Surround it with a div and give it a border and remove the border from the table

<div style="border: 1px solid black">
    <table border="0">
        <tr>
            <td>one</td>
            <td>two</td>
        </tr>
        <tr>
            <td>one</td>
            <td>two</td>
        </tr>
    </table>
</div>

You can check the working fiddle here


As per your updated question .... where you want to add or remove borders. You should remove borders from the html table first and then do the following

<td style="border-top: 1px solid black">

Assuming like you only want the top border. Similarly you have to do for others. Better way create four css class...

.topBorderOnly {
    border-top: 1px solid black;
}

.bottomBorderOnly {
    border-bottom: 1px solid black;
}

Then add the css to your code depending on the requirements.

<td class="topBorderOnly bottomBorderOnly">  

This will add both top and bottom border, similarly do for the rest.

Select Tag Helper in ASP.NET Core MVC

In Get:

public IActionResult Create()
{
    ViewData["Tags"] = new SelectList(_context.Tags, "Id", "Name");
    return View();
}

In Post:

var selectedIds= Request.Form["Tags"];

In View :

<label>Tags</label>
<select  asp-for="Tags"  id="Tags" name="Tags" class="form-control" asp-items="ViewBag.Tags" multiple></select>

c++ bool question

false == 0 and true = !false

i.e. anything that is not zero and can be converted to a boolean is not false, thus it must be true.

Some examples to clarify:

if(0)          // false
if(1)          // true
if(2)          // true
if(0 == false) // true
if(0 == true)  // false
if(1 == false) // false
if(1 == true)  // true
if(2 == false) // false
if(2 == true)  // false
cout << false  // 0
cout << true   // 1

true evaluates to 1, but any int that is not false (i.e. 0) evaluates to true but is not equal to true since it isn't equal to 1.

How to get AM/PM from a datetime in PHP

Use strtotime() to make the date a UNIX timestamp.

For output, check out the various options of date().

$timestamp = strtotime("08/04/2010 22:15:00");
date("h.i A", $timestamp);

Where do I mark a lambda expression async?

And for those of you using an anonymous expression:

await Task.Run(async () =>
{
   SQLLiteUtils slu = new SQLiteUtils();
   await slu.DeleteGroupAsync(groupname);
});

How to read until end of file (EOF) using BufferedReader in Java?

You are consuming a line at, which is discarded

while((str=input.readLine())!=null && str.length()!=0)

and reading a bigint at

BigInteger n = new BigInteger(input.readLine());

so try getting the bigint from string which is read as

BigInteger n = new BigInteger(str);

   Constructor used: BigInteger(String val)

Aslo change while((str=input.readLine())!=null && str.length()!=0) to

while((str=input.readLine())!=null)

see related post string to bigint

readLine()
Returns:
    A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached 

see javadocs

DB2 Date format

This isn't straightforward, but

SELECT CHAR(CURRENT DATE, ISO) FROM SYSIBM.SYSDUMMY1

returns the current date in yyyy-mm-dd format. You would have to substring and concatenate the result to get yyyymmdd.

SELECT SUBSTR(CHAR(CURRENT DATE, ISO), 1, 4) ||
    SUBSTR(CHAR(CURRENT DATE, ISO), 6, 2) ||
    SUBSTR(CHAR(CURRENT DATE, ISO), 9, 2)
FROM SYSIBM.SYSDUMMY1

How can I align all elements to the left in JPanel?

The easiest way I've found to place objects on the left is using FlowLayout.

JPanel panel = new JPanel(new FlowLayout(FlowLayout.LEFT));

adding a component normally to this panel will place it on the left