Programs & Examples On #Sqlparameter

Assign null to a SqlParameter

In my opinion the better way is to do this with the Parameters property of the SqlCommand class:

public static void AddCommandParameter(SqlCommand myCommand)
{
    myCommand.Parameters.AddWithValue(
        "@AgeIndex",
        (AgeItem.AgeIndex== null) ? DBNull.Value : AgeItem.AgeIndex);
}

C# string reference type?

If we have to answer the question: String is a reference type and it behaves as a reference. We pass a parameter that holds a reference to, not the actual string. The problem is in the function:

public static void TestI(string test)
{
    test = "after passing";
}

The parameter test holds a reference to the string but it is a copy. We have two variables pointing to the string. And because any operations with strings actually create a new object, we make our local copy to point to the new string. But the original test variable is not changed.

The suggested solutions to put ref in the function declaration and in the invocation work because we will not pass the value of the test variable but will pass just a reference to it. Thus any changes inside the function will reflect the original variable.

I want to repeat at the end: String is a reference type but since its immutable the line test = "after passing"; actually creates a new object and our copy of the variable test is changed to point to the new string.

Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>

The complete markup should be along these lines:

<select>
    <option selected disabled>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

You can take a look at this fiddle, and here's the result:

enter image description here

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

<select>
    <option selected disabled hidden>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

Check the fiddle here and the screenshot below.

enter image description here


Here is the solution:

<select>
    <option style="display:none;" selected>Select language</option>
    <option>Option 1</option>
    <option>Option 2</option>
</select>

Reverse / invert a dictionary mapping

Python 3+:

inv_map = {v: k for k, v in my_map.items()}

Python 2:

inv_map = {v: k for k, v in my_map.iteritems()}

How to convert a single char into an int

Or you could use the "correct" method, similar to your original atoi approach, but with std::stringstream instead. That should work with chars as input as well as strings. (boost::lexical_cast is another option for a more convenient syntax)

(atoi is an old C function, and it's generally recommended to use the more flexible and typesafe C++ equivalents where possible. std::stringstream covers conversion to and from strings)

How to display alt text for an image in chrome

Yes it's an issue in webkit and also reported in chromium: http://code.google.com/p/chromium/issues/detail?id=773 It's there since 2008... and still not fixed!!

I'm using a piece of javacsript and jQuery to make my way around this.

function showAlt(){$(this).replaceWith(this.alt)};
function addShowAlt(selector){$(selector).error(showAlt).attr("src", $(selector).src)};
addShowAlt("img");

If you only want one some images:

addShowAlt("#myImgID");

curl Failed to connect to localhost port 80

Since you have a ::1 localhost line in your hosts file, it would seem that curl is attempting to use IPv6 to contact your local web server.

Since the web server is not listening on IPv6, the connection fails.

You could try to use the --ipv4 option to curl, which should force an IPv4 connection when both are available.

Chrome dev tools fails to show response even the content returned has header Content-Type:text/html; charset=UTF-8

For those coming here from Google, and for whom the previous answers do not solve the mystery...

If you use XHR to make a server call, but do not return a response, this error will occur.

Example (from Nodejs/React but could equally be js/php):

App.tsx

const handleClickEvent = () => {
    fetch('/routeInAppjs?someVar=someValue&nutherVar=summat_else', {
        method: 'GET',
        mode: 'same-origin',
        credentials: 'include',
        headers: {
          'content-type': 'application/json',
          dataType: 'json',
        },
    }).then((response) => {
        console.log(response)
    });
}

App.js

app.route('/getAllPublicDatasheets').get(async function (req, res) {
    const { someVar, nutherVar } = req.query;
    console.log('Ending here without a return...')
});

Console.log will here report:

Failed to show response data

To fix, add the return response to bottom of your route (server-side):

res.json('Adding this below the console.log in App.js route will solve it.');

How to select date from datetime column?

Using WHERE DATE(datetime) = '2009-10-20' has performance issues. As stated here:

  • it will calculate DATE() for all rows, including those that don't match.
  • it will make it impossible to use an index for the query.

Use BETWEEN or >, <, = operators which allow to use an index:

SELECT * FROM data 
WHERE datetime BETWEEN '2009-10-20 00:00:00' AND '2009-10-20 23:59:59'

Update: the impact on using LIKE instead of operators in an indexed column is high. These are some test results on a table with 1,176,000 rows:

  • using datetime LIKE '2009-10-20%' => 2931ms
  • using datetime >= '2009-10-20 00:00:00' AND datetime <= '2009-10-20 23:59:59' => 168ms

When doing a second call over the same query the difference is even higher: 2984ms vs 7ms (yes, just 7 milliseconds!). I found this while rewriting some old code on a project using Hibernate.

Undo git stash pop that results in merge conflict

git checkout -f

must work, if your previous state is clean.

How to create an array of 20 random bytes?

For those wanting a more secure way to create a random byte array, yes the most secure way is:

byte[] bytes = new byte[20];
SecureRandom.getInstanceStrong().nextBytes(bytes);

BUT your threads might block if there is not enough randomness available on the machine, depending on your OS. The following solution will not block:

SecureRandom random = new SecureRandom();
byte[] bytes = new byte[20];
random.nextBytes(bytes);

This is because the first example uses /dev/random and will block while waiting for more randomness (generated by a mouse/keyboard and other sources). The second example uses /dev/urandom which will not block.

jQuery ui datepicker with Angularjs

angular.module('elnApp')
.directive('jqdatepicker', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ctrl) {
            $(element).datepicker({
                dateFormat: 'dd.mm.yy',
                onSelect: function(date) {
                    ctrl.$setViewValue(date);
                    ctrl.$render();
                    scope.$apply();
                }
            });
        }
    };
});

How to get the category title in a post in Wordpress?

You can use

<?php the_category(', '); ?>

which would output them in a comma separated list.

You can also do the same for tags as well:

<?php the_tags('<em>:</em>', ', ', ''); ?>

Using for loop inside of a JSP

You concrete problem is caused because you're mixing discouraged and old school scriptlets <% %> with its successor EL ${}. They do not share the same variable scope. The allFestivals is not available in scriptlet scope and the i is not available in EL scope.

You should install JSTL (<-- click the link for instructions) and declare it in top of JSP as follows:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

and then iterate over the list as follows:

<c:forEach items="${allFestivals}" var="festival">
    <tr>      
        <td>${festival.festivalName}</td>
        <td>${festival.location}</td>
        <td>${festival.startDate}</td>
        <td>${festival.endDate}</td>
        <td>${festival.URL}</td>  
    </tr>
</c:forEach>

(beware of possible XSS attack holes, use <c:out> accordingly)

Don't forget to remove the <jsp:useBean> as it has no utter value here when you're using a servlet as model-and-view controller. It would only lead to confusion. See also our servlets wiki page. Further you would do yourself a favour to disable scriptlets by the following entry in web.xml so that you won't accidently use them:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
</jsp-config>

HTML combo box with option to type an entry

This one is much smaller, doesn't require jquery and works better in safari. https://github.com/Fyrd/purejs-datalist-polyfill/

Check the issues for the modification to add a downarrow. https://github.com/Fyrd/purejs-datalist-polyfill/issues

Using SQL LOADER in Oracle to import CSV file

If your text is: Joe said, "Fred was here with his "Wife"".
This is saved in a CSV as:
"Joe said, ""Fred was here with his ""Wife""""."
(Rule is double quotes go around the whole field, and double quotes are converted to two double quotes). So a simple Optionally Enclosed By clause is needed but not sufficient. CSVs are tough due to this rule. You can sometimes use a Replace clause in the loader for that field but depending on your data this may not be enough. Often pre-processing of a CSV is needed to load in Oracle. Or save it as an XLS and use Oracle SQL Developer app to import to the table - great for one-time work, not so good for scripting.

Set an empty DateTime variable

If you set the date to

DateTime dNewDate = new DateTime();

The value is set to {1/1/0001 12:00:00 AM}

How can I add an empty directory to a Git repository?

I've been facing the issue with empty directories, too. The problem with using placeholder files is that you need to create them, and delete them, if they are not necessary anymore (because later on there were added sub-directories or files. With big source trees managing these placeholder files can be cumbersome and error prone.

This is why I decided to write an open source tool which can manage the creation/deletion of such placeholder files automatically. It is written for .NET platform and runs under Mono (.NET for Linux) and Windows.

Just have a look at: http://code.google.com/p/markemptydirs

DataGridView.Clear()

Simply if your are trying to rebind your Data Grid View just code this:

DataGridView1.DataSource = DataSet.Tables["TableName"];

OR

DataGridView.DataSource = DataTable;

else if you trying to to clear your Data Grid View just code this:

DataGridView.DataSource = null;
DataGridView.Rows.Clear();
DataGridView.Refresh();

and add any method or event to bind Data Grid View Again below this line of code....

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Right click on your website go to property pages and check both the check-boxes under Accessibility validation click on ok. run the website.

How do you select the entire excel sheet with Range using VBA?

you can use all cells as a object like this :

Dim x as Range
Set x = Worksheets("Sheet name").Cells

X is now a range object that contains the entire worksheet

ImportError: No module named win32com.client

Try this command:

pip install pywin32

Note

If it gives the following error:

Could not find a version that satisfies the requirement pywin32>=223 (from pypiwin32) (from versions:)
No matching distribution found for pywin32>=223 (from pypiwin32)

upgrade 'pip', using:

pip install --upgrade pip

Replace single quotes in SQL Server

Try escaping the single quote with a single quote:

Replace(@strip, '''', '')

Identifier not found error on function call

At the time the compiler encounters the call to swapCase in main(), it does not know about the function swapCase, so it reports an error. You can either move the definition of swapCase above main, or declare swap case above main:

void swapCase(char* name);

Also, the 32 in swapCase causes the reader to pause and wonder. The comment helps! In this context, it would add clarity to write

if ('A' <= name[i] && name[i] <= 'Z')
    name[i] += 'a' - 'A';
else if ('a' <= name[i] && name[i] <= 'z')
    name[i] += 'A' - 'a';

The construction in my if-tests is a matter of personal style. Yours were just fine. The main thing is the way to modify name[i] -- using the difference in 'a' vs. 'A' makes it more obvious what is going on, and nobody has to wonder if the '32' is actually correct.

Good luck learning!

"int cannot be dereferenced" in Java

As your methods an int datatype, you should use "==" instead of equals()

try replacing this if (id.equals(list[pos].getItemNumber()))

with

if (id.equals==list[pos].getItemNumber())

it will fix the error .

How do I find the location of my Python site-packages directory?

There are two types of site-packages directories, global and per user.

  1. Global site-packages ("dist-packages") directories are listed in sys.path when you run:

    python -m site
    

    For a more concise list run getsitepackages from the site module in Python code:

    python -c 'import site; print(site.getsitepackages())'
    

    Note: With virtualenvs getsitepackages is not available, sys.path from above will list the virtualenv's site-packages directory correctly, though. In Python 3, you may use the sysconfig module instead:

    python3 -c 'import sysconfig; print(sysconfig.get_paths()["purelib"])'
    
  2. The per user site-packages directory (PEP 370) is where Python installs your local packages:

    python -m site --user-site
    

    If this points to a non-existing directory check the exit status of Python and see python -m site --help for explanations.

    Hint: Running pip list --user or pip freeze --user gives you a list of all installed per user site-packages.


Practical Tips

  • <package>.__path__ lets you identify the location(s) of a specific package: (details)

    $ python -c "import setuptools as _; print(_.__path__)"
    ['/usr/lib/python2.7/dist-packages/setuptools']
    
  • <module>.__file__ lets you identify the location of a specific module: (difference)

    $ python3 -c "import os as _; print(_.__file__)"
    /usr/lib/python3.6/os.py
    
  • Run pip show <package> to show Debian-style package information:

    $ pip show pytest
    Name: pytest
    Version: 3.8.2
    Summary: pytest: simple powerful testing with Python
    Home-page: https://docs.pytest.org/en/latest/
    Author: Holger Krekel, Bruno Oliveira, Ronny Pfannschmidt, Floris Bruynooghe, Brianna Laugher, Florian Bruhin and others
    Author-email: None
    License: MIT license
    Location: /home/peter/.local/lib/python3.4/site-packages
    Requires: more-itertools, atomicwrites, setuptools, attrs, pathlib2, six, py, pluggy
    

React setState not updating state

I had an issue when setting react state multiple times (it always used default state). Following this react/github issue worked for me

const [state, setState] = useState({
  foo: "abc",
  bar: 123
});

// Do this!
setState(prevState => {
  return {
    ...prevState,
    foo: "def"
  };
});
setState(prevState => {
  return {
    ...prevState,
    bar: 456
  };
});

Checkbox value true/false

Use Checked = true

$("#checkbox1").prop('checked', true);

Note: I am not clear whether you want to onclick/onchange event on checkbox. is(":checked", function(){}) is a wrong in the question.

Indent starting from the second line of a paragraph with CSS

This worked for me:

p { margin-left: -2em; 
 text-indent: 2em 
 }

What is the best way to initialize a JavaScript Date to midnight?

In case you already have d3.js as a dependency in your project, or don't mind bringing it in, d3-time (d3.js library is modular as of v4.0.0) has got Intervals.

They might prove useful when setting dates to "default" values, e.g. midnight, 0.00 seconds, the first of the month, etc.

var d = new Date(); // Wed Aug 02 2017 15:01:07 GMT+0200 (CEST)
d3.timeHour(d) // Wed Aug 02 2017 00:00:00 GMT+0200 (CEST)
d3.timeMonth(d) // Tue Aug 01 2017 00:00:00 GMT+0200 (CEST)

Can someone provide an example of a $destroy event for scopes in AngularJS?

Demo: http://jsfiddle.net/sunnycpp/u4vjR/2/

Here I have created handle-destroy directive.

ctrl.directive('handleDestroy', function() {
    return function(scope, tElement, attributes) {        
        scope.$on('$destroy', function() {
            alert("In destroy of:" + scope.todo.text);
        });
    };
});

Not class selector in jQuery

You can use the :not filter selector:

$('foo:not(".someClass")')

Or not() method:

$('foo').not(".someClass")

More Info:

PHP script to loop through all of the files in a directory?

You can use this code to loop through a directory recursively:

$path = "/home/myhome";
$rdi = new RecursiveDirectoryIterator($path, RecursiveDirectoryIterator::KEY_AS_PATHNAME);
foreach (new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::SELF_FIRST) as $file => $info) {
    echo $file."\n";
}

Best way to update data with a RecyclerView adapter

Found following solution working for my similar problem:

private ExtendedHashMap mData = new ExtendedHashMap();
private  String[] mKeys;

public void setNewData(ExtendedHashMap data) {
    mData.putAll(data);
    mKeys = data.keySet().toArray(new String[data.size()]);
    notifyDataSetChanged();
}

Using the clear-command

mData.clear()

is not nessescary

Search a string in a file and delete it from this file by Shell Script

Try the vim-way:

ex -s +"g/foo/d" -cwq file.txt

How to start and stop/pause setInterval?

(function(){
    var i = 0;
    function stop(){
        clearTimeout(i);
    }

    function start(){
        i = setTimeout( timed, 1000 );
    }

    function timed(){
       document.getElementById("input").value++;
       start();
    }

    window.stop = stop;
    window.start = start;
})()

http://jsfiddle.net/TE3Z2/

How do I merge a git tag onto a branch

You mean this?

git checkout destination_branch
git merge tag_name

How do I clone a subdirectory only of a Git repository?

While I hate actually having to use svn when dealing with git repos :/ I use this all the time;

function git-scp() (
  URL="$1" && shift 1
  svn export ${URL/blob\/master/trunk}
)

This allows you to copy out from the github url without modification. Usage;

--- /tmp » git-scp https://github.com/dgraph-io/dgraph/blob/master/contrib/config/kubernetes/helm                                                                                                                  1 ?
A    helm
A    helm/Chart.yaml
A    helm/README.md
A    helm/values.yaml
Exported revision 6367.

--- /tmp » ls | grep helm
Permissions Size User    Date Modified    Name
drwxr-xr-x     - anthony 2020-01-07 15:53 helm/

php exec() is not executing the command

You might also try giving the full path to the binary you're trying to run. That solved my problem when trying to use ImageMagick.

How to convert index of a pandas dataframe into a column?

either:

df['index1'] = df.index

or, .reset_index:

df.reset_index(level=0, inplace=True)

so, if you have a multi-index frame with 3 levels of index, like:

>>> df
                       val
tick       tag obs        
2016-02-26 C   2    0.0139
2016-02-27 A   2    0.5577
2016-02-28 C   6    0.0303

and you want to convert the 1st (tick) and 3rd (obs) levels in the index into columns, you would do:

>>> df.reset_index(level=['tick', 'obs'])
          tick  obs     val
tag                        
C   2016-02-26    2  0.0139
A   2016-02-27    2  0.5577
C   2016-02-28    6  0.0303

Convert NSDate to String in iOS Swift

You can use this extension:

extension Date {

    func toString(withFormat format: String) -> String {
        let formatter = DateFormatter()
        formatter.dateFormat = format
        let myString = formatter.string(from: self)
        let yourDate = formatter.date(from: myString)
        formatter.dateFormat = format

        return formatter.string(from: yourDate!)
    }
}

And use it in your view controller like this (replace <"yyyy"> with your format):

yourString = yourDate.toString(withFormat: "yyyy")

No Multiline Lambda in Python: Why not?

Guido van Rossum (the inventor of Python) answers this exact question himself in an old blog post.
Basically, he admits that it's theoretically possible, but that any proposed solution would be un-Pythonic:

"But the complexity of any proposed solution for this puzzle is immense, to me: it requires the parser (or more precisely, the lexer) to be able to switch back and forth between indent-sensitive and indent-insensitive modes, keeping a stack of previous modes and indentation level. Technically that can all be solved (there's already a stack of indentation levels that could be generalized). But none of that takes away my gut feeling that it is all an elaborate Rube Goldberg contraption."

How do I change the select box arrow

You can skip the container or background image with pure css arrow:

select {

  /* make arrow and background */

  background:
    linear-gradient(45deg, transparent 50%, blue 50%),
    linear-gradient(135deg, blue 50%, transparent 50%),
    linear-gradient(to right, skyblue, skyblue);
  background-position:
    calc(100% - 21px) calc(1em + 2px),
    calc(100% - 16px) calc(1em + 2px),
    100% 0;
  background-size:
    5px 5px,
    5px 5px,
    2.5em 2.5em;
  background-repeat: no-repeat;

  /* styling and reset */

  border: thin solid blue;
  font: 300 1em/100% "Helvetica Neue", Arial, sans-serif;
  line-height: 1.5em;
  padding: 0.5em 3.5em 0.5em 1em;

  /* reset */

  border-radius: 0;
  margin: 0;      
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  -webkit-appearance:none;
  -moz-appearance:none;
}

Sample here

The way to check a HDFS directory's size?

With this you will get size in GB

hdfs dfs -du PATHTODIRECTORY | awk '/^[0-9]+/ { print int($1/(1024**3)) " [GB]\t" $2 }'

How and when to use ‘async’ and ‘await’

Showing the above explanations in action in a simple console program:

class Program
{
    static void Main(string[] args)
    {
        TestAsyncAwaitMethods();
        Console.WriteLine("Press any key to exit...");
        Console.ReadLine();
    }

    public async static void TestAsyncAwaitMethods()
    {
        await LongRunningMethod();
    }

    public static async Task<int> LongRunningMethod()
    {
        Console.WriteLine("Starting Long Running method...");
        await Task.Delay(5000);
        Console.WriteLine("End Long Running method...");
        return 1;
    }
}

And the output is:

Starting Long Running method...
Press any key to exit...
End Long Running method...

Thus,

  1. Main starts the long running method via TestAsyncAwaitMethods. That immediately returns without halting the current thread and we immediately see 'Press any key to exit' message
  2. All this while, the LongRunningMethod is running in the background. Once its completed, another thread from Threadpool picks up this context and displays the final message

Thus, not thread is blocked.

Logger slf4j advantages of formatting with {} instead of string concatenation

It is about string concatenation performance. It's potentially significant if your have dense logging statements.

(Prior to SLF4J 1.7) But only two parameters are possible

Because the vast majority of logging statements have 2 or fewer parameters, so SLF4J API up to version 1.6 covers (only) the majority of use cases. The API designers have provided overloaded methods with varargs parameters since API version 1.7.

For those cases where you need more than 2 and you're stuck with pre-1.7 SLF4J, then just use either string concatenation or new Object[] { param1, param2, param3, ... }. There should be few enough of them that the performance is not as important.

How to cherry pick a range of commits and merge into another branch?

I wrapped VonC's code into a short bash script, git-multi-cherry-pick, for easy running:

#!/bin/bash

if [ -z $1 ]; then
    echo "Equivalent to running git-cherry-pick on each of the commits in the range specified.";
    echo "";
    echo "Usage:  $0 start^..end";
    echo "";
    exit 1;
fi

git rev-list --reverse --topo-order $1 | while read rev 
do 
  git cherry-pick $rev || break 
done 

I'm currently using this as I rebuild the history of a project that had both 3rd-party code and customizations mixed together in the same svn trunk. I'm now splitting apart core 3rd party code, 3rd party modules, and customizations onto their own git branches for better understanding of customizations going forward. git-cherry-pick is helpful in this situation since I have two trees in the same repository, but without a shared ancestor.

How to do a batch insert in MySQL

Most of the time, you are not working in a MySQL client and you should batch inserts together using the appropriate API.

E.g. in JDBC:

connection con.setAutoCommit(false); 
PreparedStatement prepStmt = con.prepareStatement("UPDATE DEPT SET MGRNO=? WHERE DEPTNO=?");
prepStmt.setString(1,mgrnum1);                 
prepStmt.setString(2,deptnum1);
prepStmt.addBatch();

prepStmt.setString(1,mgrnum2);                        
prepStmt.setString(2,deptnum2);
prepStmt.addBatch();

int [] numUpdates=prepStmt.executeBatch();

http://publib.boulder.ibm.com/infocenter/db2luw/v8/index.jsp?topic=/com.ibm.db2.udb.doc/ad/tjvbtupd.htm

Get model's fields in Django

_meta is private, but it's relatively stable. There are efforts to formalise it, document it and remove the underscore, which might happen before 1.3 or 1.4. I imagine effort will be made to ensure things are backwards compatible, because lots of people have been using it anyway.

If you're particularly concerned about compatibility, write a function that takes a model and returns the fields. This means if something does change in the future, you only have to change one function.

def get_model_fields(model):
    return model._meta.fields

I believe this will return a list of Field objects. To get the value of each field from the instance, use getattr(instance, field.name).

Update: Django contributors are working on an API to replace the _Meta object as part of a Google Summer of Code. See:
- https://groups.google.com/forum/#!topic/django-developers/hD4roZq0wyk
- https://code.djangoproject.com/wiki/new_meta_api

Not connecting to SQL Server over VPN

This is what fixed my connection problem of accessing the SQL Server 2012 Database via VPN

With the SQL Server 2012 Configuration Manager,

I went to the SQL Server Network configuration

Then clicked on the NEW server instance and double-clicked the TCP/IP protocol [I had also previously enabled this option and rebooted the server but that did still not fix it]

now that the TCP/IP was enabled, I noted that all of the IP port slots in the 'IP Addresses' tab of the TCP/IP Properties advanced dialog were set to Enabled=No.

I was curious to why my new installation set all of these IP slots to NO rather than Yes, so I just changed them to YES.

Now the connection to the sever via VPN works great, I did not change any port numbers.

Note: I also had SQL Server 2008 default from the Visual studio 2010 uninstalled, but I do not think that had a direct effect to the TCP/IP situation. A coworker told me that the 2008 and 2005 installations which come with visual studio may interfere with SQL 2012.

Background Image for Select (dropdown) does not work in Chrome

select 
{
    -webkit-appearance: none;
}

If you need to you can also add an image that contains the arrow as part of the background.

Page Redirect after X seconds wait using JavaScript

It looks you are almost there. Try:

if(error == true){

    // Your application has indicated there's an error
    window.setTimeout(function(){

        // Move to a new location or you can do something else
        window.location.href = "https://www.google.co.in";

    }, 5000);

}

Node.js request CERT_HAS_EXPIRED

I had this problem on production with Heroku and locally while debugging on my macbook pro this morning.

After an hour of debugging, this resolved on its own both locally and on production. I'm not sure what fixed it, so that's a bit annoying. It happened right when I thought I did something, but reverting my supposed fix didn't bring the problem back :(

Interestingly enough, it appears my database service, MongoDb has been having server problems since this morning, so there's a good chance this was related to it.

enter image description here

Arduino Sketch upload issue - avrdude: stk500_recv(): programmer is not responding

Did you install/update the driver for the FTDI cable? (Step three on http://arduino.cc/en/Guide/Howto). Running the Arduino IDE from my Raspberry Pi worked fine without explicitly installing the drivers (either they were pre-installed or the Arduino IDE installer took care of it). On my Mac this was not the case and I had to install the cable drivers in addition to the IDE.

What does the colon (:) operator do?

It's used in for loops to iterate over a list of objects.

for (Object o: list)
{
    // o is an element of list here
}

Think of it as a for <item> in <list> in Python.

IN vs OR in the SQL WHERE Clause

The best way to find out is looking at the Execution Plan.


I tried it with Oracle, and it was exactly the same.

CREATE TABLE performance_test AS ( SELECT * FROM dba_objects );

SELECT * FROM performance_test
WHERE object_name IN ('DBMS_STANDARD', 'DBMS_REGISTRY', 'DBMS_LOB' );

Even though the query uses IN, the Execution Plan says that it uses OR:

--------------------------------------------------------------------------------------    
| Id  | Operation         | Name             | Rows  | Bytes | Cost (%CPU)| Time     |    
--------------------------------------------------------------------------------------    
|   0 | SELECT STATEMENT  |                  |     8 |  1416 |   163   (2)| 00:00:02 |    
|*  1 |  TABLE ACCESS FULL| PERFORMANCE_TEST |     8 |  1416 |   163   (2)| 00:00:02 |    
--------------------------------------------------------------------------------------    

Predicate Information (identified by operation id):                                       
---------------------------------------------------                                       

   1 - filter("OBJECT_NAME"='DBMS_LOB' OR "OBJECT_NAME"='DBMS_REGISTRY' OR                
              "OBJECT_NAME"='DBMS_STANDARD')                                              

WCF service startup error "This collection already contains an address with scheme http"

In .Net 4, you can use the multipleSiteBindingsEnabled option:

<system.serviceModel>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true">
    </serviceHostingEnvironment>
</system.serviceModel>

Then, you won't have to specify each address.

http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehostingenvironment.multiplesitebindingsenabled.aspx

What does "javax.naming.NoInitialContextException" mean?

It means that there is no initial context :)

But seriously folks, JNDI (javax.naming) is all about looking up objects or resources from some directory or provider. To look something up, you need somewhere to look (this is the InitialContext). NoInitialContextException means "I want to find the telephone number for John Smith, but I have no phonebook to look in".

An InitialContext can be created in any number of ways. It can be done manually, for instance creating a connection to an LDAP server. It can also be set up by an application server inside which you run your application. In this case, the container (application server) already provides you with a "phonebook", through which you can look up anything the application server makes available. This is often configurable and a common way of moving this type of configuration from the application implementation to the container, where it can be shared across all applications in the server.

UPDATE: from the code snippet you post it looks like you are trying to run code stand-alone that is meant to be run in an application server. In this case, the code attempting to get a connection to a database from the "phonebook". This is one of the resources that is often configured in the application server container. So, rather than having to manage configuration and connections to the database in your code, you can configure it in your application server and simple ask for a connection (using JNDI) in your code.

Best way to log POST data in Apache?

Though It's late to answer. This module can do: https://github.com/danghvu/mod_dumpost

What's your favorite "programmer" cartoon?

Tragically, my favorite cartoon is too old to be on the interwebs.

It's from Datamation. (Remember Datamation?) A man is sitting at a desk. There are bits of electronics everywhere. Rubble is strewn into every corner of the room. His face and hair are singed.

He is thinking "It's never done that before."

Importing xsd into wsdl

import vs. include

The primary purpose of an import is to import a namespace. A more common use of the XSD import statement is to import a namespace which appears in another file. You might be gathering the namespace information from the file, but don't forget that it's the namespace that you're importing, not the file (don't confuse an import statement with an include statement).

Another area of confusion is how to specify the location or path of the included .xsd file: An XSD import statement has an optional attribute named schemaLocation but it is not necessary if the namespace of the import statement is at the same location (in the same file) as the import statement itself.

When you do chose to use an external .xsd file for your WSDL, the schemaLocation attribute becomes necessary. Be very sure that the namespace you use in the import statement is the same as the targetNamespace of the schema you are importing. That is, all 3 occurrences must be identical:

WSDL:

xs:import namespace="urn:listing3" schemaLocation="listing3.xsd"/>

XSD:

<xsd:schema targetNamespace="urn:listing3"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 

Another approach to letting know the WSDL about the XSD is through Maven's pom.xml:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>xmlbeans-maven-plugin</artifactId>
  <executions>
    <execution>
      <id>generate-sources-xmlbeans</id>
      <phase>generate-sources</phase>
      <goals>
    <goal>xmlbeans</goal>
      </goals>
    </execution>
  </executions>
  <version>2.3.3</version>
  <inherited>true</inherited>
  <configuration>
    <schemaDirectory>${basedir}/src/main/xsd</schemaDirectory>
  </configuration>
</plugin>

You can read more on this in this great IBM article. It has typos such as xsd:import instead of xs:import but otherwise it's fine.

How to change a Git remote on Heroku

here is a better answer found through Git docs.

This shows what the heroku remote is:

$ git remote get-url heroku

Found it here: https://git-scm.com/docs/git-remote Also in that document is a set-url, if you need to change it.

HowTo Generate List of SQL Server Jobs and their owners

A colleague told me about this stored procedure...

USE msdb

EXEC dbo.sp_help_job

How to generate and validate a software license key?

Simple answer - No matter what scheme you use it can be cracked.

Don't punish honest customers with a system meant to prevent hackers, as hackers will crack it regardless.

A simple hashed code tied to their email or similar is probably good enough. Hardware based IDs always become an issue when people need to reinstall or update hardware.

Good thread on the issue: http://discuss.joelonsoftware.com/default.asp?biz.5.82298.34

Check if an object belongs to a class in Java

If you ever need to do this dynamically, you can use the following:

boolean isInstance(Object object, Class<?> type) {
    return type.isInstance(object);
}

You can get an instance of java.lang.Class by calling the instance method Object::getClass on any object (returns the Class which that object is an instance of), or you can do class literals (for example, String.class, List.class, int[].class). There are other ways as well, through the reflection API (which Class itself is the entry point for).

AngularJS ui router passing data between states without URL

We can use params, new feature of the UI-Router:

API Reference / ui.router.state / $stateProvider

params A map which optionally configures parameters declared in the url, or defines additional non-url parameters. For each parameter being configured, add a configuration object keyed to the name of the parameter.

See the part: "...or defines additional non-url parameters..."

So the state def would be:

$stateProvider
  .state('home', {
    url: "/home",
    templateUrl: 'tpl.html',
    params: { hiddenOne: null, }
  })

Few examples form the doc mentioned above:

// define a parameter's default value
params: {
  param1: { value: "defaultValue" }
}
// shorthand default values
params: {
  param1: "defaultValue",
  param2: "param2Default"
}

// param will be array []
params: {
  param1: { array: true }
}

// handling the default value in url:
params: {
  param1: {
    value: "defaultId",
    squash: true
} }
// squash "defaultValue" to "~"
params: {
  param1: {
    value: "defaultValue",
    squash: "~"
  } }

EXTEND - working example: http://plnkr.co/edit/inFhDmP42AQyeUBmyIVl?p=info

Here is an example of a state definition:

 $stateProvider
  .state('home', {
      url: "/home",
      params : { veryLongParamHome: null, },
      ...
  })
  .state('parent', {
      url: "/parent",
      params : { veryLongParamParent: null, },
      ...
  })
  .state('parent.child', { 
      url: "/child",
      params : { veryLongParamChild: null, },
      ...
  })

This could be a call using ui-sref:

<a ui-sref="home({veryLongParamHome:'Home--f8d218ae-d998-4aa4-94ee-f27144a21238'
  })">home</a>

<a ui-sref="parent({ 
    veryLongParamParent:'Parent--2852f22c-dc85-41af-9064-d365bc4fc822'
  })">parent</a>

<a ui-sref="parent.child({
    veryLongParamParent:'Parent--0b2a585f-fcef-4462-b656-544e4575fca5',  
    veryLongParamChild:'Child--f8d218ae-d998-4aa4-94ee-f27144a61238'
  })">parent.child</a>

Check the example here

HTML5 video - show/hide controls programmatically

Here's how to do it:

var myVideo = document.getElementById("my-video")    
myVideo.controls = false;

Working example: https://jsfiddle.net/otnfccgu/2/

See all available properties, methods and events here: https://www.w3schools.com/TAGs/ref_av_dom.asp

How to run server written in js with Node.js

Just go on that directory of your JS file from cmd and write node jsFile.js or even node jsFile; both will work fine.

Group list by values

len = max(key for (item, key) in list)
newlist = [[] for i in range(len+1)]
for item,key in list:
  newlist[key].append(item)

You can do it in a single list comprehension, perhaps more elegant but O(n**2):

[[item for (item,key) in list if key==i] for i in range(max(key for (item,key) in list)+1)]

How do I fix certificate errors when running wget on an HTTPS URL in Cygwin?

If the problem is that a known root CA is missing and when you are using ubuntu or debian, then you can solve the problem with this one line:

sudo apt-get install ca-certificates

Java and unlimited decimal places?

I believe that you are looking for the java.lang.BigDecimal class.

Python add item to the tuple

#1 form

a = ('x', 'y')
b = a + ('z',)
print(b)

#2 form

a = ('x', 'y')
b = a + tuple('b')
print(b)

jQuery dialog popup

You can check this link: http://jqueryui.com/dialog/

This code should work fine

$("#dialog").dialog();

Generate SHA hash in C++ using OpenSSL library

correct syntax at command line should be

echo -n "compute sha1" | openssl sha1

otherwise you'll hash the trailing newline character as well.

How to upsert (update or insert) in SQL Server 2005

Try to check for existence:

IF NOT EXISTS (SELECT * FROM dbo.Employee WHERE ID = @SomeID)

    INSERT INTO dbo.Employee(Col1, ..., ColN)
    VALUES(Val1, .., ValN)

ELSE

    UPDATE dbo.Employee
    SET Col1 = Val1, Col2 = Val2, ...., ColN = ValN
    WHERE ID = @SomeID

You could easily wrap this into a stored procedure and just call that stored procedure from the outside (e.g. from a programming language like C# or whatever you're using).

Update: either you can just write this entire statement in one long string (doable - but not really very useful) - or you can wrap it into a stored procedure:

CREATE PROCEDURE dbo.InsertOrUpdateEmployee
       @ID INT,
       @Name VARCHAR(50),
       @ItemName VARCHAR(50),  
       @ItemCatName VARCHAR(50),
       @ItemQty DECIMAL(15,2)
AS BEGIN
    IF NOT EXISTS (SELECT * FROM dbo.Table1 WHERE ID = @ID)
       INSERT INTO dbo.Table1(ID, Name, ItemName, ItemCatName, ItemQty)
       VALUES(@ID, @Name, @ItemName, @ItemCatName, @ItemQty)
    ELSE
       UPDATE dbo.Table1
       SET Name = @Name,
           ItemName = @ItemName,
           ItemCatName = @ItemCatName,
           ItemQty = @ItemQty
       WHERE ID = @ID
END

and then just call that stored procedure from your ADO.NET code

<img>: Unsafe value used in a resource URL context

Angular treats all values as untrusted by default. When a value is inserted into the DOM from a template, via property, attribute, style, class binding, or interpolation, Angular sanitizes and escapes untrusted values.

So if you are manipulating DOM directly and inserting content it, you need to sanitize it otherwise Angular will through errors.

I have created the pipe SanitizeUrlPipe for this

import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Pipe({
    name: "sanitizeUrl"
})
export class SanitizeUrlPipe implements PipeTransform {

    constructor(private _sanitizer: DomSanitizer) { }

    transform(v: string): SafeHtml {
        return this._sanitizer.bypassSecurityTrustResourceUrl(v);
    }
}

and this is how you can use

<iframe [src]="url | sanitizeUrl" width="100%" height="500px"></iframe>

If you want to add HTML, then SanitizeHtmlPipe can help

import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Pipe({
    name: "sanitizeHtml"
})
export class SanitizeHtmlPipe implements PipeTransform {

    constructor(private _sanitizer: DomSanitizer) { }

    transform(v: string): SafeHtml {
        return this._sanitizer.bypassSecurityTrustHtml(v);
    }
}

Read more about angular security here.

How to align a div inside td element using CSS class

div { margin: auto; }

This will center your div.

Div by itself is a blockelement. Therefor you need to define the style to the div how to behave.

Can I call a constructor from another constructor (do constructor chaining) in C++?

When calling a constructor it actually allocates memory, either from the stack or from the heap. So calling a constructor in another constructor creates a local copy. So we are modifying another object, not the one we are focusing on.

What is the function of FormulaR1C1?

I find the most valuable feature of .FormulaR1C1 is sheer speed. Versus eg a couple of very large loops filling some data into a sheet, If you can convert what you are doing into a .FormulaR1C1 form. Then a single operation eg myrange.FormulaR1C1 = "my particular formuala" is blindingly fast (can be a thousand times faster). No looping and counting - just fill the range at high speed.

How to pass arguments from command line to gradle

Building on Peter N's answer, this is an example of how to add (optional) user-specified arguments to pass to Java main for a JavaExec task (since you can't set the 'args' property manually for the reason he cites.)

Add this to the task:

task(runProgram, type: JavaExec) {

  [...]

  if (project.hasProperty('myargs')) {
      args(myargs.split(','))
  }

... and run at the command line like this

% ./gradlew runProgram '-Pmyargs=-x,7,--no-kidding,/Users/rogers/tests/file.txt'

How to force a component's re-rendering in Angular 2?

I force reload my component using *ngIf.

All the components inside my container goes back to the full lifecycle hooks .

In the template :

<ng-container *ngIf="_reload">
    components here 
</ng-container>

Then in the ts file :

public _reload = true;

private reload() {
    setTimeout(() => this._reload = false);
    setTimeout(() => this._reload = true);
}

How do I properly escape quotes inside HTML attributes?

Per HTML syntax, and even HTML5, the following are all valid options:

<option value="&quot;asd">test</option>
<option value="&#34;asd">test</option>
<option value='"asd'>test</option>
<option value='&quot;asd'>test</option>
<option value='&#34;asd'>test</option>
<option value=&quot;asd>test</option>
<option value=&#34;asd>test</option>

Note that if you are using XML syntax the quotes (single or double) are required.

Here's a jsfiddle showing all of the above working.

How do I determine if a checkbox is checked?

try learning jQuery it's a great place to start with javascript and it really simplifies your code and help separate your js from your html. include the js file from google's CDN (https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js)

then in your script tag (still in the <head>) use:

$(function() {//code inside this function will run when the document is ready
    alert($('#lifecheck').is(':checked'));

    $('#lifecheck').change(function() {//do something when the user clicks the box
        alert(this.checked);
    });
});

How to check whether a string contains a substring in JavaScript?

ECMAScript 6 introduced String.prototype.includes:

_x000D_
_x000D_
const string = "foo";_x000D_
const substring = "oo";_x000D_
_x000D_
console.log(string.includes(substring));
_x000D_
_x000D_
_x000D_

includes doesn’t have Internet Explorer support, though. In ECMAScript 5 or older environments, use String.prototype.indexOf, which returns -1 when a substring cannot be found:

_x000D_
_x000D_
var string = "foo";_x000D_
var substring = "oo";_x000D_
_x000D_
console.log(string.indexOf(substring) !== -1);
_x000D_
_x000D_
_x000D_

Reading a json file in Android

Put that file in assets.

For project created in Android Studio project you need to create assets folder under the main folder.

Read that file as:

public String loadJSONFromAsset(Context context) {
        String json = null;
        try {
            InputStream is = context.getAssets().open("file_name.json");

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

            json = new String(buffer, "UTF-8");


        } catch (IOException ex) {
            ex.printStackTrace();
            return null;
        }
        return json;

    }

and then you can simply read this string return by this function as

JSONObject obj = new JSONObject(json_return_by_the_function);

For further details regarding JSON see http://www.vogella.com/articles/AndroidJSON/article.html

Hope you will get what you want.

inserting characters at the start and end of a string

You can also use join:

yourstring = ''.join(('L','yourstring','LL'))

Result:

>>> yourstring
'LyourstringLL'

Easy way to export multiple data.frame to multiple Excel worksheets

You can also use the openxlsx library to export multiple datasets to multiple sheets in a single workbook.The advantage of openxlsx over xlsx is that openxlsx removes the dependencies on java libraries.

Write a list of data.frames to individual worksheets using list names as worksheet names.

require(openxlsx)
list_of_datasets <- list("Name of DataSheet1" = dataframe1, "Name of Datasheet2" = dataframe2)
write.xlsx(list_of_datasets, file = "writeXLSX2.xlsx")

URL encoding in Android

try {
                    query = URLEncoder.encode(query, "utf-8");
                } catch (UnsupportedEncodingException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

Git "error: The branch 'x' is not fully merged"

If you made a merge on Github and are seeing the error below. You need to pull (fetch and commit) the changes from the remote server before it will recognize the merge on your local. After doing this, Git will allow you to delete the branch without giving you the error.

error: The branch 'x' is not fully merged. If you are sure you want to delete it, run 'git branch -D 'x'.

How do I convert a Swift Array to a String?

If the array contains strings, you can use the String's join method:

var array = ["1", "2", "3"]

let stringRepresentation = "-".join(array) // "1-2-3"

In Swift 2:

var array = ["1", "2", "3"]

let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"

This can be useful if you want to use a specific separator (hypen, blank, comma, etc).

Otherwise you can simply use the description property, which returns a string representation of the array:

let stringRepresentation = [1, 2, 3].description // "[1, 2, 3]"

Hint: any object implementing the Printable protocol has a description property. If you adopt that protocol in your own classes/structs, you make them print friendly as well

In Swift 3

  • join becomes joined, example [nil, "1", "2"].flatMap({$0}).joined()
  • joinWithSeparator becomes joined(separator:) (only available to Array of Strings)

In Swift 4

var array = ["1", "2", "3"]
array.joined(separator:"-")

Command-line Unix ASCII-based charting / plotting tool

While gnuplot is powerful, it's also really irritating when you just want to pipe in a bunch of points and get a graph.

Thankfully, someone created eplot (easy plot), which handles all the nonsense for you.

It doesn't seem to have an option to force terminal graphs; I patched it like so:

--- eplot.orig  2012-10-12 17:07:35.000000000 -0700
+++ eplot       2012-10-12 17:09:06.000000000 -0700
@@ -377,6 +377,7 @@
                # ---- print the options
                com="echo '\n"+getStyleString+@oc["MiscOptions"]
                com=com+"set multiplot;\n" if doMultiPlot
+               com=com+"set terminal dumb;\n"
                com=com+"plot "+@oc["Range"]+comString+"\n'| gnuplot -persist"
                printAndRun(com)
                # ---- convert to PDF

An example of use:

[$]> git shortlog -s -n | awk '{print $1}' | eplot 2> /dev/null


  3500 ++-------+-------+--------+--------+-------+--------+-------+-------++
       +        +       +        "/tmp/eplot20121012-19078-fw3txm-0" ****** +       *                                                                    |  3000 +*                                                                  ++       |*                                                                   |       | *                                                                  |  2500 ++*                                                                 ++       | *                                                                  |
       |  *                                                                 |
  2000 ++ *                                                                ++
       |  **                                                                |
  1500 ++   ****                                                           ++
       |        *                                                           |
       |         **                                                         |
  1000 ++          *                                                       ++
       |            *                                                       |
       |            *                                                       |
   500 ++            ***                                                   ++
       |                **************                                      |
       +        +       +        +    **********  +        +       +        +
     0 ++-------+-------+--------+--------+-----***************************++
       0        5       10       15       20      25       30      35       40

Difference between npx and npm?

Introducing npx: an npm package runner

NPM - Manages packages but doesn't make life easy executing any.
NPX - A tool for executing Node packages.

NPX comes bundled with NPM version 5.2+

NPM by itself does not simply run any package. it doesn't run any package in a matter of fact. If you want to run a package using NPM, you must specify that package in your package.json file.

When executables are installed via NPM packages, NPM links to them:

  1. local installs have "links" created at ./node_modules/.bin/ directory.
  2. global installs have "links" created from the global bin/ directory (e.g. /usr/local/bin) on Linux or at %AppData%/npm on Windows.

Documentation you should read


NPM:

One might install a package locally on a certain project:

npm install some-package

Now let's say you want NodeJS to execute that package from the command line:

$ some-package

The above will fail. Only globally installed packages can be executed by typing their name only.

To fix this, and have it run, you must type the local path:

$ ./node_modules/.bin/some-package

You can technically run a locally installed package by editing your packages.json file and adding that package in the scripts section:

{
  "name": "whatever",
  "version": "1.0.0",
  "scripts": {
    "some-package": "some-package"
  }
}

Then run the script using npm run-script (or npm run):

npm run some-package

NPX:

npx will check whether <command> exists in $PATH, or in the local project binaries, and execute it. So, for the above example, if you wish to execute the locally-installed package some-package all you need to do is type:

npx some-package

Another major advantage of npx is the ability to execute a package which wasn't previously installed:

$ npx create-react-app my-app

The above example will generate a react app boilerplate within the path the command had run in, and ensures that you always use the latest version of a generator or build tool without having to upgrade each time you’re about to use it.


Use-Case Example:

npx command may be helpful in the script section of a package.json file, when it is unwanted to define a dependency which might not be commonly used or any other reason:

"scripts": {
    "start": "npx [email protected]",
    "serve": "npx http-server"
}

Call with: npm run serve


Related questions:

  1. How to use package installed locally in node_modules?
  2. NPM: how to source ./node_modules/.bin folder?
  3. How do you run a js file using npm scripts?

Is there a way to do repetitive tasks at intervals?

A broader answer to this question might consider the Lego brick approach often used in Occam, and offered to the Java community via JCSP. There is a very good presentation by Peter Welch on this idea.

This plug-and-play approach translates directly to Go, because Go uses the same Communicating Sequential Process fundamentals as does Occam.

So, when it comes to designing repetitive tasks, you can build your system as a dataflow network of simple components (as goroutines) that exchange events (i.e. messages or signals) via channels.

This approach is compositional: each group of small components can itself behave as a larger component, ad infinitum. This can be very powerful because complex concurrent systems are made from easy to understand bricks.

Footnote: in Welch's presentation, he uses the Occam syntax for channels, which is ! and ? and these directly correspond to ch<- and <-ch in Go.

How to set a binding in Code?

You need to change source to viewmodel object:

myBinding.Source = viewModelObject;

PHP Fatal error: Cannot redeclare class

Another possible culprit is source control and unresolved conflicts. SVN may cause the same class to appear twice in the conflicted code file; two alternative versions of it ("mine" and "theirs").

How to terminate a process in vbscript

Just type in the following command: taskkill /f /im (program name) To find out the im of your program open task manager and look at the process while your program is running. After the program has run a process will disappear from the task manager; that is your program.

Style disabled button with CSS

For all of us using bootstrap, you can change the style by adding the "disabled" class and using the following:

HTML

<button type="button"class="btn disabled">Text</button>

CSS

.btn:disabled,
.btn.disabled{
  color:#fff;
  border-color: #a0a0a0;
  background-color: #a0a0a0;
}
.btn:disabled:hover,
.btn:disabled:focus,
.btn.disabled:hover,
.btn.disabled:focus {
  color:#fff;
  border-color: #a0a0a0;
  background-color: #a0a0a0;
}

Remember that adding the "disabled" class doesn't necessarily disable the button, for example in a submit form. To disable its behaviour use the disabled property:

<button type="button"class="btn disabled" disabled="disabled">Text</button>

A working fiddle with some examples is available here.

ImportError: No module named dateutil.parser

i have same issues on my MacOS and it's work for me to try

pip3 install python-dateutil

on Ubuntu

sudo apt-get install python-dateutil

Check here

grep's at sign caught as whitespace

After some time with Google I asked on the ask ubuntu chat room.

A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:

grep -P "(^|\s)abc(\s|$)" gives the result I was looking for. -P is an experimental implementation of perl regexps.

grepping for abc and then using filters like grep -v '@abc' (this is far from perfect...) should also work, but my patch does something similar.

How do I restart nginx only after the configuration test was successful on Ubuntu?

I use the following command to reload Nginx (version 1.5.9) only if a configuration test was successful:

/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload

If you need to do this often, you may want to use an alias. I use the following:

alias n='/etc/init.d/nginx configtest && sudo /etc/init.d/nginx reload'

The trick here is done by the "&&" which only executes the second command if the first was successful. You can see here a more detailed explanation of the use of the "&&" operator.

You can use "restart" instead of "reload" if you really want to restart the server.

Improving bulk insert performance in Entity framework

There is no way to force EF to improve performance when doing it this way. The problem is that EF executes each insert in separate round trip to the database. Awesome isn't it? Even DataSets supported batch processing. Check this article for some workaround. Another workaround can be using custom stored procedure accepting table valued parameter but you need raw ADO.NET for that.

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

Negation in Python

Python prefers English keywords to punctuation. Use not x, i.e. not os.path.exists(...). The same thing goes for && and || which are and and or in Python.

WPF popup window

XAML

<Popup Name="myPopup">
      <TextBlock Name="myPopupText" 
                 Background="LightBlue" 
                 Foreground="Blue">
        Popup Text
      </TextBlock>
</Popup>

c#

    Popup codePopup = new Popup();
    TextBlock popupText = new TextBlock();
    popupText.Text = "Popup Text";
    popupText.Background = Brushes.LightBlue;
    popupText.Foreground = Brushes.Blue;
    codePopup.Child = popupText;

you can find more details about the Popup Control from MSDN documentation.

MSDN documentation on Popup control

bash shell nested for loop

#!/bin/bash
# loop*figures.bash

for i in 1 2 3 4 5  # First loop.
do
    for j in $(seq 1 $i)
    do
        echo  -n "*" 
    done
    echo 
done
echo
# outputs
# *
# **
# ***
# ****
# *****

for i in 5 4 3 2 1 # First loop.
do
    for j in $(seq -$i -1)
    do
        echo  -n "*" 
    done
    echo 
done

# outputs
# *****
# ****
# ***
# **
# *

for i in 1 2 3 4 5  # First loop.
do
    for k in $(seq -5 -$i)
    do
        echo -n ' '
    done
    for j in $(seq 1 $i)
    do
        echo  -n "* " 
    done
    echo 
done
echo

# outputs
#     * 
#    * * 
#   * * * 
#  * * * * 
# * * * * * 

for i in 1 2 3 4 5  # First loop.
do
    for j in $(seq -5 -$i)
    do
        echo  -n "* " 
    done
    echo 
    for k in $(seq 1 $i)
    do
        echo -n ' '
    done
done
echo

# outputs
# * * * * * 
#  * * * * 
#   * * * 
#    * * 
#     *


exit 0

Asp.net Validation of viewstate MAC failed

my problem was this piece of javascript code

$('input').each(function(ele, indx){
    this.value = this.value.toUpperCase();
});

Turns it was messing with viewstate hidden field so I changed it to below code and it worked

$('input:visible').each(function(ele, indx){
    this.value = this.value.toUpperCase();
});

Find out which remote branch a local branch is tracking

You can use git checkout, i.e. "check out the current branch". This is a no-op with a side-effects to show the tracking information, if exists, for the current branch.

$ git checkout 
Your branch is up-to-date with 'origin/master'.

Why does "return list.sort()" return None, not the list?

To understand why it does not return the list:

sort() doesn't return any value while the sort() method just sorts the elements of a given list in a specific order - ascending or descending without returning any value.

So problem is with answer = newList.sort() where answer is none.

Instead you can just do return newList.sort().

The syntax of the sort() method is:

list.sort(key=..., reverse=...)

Alternatively, you can also use Python's in-built function sorted() for the same purpose.

sorted(list, key=..., reverse=...)

Note: The simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list.

So in your case answer = sorted(newList).

How to vertically align elements in a div?

We may use a CSS function calculation to calculate the size of the element and then position the child element accordingly.

Example HTML:

<div class="box">
    <span><a href="#">Some Text</a></span>
</div>

And CSS:

.box {
    display: block;
    background: #60D3E8;
    position: relative;
    width: 300px;
    height: 200px;
    text-align: center;

}
.box span {
    font: bold 20px/20px 'source code pro', sans-serif;
    position: absolute;
    left: 0;
    right: 0;
    top: calc(50% - 10px);
}
a {
    color: white;
    text-decoration: none;
}

Demo created here: https://jsfiddle.net/xnjq1t22/

This solution works well with responsive div height and width as well.

Note: The calc function is not tested for compatiblity with old browsers.

Better way to sum a property value in an array

I know that this question has an accepted answer but I thought I'd chip in with an alternative which uses array.reduce, seeing that summing an array is the canonical example for reduce:

$scope.sum = function(items, prop){
    return items.reduce( function(a, b){
        return a + b[prop];
    }, 0);
};

$scope.travelerTotal = $scope.sum($scope.traveler, 'Amount');

Fiddle

What is the difference between a data flow diagram and a flow chart?

Data Flow and Flow Chart differ in processes, flow, and timing.

  1. Processes

    a.) On DFDs, processes can operate in parallel (at-the-same-time).

    b.) On flowcharts, processes execute one at a time.


  1. Flow

    a.) DFDs show the flow of data through a system

    b.) Flowcharts show the flow of control (sequence and transfer of control)


  1. Timing

    a.) Processes on a DFD can have dramatically different timing (daily, weekly, on demand)

    b.) Processes on flowcharts are part of a single program with consistent timing

Read/Parse text file line by line in VBA

The below is my code from reading text file to excel file.

Sub openteatfile()
Dim i As Long, j As Long
Dim filepath As String
filepath = "C:\Users\TarunReddyNuthula\Desktop\sample.ctxt"
ThisWorkbook.Worksheets("Sheet4").Range("Al:L20").ClearContents
Open filepath For Input As #1
i = l
Do Until EOF(1)
Line Input #1, linefromfile
lineitems = Split(linefromfile, "|")
        For j = LBound(lineitems) To UBound(lineitems)
            ThisWorkbook.Worksheets("Sheet4").Cells(i, j + 1).value = lineitems(j)
        Next j
    i = i + 1 
Loop
Close #1
End Sub

Copy all the lines to clipboard

Click the left mouse button, drag across the section you want to copy and release. The code automatically gets copied to clipboard.

How to generate JAXB classes from XSD?

1) You can use standard java utility xjc - ([your java home dir]\bin\xjc.exe). But you need to create .bat (or .sh) script for using it.

e.g. generate.bat:

[your java home dir]\bin\xjc.exe %1 %2 %3

e.g. test-scheme.xsd:

<?xml version="1.0"?>
<xs:schema version="1.0"
           xmlns:xs="http://www.w3.org/2001/XMLSchema"
           elementFormDefault="qualified" 
           targetNamespace="http://myprojects.net/xsd/TestScheme"
           xmlns="http://myprojects.net/xsd/TestScheme">
    <xs:element name="employee" type="PersonInfoType"/>

    <xs:complexType name="PersonInfoType">
        <xs:sequence>
            <xs:element name="firstname" type="xs:string"/>
            <xs:element name="lastname" type="xs:string"/>
        </xs:sequence>
    </xs:complexType>
</xs:schema>

Run .bat file with parameters: generate.bat test-scheme.xsd -d [your src dir]

For more info use this documentation - http://docs.oracle.com/javaee/5/tutorial/doc/bnazg.html

and this - http://docs.oracle.com/javase/6/docs/technotes/tools/share/xjc.html

2) JAXB (xjc utility) is installed together with JDK6 by default.

Difference between x86, x32, and x64 architectures?

x86 refers to the Intel processor architecture that was used in PCs. Model numbers were 8088 (8 bit bus version of 8086 and used in the first IBM PC), 8086, 286, 386, 486. After which they switched to names instead of numbers to stop AMD from copying the processor names. Pentium etc, never a Hexium :).

x64 is the architecture name for the extensions to the x86 instruction set that enable 64-bit code. Invented by AMD and later copied by Intel when they couldn't get their own 64-bit arch to be competitive, Itanium didn't fare well. Other names for it are x86_64, AMD's original name and commonly used in open source tools. And amd64, AMD's next name and commonly used in Microsoft tools. Intel's own names for it (EM64T and "Intel 64") never caught on.

x32 is a fuzzy term that's not associated with hardware. It tends to be used to mean "32-bit" or "32-bit pointer architecture", Linux has an ABI by that name.

Converting XML to JSON using Python?

To anyone that may still need this. Here's a newer, simple code to do this conversion.

from xml.etree import ElementTree as ET

xml    = ET.parse('FILE_NAME.xml')
parsed = parseXmlToJson(xml)


def parseXmlToJson(xml):
  response = {}

  for child in list(xml):
    if len(list(child)) > 0:
      response[child.tag] = parseXmlToJson(child)
    else:
      response[child.tag] = child.text or ''

    # one-liner equivalent
    # response[child.tag] = parseXmlToJson(child) if len(list(child)) > 0 else child.text or ''

  return response

MYSQL Sum Query with IF Condition

How about this?

SUM(IF(PaymentType = "credit card", totalamount, 0)) AS CreditCardTotal

missing private key in the distribution certificate on keychain

To add on to others' answers, if you don't have access to that private key anymore it's fairly simple to get back up and running:

  1. revoke your active certificate in the provisioning portal
  2. create new developer certificate (keychain access/.../request for csr...etc.)
  3. download and install a new certificate
  4. create a new provisioning profile for existing app id (on provisioning portal)
  5. download and install new provisioning profile and in the build, settings set the appropriate code signing identities

.NET Global exception handler in console application

You also need to handle exceptions from threads:

static void Main(string[] args) {
Application.ThreadException += MYThreadHandler;
}

private void MYThreadHandler(object sender, Threading.ThreadExceptionEventArgs e)
{
    Console.WriteLine(e.Exception.StackTrace);
}

Whoop, sorry that was for winforms, for any threads you're using in a console application you will have to enclose in a try/catch block. Background threads that encounter unhandled exceptions do not cause the application to end.

C++ Array of pointers: delete or delete []?

delete[] monsters is definitely wrong. My heap debugger shows the following output:

allocated non-array memory at 0x3e38f0 (20 bytes)
allocated non-array memory at 0x3e3920 (20 bytes)
allocated non-array memory at 0x3e3950 (20 bytes)
allocated non-array memory at 0x3e3980 (20 bytes)
allocated non-array memory at 0x3e39b0 (20 bytes)
allocated non-array memory at 0x3e39e0 (20 bytes)
releasing     array memory at 0x22ff38

As you can see, you are trying to release with the wrong form of delete (non-array vs. array), and the pointer 0x22ff38 has never been returned by a call to new. The second version shows the correct output:

[allocations omitted for brevity]
releasing non-array memory at 0x3e38f0
releasing non-array memory at 0x3e3920
releasing non-array memory at 0x3e3950
releasing non-array memory at 0x3e3980
releasing non-array memory at 0x3e39b0
releasing non-array memory at 0x3e39e0

Anyway, I prefer a design where manually implementing the destructor is not necessary to begin with.

#include <array>
#include <memory>

class Foo
{
    std::array<std::shared_ptr<Monster>, 6> monsters;

    Foo()
    {
        for (int i = 0; i < 6; ++i)
        {
            monsters[i].reset(new Monster());
        }
    }

    virtual ~Foo()
    {
        // nothing to do manually
    }
};

Code-first vs Model/Database-first

Code-first appears to be the rising star. I had a quick look at Ruby on Rails, and their standard is code-first, with database migrations.

If you are building an MVC3 application, I believe Code first has the following advantages:

  • Easy attribute decoration - You can decorate fields with validation, require, etc.. attributes, it's quite awkward with EF modelling
  • No weird modelling errors - EF modelling often has weird errors, such as when you try to rename an association property, it needs to match the underlying meta-data - very inflexible.
  • Not awkward to merge - When using code version control tools such as mercurial, merging .edmx files is a pain. You're a programmer used to C#, and there you are merging a .edmx. Not so with code-first.
  • Contrast back to Code first and you have complete control without all the hidden complexities and unknowns to deal with.
  • I recommend you use the Package Manager command line tool, don't even use the graphical tools to add a new controller to scaffold views.
  • DB-Migrations - Then you can also Enable-Migrations. This is so powerful. You make changes to your model in code, and then the framework can keep track of schema changes, so you can seamlessly deploy upgrades, with schema versions automatically upgraded (and downgraded if required). (Not sure, but this probably does work with model-first too)

Update

The question also asks for a comparison of code-first to EDMX model/db-first. Code-first can be used for both of these approaches too:

How to convert View Model into JSON object in ASP.NET MVC?

Well done, you've only just started using MVC and you've found its first major flaw.

You don't really want to be converting it to JSON in the view, and you don't really want to convert it in the controller, as neither of these locations make sense. Unfortunately, you're stuck with this situation.

The best thing I've found to do is send the JSON to the view in a ViewModel, like this:

var data = somedata;
var viewModel = new ViewModel();
var serializer = new JavaScriptSerializer();
viewModel.JsonData = serializer.Serialize(data);

return View("viewname", viewModel);

then use

<%= Model.JsonData %>

in your view. Be aware that the standard .NET JavaScriptSerializer is pretty crap.

doing it in the controller at least makes it testable (although not exactly like the above - you probably want to take an ISerializer as a dependency so you can mock it)

Update also, regarding your JavaScript, it would be good practice to wrap ALL the widget JS you have above like so:

(
    // all js here
)();

this way if you put multiple widgets on a page, you won't get conflicts (unless you need to access the methods from elsewhere in the page, but in that case you should be registering the widget with some widget framework anyway). It may not be a problem now, but it would be good practice to add the brackets now to save yourself muchos effort in the future when it becomes a requirement, it's also good OO practice to encapsulate the functionality.

Should ol/ul be inside <p> or outside?

actually you should only put in-line elements inside the p, so in your case ol is better outside

static const vs #define

Defining constants by using preprocessor directive #define is not recommended to apply not only in C++, but also in C. These constants will not have the type. Even in C was proposed to use const for constants.

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

I had same issue and I solved it by "pod setup" after installing cocoapods.

Using relative URL in CSS file, what location is it relative to?

This worked for me. adding two dots and slash.

body{
    background: url(../images/yourimage.png);
}

window.open with headers

Use POST instead

Although it is easy to construct a GET query using window.open(), it's a bad idea (see below). One workaround is to create a form that submits a POST request. Like so:

<form id="helper" action="###/your_page###" style="display:none">
<inputtype="hidden" name="headerData" value="(default)">
</form>

<input type="button" onclick="loadNnextPage()" value="Click me!">

<script>
function loadNnextPage() {
  document.getElementById("helper").headerData.value = "New";
  document.getElementById("helper").submit();
}
</script>

Of course you will need something on the server side to handle this; as others have suggested you could create a "proxy" script that sends headers on your behalf and returns the results.

Problems with GET

  • Query strings get stored in browser history,
  • can be shoulder-surfed
  • copy-pasted,
  • and often you don't want it to be easy to "refresh" the same transaction.

How to make a progress bar

If you need to show and hide progress bar inside your php and java script, then follow this step.Its a complete solution, no need of any library etc.

           //Design Progress Bar

  <style>
#spinner
{     
position: absolute;
left: 50%;
top: 50%;
background-color: white;
z-index: 100;

height: 200px;


width: 300px;
margin-left: -300px;

    /*Change your loading image here*/
   background: url(images/loading12.gif) 50% 50% no-repeat ;

}
  </style>

               //Progress Bar inside your Page

<div id="spinner" style=" display:none; ">
</div>                                

    // Button to show and Hide Progress Bar
<input class="submit" onClick="Show()" type="button" value="Show" /> 
<input class="submit" onClick="Hide()" type="button" value="Hide" /> 

            //Java Script Function to Handle Button Event     
<script language="javascript" type="text/javascript">
 function Show()
 {       
  document.getElementById("spinner").style.display = 'inline';
 }
function Hide()
 {       
  document.getElementById("spinner").style.display = 'none';
 }

</script>

Image link: Download image from here

How to initialize private static members in C++?

The class declaration should be in the header file (Or in the source file if not shared).
File: foo.h

class foo
{
    private:
        static int i;
};

But the initialization should be in source file.
File: foo.cpp

int foo::i = 0;

If the initialization is in the header file then each file that includes the header file will have a definition of the static member. Thus during the link phase you will get linker errors as the code to initialize the variable will be defined in multiple source files. The initialisation of the static int i must be done outside of any function.

Note: Matt Curtis: points out that C++ allows the simplification of the above if the static member variable is of const int type (e.g. int, bool, char). You can then declare and initialize the member variable directly inside the class declaration in the header file:

class foo
{
    private:
        static int const i = 42;
};

How can one create an overlay in css?

I was just playing around with a similar problem on codepen, this is what I did to create an overlay using a simple css markup. I created a div element with class .box applied to it. Inside this div I created two divs, one with .inner class applied to it and the other with .notext class applied to it. Both of these classes inside the .box div are initially set to display:none but when the .box is hovered over, these are made visible.

_x000D_
_x000D_
.box{_x000D_
  height:450px;_x000D_
  width:450px;_x000D_
  border:1px solid black;_x000D_
  margin-top:50px;_x000D_
  display:inline-block;_x000D_
  margin-left:50px;_x000D_
  transition: width 2s, height 2s;_x000D_
  position:relative;_x000D_
  text-align: center;_x000D_
    background:url('https://upload.wikimedia.org/wikipedia/commons/c/cd/Panda_Cub_from_Wolong,_Sichuan,_China.JPG');_x000D_
  background-size:cover;_x000D_
  background-position:center;_x000D_
  _x000D_
}_x000D_
.box:hover{_x000D_
  width:490px;_x000D_
  height:490px;_x000D_
}_x000D_
.inner{_x000D_
  border:1px solid red;_x000D_
  position:relative;_x000D_
  width:100%;_x000D_
  height:100%;_x000D_
  top:0px;_x000D_
  left:0px;_x000D_
  display:none; _x000D_
  color:white;_x000D_
  font-size:xx-large;_x000D_
  z-index:10;_x000D_
}_x000D_
.box:hover > .inner{_x000D_
  display:inline-block;_x000D_
}_x000D_
.notext{_x000D_
  height:30px;_x000D_
  width:30px;_x000D_
  border:1px solid blue;_x000D_
  position:absolute;_x000D_
  top:0px;_x000D_
  left:0px;_x000D_
  width:100%;_x000D_
  height:100%;_x000D_
  display:none;_x000D_
}_x000D_
.box:hover > .notext{_x000D_
  background-color:black;_x000D_
  opacity:0.5;_x000D_
  display:inline-block;_x000D_
}
_x000D_
<div class="box">_x000D_
  <div class="inner">_x000D_
    <p>Panda!</p>_x000D_
  </div>_x000D_
  <div class="notext"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope this helps! :) Any suggestions are welcome.

How to disable scrolling in UITableView table when the content fits on the screen

You can verify the number of visible cells using this function:

- (NSArray *)visibleCells

This method will return an array with the cells that are visible, so you can count the number of objects in this array and compare with the number of objects in your table.. if it's equal.. you can disable the scrolling using:

tableView.scrollEnabled = NO;

As @Ginny mentioned.. we would can have problems with partially visible cells, so this solution works better in this case:

tableView.scrollEnabled = (tableView.contentSize.height <= CGRectGetHeight(tableView.frame));

In case you are using autoLayout this solution do the job:

tableView.alwaysBounceVertical = NO.

How to generate keyboard events?

Every platform is going to have a different approach to being able to generate keyboard events. This is because they each need to make use of system libraries (and system extensions). For a cross platform solution, you would need to take each of these solutions and wrap then into a platform check to perform the proper approach.

For windows, you might be able to use the pywin32 extension. win32api.keybd_event

win32api.keybd_event

keybd_event(bVk, bScan, dwFlags, dwExtraInfo)

Simulate a keyboard event

Parameters

bVk : BYTE - Virtual-key code
bScan : BYTE - Hardware scan code
dwFlags=0 : DWORD - Flags specifying various function options
dwExtraInfo=0 : DWORD - Additional data associated with keystroke

You will need to investigate pywin32 for how to properly use it, as I have never used it.

How to call function on child component on parent events

You can use $emit and $on. Using @RoyJ code:

html:

<div id="app">
  <my-component></my-component>
  <button @click="click">Click</button>  
</div>

javascript:

var Child = {
  template: '<div>{{value}}</div>',
  data: function () {
    return {
      value: 0
    };
  },
  methods: {
    setValue: function(value) {
        this.value = value;
    }
  },
  created: function() {
    this.$parent.$on('update', this.setValue);
  }
}

new Vue({
  el: '#app',
  components: {
    'my-component': Child
  },
  methods: {
    click: function() {
        this.$emit('update', 7);
    }
  }
})

Running example: https://jsfiddle.net/rjurado/m2spy60r/1/

Is there a way to follow redirects with command line cURL?

Use the location header flag:

curl -L <URL>

sqlite copy data from one table to another

If you're copying data like that, that probably means your datamodel isn't fully normalized, right? Is it possible to make one list of countries and do a JOIN more?

Instead of a JOIN you could also use virtual tables so you don't have to change the queries in your system.

How to read connection string in .NET Core?

The way that I found to resolve this was to use AddJsonFile in a builder at Startup (which allows it to find the configuration stored in the appsettings.json file) and then use that to set a private _config variable

public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
        _config = builder.Build();
    }

And then I could set the configuration string as follows:

var connectionString = _config.GetConnectionString("DbContextSettings:ConnectionString"); 

This is on dotnet core 1.1

show dbs gives "Not Authorized to execute command" error

Create a user like this:

db.createUser(
      {
        user: "myUserAdmin",
        pwd: "abc123",
        roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
      }
    )

Then connect it following this:

mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"

Check the manual :

https://docs.mongodb.org/manual/tutorial/enable-authentication/

Uncaught SoapFault exception: [HTTP] Error Fetching http headers

Try to set :

default_socket_timeout = 120

in your php.ini file.

Android ImageView Fixing Image Size

Fix ImageView's size with dp or fill_parent and set android:scaleType to fitXY.

use regular expression in if-condition in bash

Adding this solution with grep and basic sh builtins for those interested in a more portable solution (independent of bash version; also works with plain old sh, on non-Linux platforms etc.)

# GLOB matching
gg=svm-grid-ch    
case "$gg" in
   *grid*) echo $gg ;;
esac

# REGEXP    
if echo "$gg" | grep '^....grid*' >/dev/null ; then echo $gg ; fi    
if echo "$gg" | grep '....grid*' >/dev/null ; then echo $gg ; fi    
if echo "$gg" | grep 's...grid*' >/dev/null ; then echo $gg ; fi    

# Extended REGEXP
if echo "$gg" | egrep '(^....grid*|....grid*|s...grid*)' >/dev/null ; then
  echo $gg
fi    

Some grep incarnations also support the -q (quiet) option as an alternative to redirecting to /dev/null, but the redirect is again the most portable.

Convert string into integer in bash script - "Leading Zero" number error

You could also use bc

hour=8
result=$(echo "$hour + 1" | bc)
echo $result
9

How to save to local storage using Flutter?

I was looking for the same, simple local storage but also with a reasonable level of security. The two solutions I've found that make the most sense are flutter_secure_storage (as mentioned by Raouf) for the small stuff, and hive for larger datasets.

iTerm2 keyboard shortcut - split pane navigation

From the documentation:

Cmd] and Cmd[ navigates among split panes in order of use.

CRON command to run URL address every 5 minutes

Based on the comments try

*/5 * * * * wget http://example.com/check

[Edit: 10 Apr 2017]

This answer still seems to be getting a few hits so I thought I'd add a link to a new page I stumbled across which may help create cron commands: https://crontab.guru

Why is Android Studio reporting "URI is not registered"?

For me, the offending xml files were missing the header line...

<?xml version="1.0" encoding="utf-8"?>

Adding that fixed it.

get string value from HashMap depending on key name

An important point to be noted here is that if your key is an object of user-defined class in java then make it a point to override the equals method. Because the HashMap.get(Object key) method uses the equals method for matching the key value. If you do not override the equals method then it will try to find the value simply based on the reference of the key and not the actual value of key in which case it will always return a null.

How Do I Uninstall Yarn

If you are still getting errors after deleting ~/.yarn about files not being found, don't forget to delete the yarn rc file:

rm ~/.yarnrc.yml 

Windows 7 - Add Path

Another method that worked for me on Windows 7 that did not require administrative privileges:

Click on the Start menu, search for "environment," click "Edit environment variables for your account."

In the window that opens, select "PATH" under "User variables for username" and click the "Edit..." button. Add your new path to the end of the existing Path, separated by a semi-colon (%PATH%;C:\Python27;...;C:\NewPath). Click OK on all the windows, open a new CMD window, and test the new variable.

How to change the value of ${user} variable used in Eclipse templates

It seems that your best bet is to redefine the java user.name variable either at your command line, or using the eclipse.ini file in your eclipse install root directory.

This seems to work fine for me:

-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256M
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Duser.name=Davide Inglima
-Xms40m
-Xmx512m    

Update:

http://morlhon.net/blog/2005/09/07/eclipse-username/ is a dead link...

Here's a new one: https://web.archive.org/web/20111225025454/http://morlhon.net:80/blog/2005/09/07/eclipse-username/

Copying Code from Inspect Element in Google Chrome

You can copy by inspect element and target the div you want to copy. Just press ctrl+c and then your div will be copy and paste in your code it will run easily.

Replace Multiple String Elements in C#

Maybe a little more readable?

    public static class StringExtension {

        private static Dictionary<string, string> _replacements = new Dictionary<string, string>();

        static StringExtension() {
            _replacements["&"] = "and";
            _replacements[","] = "";
            _replacements["  "] = " ";
            // etc...
        }

        public static string clean(this string s) {
            foreach (string to_replace in _replacements.Keys) {
                s = s.Replace(to_replace, _replacements[to_replace]);
            }
            return s;
        }
    }

Also add New In Town's suggestion about StringBuilder...

Wrap long lines in Python

There are two approaches which are not mentioned above, but both of which solve the problem in a way which complies with PEP 8 and allow you to make better use of your space. They are:

msg = (
    'This message is so long, that it requires '
    'more than {x} lines.{sep}'
    'and you may want to add more.').format(
        x=x, sep=2*'\n')
print(msg)

Notice how the parentheses are used to allow us not to add plus signs between pure strings, and spread the result over multiple lines without the need for explicit line continuation '\' (ugly and cluttered). The advantages are same with what is described below, the difference is that you can do it anywhere. Compared to the previous alternative, it is visually better when inspecting code, because it outlines the start and end of msg clearly (compare with msg += one every line, which needs one additional thinking step to deduce that those lines add to the same string - and what if you make a typo, forgetting a + on one random line ?).

Regarding this approach, many times we have to build a string using iterations and checks within the iteration body, so adding its pieces within the function call, as shown later, is not an option.

A close alternative is:

msg = 'This message is so long, that it requires '
msg += 'many lines to write, one reason for that\n'
msg += 'is that it contains numbers, like this '
msg += 'one: ' + str(x) +', which take up more space\n'
msg += 'to insert. Note how newlines are also included '
msg += 'and can be better presented in the code itself.'
print(msg)

Though the first is preferable.

The other approach is like the previous ones, though it starts the message on the line below the print. The reason for this is to gain space on the left, otherwise the print( itself "pushes" you to the right. This consumption of indentation is the inherited by the rest of the lines comprising the message, because according to PEP 8 they must align with the opening parenthesis of print above them. So if your message was already long, this way it's forced to be spread over even more lines.

Contrast:

raise TypeError('aaaaaaaaaaaaaaaa' +
                'aaaaaaaaaaaaaaaa' +
                'aaaaaaaaaaaaaaaa')

with this (suggested here):

raise TypeError(
    'aaaaaaaaaaaaaaaaaaaaaaaa' +
    'aaaaaaaaaaaaaaaaaaaaaaaa')

The line spread was reduced. Of course this last approach does no apply so much to print, because it is a short call. But it does apply to exceptions.

A variation you can have is:

raise TypeError((
    'aaaaaaaaaaaaaaaaaaaaaaaa'
    'aaaaaaaaaaaaaaaaaaaaaaaa'
    'aaaaa {x} aaaaa').format(x=x))

Notice how you don't need to have plus signs between pure strings. Also, the indentation guides the reader's eyes, no stray parentheses hanging below to the left. The replacements are very readable. In particular, such an approach makes writing code that generates code or mathematical formulas a very pleasant task.

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

You might have to move the mouse to any particular location after context click() like this -

Actions action = new Actions(driver);
actions.contextClick(link).moveByOffset(x,y).click().build().perform();

To understand how moveByOffset(x,y) works look here;

I hope this works. You will have to calculate the offset values for x and y;

best way would be to find the size of each option button after right clicking and then if you click on the 2nd option .

x = width of option button/2

y = 2*(size of each option button)

How to remove lines in a Matplotlib plot

Hopefully this can help others: The above examples use ax.lines. With more recent mpl (3.3.1), there is ax.get_lines(). This bypasses the need for calling ax.lines=[]

for line in ax.get_lines(): # ax.lines:
    line.remove()
# ax.lines=[] # needed to complete removal when using ax.lines

SQL QUERY replace NULL value in a row with a value from the previous known value

Here's a MySQL solution:

UPDATE mytable
SET number = (@n := COALESCE(number, @n))
ORDER BY date;

This is concise, but won't necessary work in other brands of RDBMS. For other brands, there might be a brand-specific solution that is more relevant. That's why it's important to tell us the brand you're using.

It's nice to be vendor-independent, as @Pax commented, but failing that, it's also nice to use your chosen brand of database to its fullest advantage.


Explanation of the above query:

@n is a MySQL user variable. It starts out NULL, and is assigned a value on each row as the UPDATE runs through rows. Where number is non-NULL, @n is assigned the value of number. Where number is NULL, the COALESCE() defaults to the previous value of @n. In either case, this becomes the new value of the number column and the UPDATE proceeds to the next row. The @n variable retains its value from row to row, so subsequent rows get values that come from the prior row(s). The order of the UPDATE is predictable, because of MySQL's special use of ORDER BY with UPDATE (this is not standard SQL).

Will Google Android ever support .NET?

Update: Since I wrote this answer two years ago, we productized Mono to run on Android. The work included a few steps: porting Mono to Android, integrating it with Visual Studio, building plugins for MonoDevelop on Mac and Windows and exposing the Java Android APIs to .NET languages. This is now available at http://monodroid.net

Mono on Android is based on the Mono 2.10 runtime, and defaults to 4.0 profile with the C# 4.0 compiler and uses Mono's new SGen garbage collection engine, as well as our new distributed garbage collection system that performs GC across Java and Mono.


The links below reflect Mono on Android as of January of 2009, I have kept them for historical context

Mono now works on Android thanks to the work of Koushik Dutta and Marc Crichton.

You can see a video of it running here: http://www.koushikdutta.com/2009/01/mono-on-android-with-gratuitous-shaky.html

And you can get the instructions to build Mono yourself here: http://www.koushikdutta.com/2009/01/building-mono-for-android.html

You can get a benchmark comparing Mono's JIT vs Dalvik's interpreter here: http://www.koushikdutta.com/2009/01/dalvik-vs-mono.html

And of course, you can get a pre-configured image with Mono here (go to the bottom of the post for details on using that): http://www.koushikdutta.com/2009/01/building-mono-for-android.html

What is "android.R.layout.simple_list_item_1"?

android.R.layout.simple_list_item_1, this is row layout file in your res/layout folder which contains the corresponding design for your row in listview. Now we just bind the array list items to the row layout by using mylistview.setadapter(aa);

jQuery select box validation

Jquery Select Box Validation.You can Alert Message via alert or Put message in Div as per your requirements.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="message"></div>_x000D_
<form method="post">_x000D_
<select name="year"  id="year">_x000D_
    <option value="0">Year</option>_x000D_
    <option value="1">1919</option>_x000D_
    <option value="2">1920</option>_x000D_
    <option value="3">1921</option>_x000D_
    <option value="4">1922</option>_x000D_
</select>_x000D_
<button id="clickme">Click</button>_x000D_
</form>_x000D_
<script>_x000D_
$("#clickme").click(function(){_x000D_
_x000D_
if( $("#year option:selected").val()=='0'){_x000D_
_x000D_
alert("Please select one option at least");_x000D_
_x000D_
  $("#message").html("Select At least one option");_x000D_
_x000D_
}_x000D_
_x000D_
_x000D_
});_x000D_
_x000D_
</script>
_x000D_
_x000D_
_x000D_

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

The Python 3 range() object doesn't produce numbers immediately; it is a smart sequence object that produces numbers on demand. All it contains is your start, stop and step values, then as you iterate over the object the next integer is calculated each iteration.

The object also implements the object.__contains__ hook, and calculates if your number is part of its range. Calculating is a (near) constant time operation *. There is never a need to scan through all possible integers in the range.

From the range() object documentation:

The advantage of the range type over a regular list or tuple is that a range object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the start, stop and step values, calculating individual items and subranges as needed).

So at a minimum, your range() object would do:

class my_range:
    def __init__(self, start, stop=None, step=1, /):
        if stop is None:
            start, stop = 0, start
        self.start, self.stop, self.step = start, stop, step
        if step < 0:
            lo, hi, step = stop, start, -step
        else:
            lo, hi = start, stop
        self.length = 0 if lo > hi else ((hi - lo - 1) // step) + 1

    def __iter__(self):
        current = self.start
        if self.step < 0:
            while current > self.stop:
                yield current
                current += self.step
        else:
            while current < self.stop:
                yield current
                current += self.step

    def __len__(self):
        return self.length

    def __getitem__(self, i):
        if i < 0:
            i += self.length
        if 0 <= i < self.length:
            return self.start + i * self.step
        raise IndexError('my_range object index out of range')

    def __contains__(self, num):
        if self.step < 0:
            if not (self.stop < num <= self.start):
                return False
        else:
            if not (self.start <= num < self.stop):
                return False
        return (num - self.start) % self.step == 0

This is still missing several things that a real range() supports (such as the .index() or .count() methods, hashing, equality testing, or slicing), but should give you an idea.

I also simplified the __contains__ implementation to only focus on integer tests; if you give a real range() object a non-integer value (including subclasses of int), a slow scan is initiated to see if there is a match, just as if you use a containment test against a list of all the contained values. This was done to continue to support other numeric types that just happen to support equality testing with integers but are not expected to support integer arithmetic as well. See the original Python issue that implemented the containment test.


* Near constant time because Python integers are unbounded and so math operations also grow in time as N grows, making this a O(log N) operation. Since it’s all executed in optimised C code and Python stores integer values in 30-bit chunks, you’d run out of memory before you saw any performance impact due to the size of the integers involved here.

React Modifying Textarea Values

I think you want something along the line of:

Parent:

<Editor name={this.state.fileData} />

Editor:

var Editor = React.createClass({
  displayName: 'Editor',
  propTypes: {
    name: React.PropTypes.string.isRequired
  },
  getInitialState: function() { 
    return {
      value: this.props.name
    };
  },
  handleChange: function(event) {
    this.setState({value: event.target.value});
  },
  render: function() {
    return (
      <form id="noter-save-form" method="POST">
        <textarea id="noter-text-area" name="textarea" value={this.state.value} onChange={this.handleChange} />
        <input type="submit" value="Save" />
      </form>
    );
  }
});

This is basically a direct copy of the example provided on https://facebook.github.io/react/docs/forms.html

Update for React 16.8:

import React, { useState } from 'react';

const Editor = (props) => {
    const [value, setValue] = useState(props.name);

    const handleChange = (event) => {
        setValue(event.target.value);
    };

    return (
        <form id="noter-save-form" method="POST">
            <textarea id="noter-text-area" name="textarea" value={value} onChange={handleChange} />
            <input type="submit" value="Save" />
        </form>
    );
}

Editor.propTypes = {
    name: PropTypes.string.isRequired
};

Copy Notepad++ text with formatting?

For those who do not see Plugins->NPPExport,

Download Plugin Manager from this. Extract contents and place under C/ProgramFile/NP++ installation, plugins & updater folder. Restart NP++. You should be able to see Plugins->Plugin Manager then. You can download any plugin, including NPPExport and install it to see the Copy command.

Java: How to check if object is null?

Drawable drawable = Common.getDrawableFromUrl(this, product.getMapPath());
if (drawable == null) {
    drawable = getRandomDrawable();
}

The equals() method checks for value equality, which means that it compares the contents of two objects. Since null is not an object, this crashes when trying to compare the contents of your object to the contents of null.

The == operator checks for reference equality, which means that it looks whether the two objects are actually the very same object. This does not require the objects to actually exist; two nonexistent objects (null references) are also equal.

What does cmd /C mean?

/C Carries out the command specified by the string and then terminates.

You can get all the cmd command line switches by typing cmd /?.

How do you format code on save in VS Code

For MAC user, add this line into your Default Settings

File path is: /Users/USER_NAME/Library/Application Support/Code/User/settings.json

"tslint.autoFixOnSave": true

Sample of the file would be:

{
    "window.zoomLevel": 0,
    "workbench.iconTheme": "vscode-icons",
    "typescript.check.tscVersion": false,
    "vsicons.projectDetection.disableDetect": true,
    "typescript.updateImportsOnFileMove.enabled": "always",
    "eslint.autoFixOnSave": true,
    "tslint.autoFixOnSave": true
}

Invert match with regexp

Based on Daniel's answer, I think I've got something that works:

^(.(?!test))*$

The key is that you need to make the negative assertion on every character in the string

How to determine if Javascript array contains an object with an attribute that equals a given value?

const check = vendors.find((item)=>item.Name==='Magenic')

console.log(check)

Try this code.

If the item or element is present then the output will show you that element. If it is not present then the output will be 'undefined'.

MySQL check if a table exists without throwing an exception

$q = "SHOW TABLES";
$res = mysql_query($q, $con);
if ($res)
while ( $row = mysql_fetch_array($res, MYSQL_ASSOC) )
{
    foreach( $row as $key => $value )
    {
        if ( $value = BTABLE )  // BTABLE IS A DEFINED NAME OF TABLE
            echo "exist";
        else
            echo "not exist";
    }
}

Node.js Generate html

You can use jsdom

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const { document } = (new JSDOM(`...`)).window;

or, take a look at cheerio, it may more suitable in your case.

Reading file contents on the client-side in javascript in various browsers

Happy coding!
If you get an error on Internet Explorer, Change the security settings to allow ActiveX

var CallBackFunction = function(content) {
  alert(content);
}
ReadFileAllBrowsers(document.getElementById("file_upload"), CallBackFunction);
//Tested in Mozilla Firefox browser, Chrome
function ReadFileAllBrowsers(FileElement, CallBackFunction) {
  try {
    var file = FileElement.files[0];
    var contents_ = "";

    if (file) {
      var reader = new FileReader();
      reader.readAsText(file, "UTF-8");
      reader.onload = function(evt) {
        CallBackFunction(evt.target.result);
      }
      reader.onerror = function(evt) {
        alert("Error reading file");
      }
    }
  } catch (Exception) {
    var fall_back = ieReadFile(FileElement.value);
    if (fall_back != false) {
      CallBackFunction(fall_back);
    }
  }
}
///Reading files with Internet Explorer
function ieReadFile(filename) {
  try {
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile(filename, 1);
    var contents = fh.ReadAll();
    fh.Close();
    return contents;
  } catch (Exception) {
    alert(Exception);
    return false;
  }
}

Removing whitespace between HTML elements when using line breaks

The whitespace between the elements is only put there by the HTML editor for visual formatting purposes. You can use jQuery to remove the whitespace:

$("div#MyImages").each(function () {

    var div = $(this);
    var children= div.children();
    children.detach();
    div.empty();
    div.append(children);

});

This detaches the child elements, clears any whitespace that remains before adding the child elements back again.

Unlike the other answers to this question, using this method ensures that the inherited css display and font-size values are maintained. There's also no need to use float and the cumbersome clear that is then required. Of course, you will need to be using jQuery.

Facebook how to check if user has liked page and show content?

UPDATE 21/11/2012 @ALL : I have updated the example so that it works better and takes into accounts remarks from Chris Jacob and FB Best practices, have a look of working example here


Hi So as promised here is my answer using only javascript :

The content of the BODY of the page :

<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
  FB.init({
    appId  : 'YOUR APP ID',
    status : true, 
    cookie : true, 
    xfbml  : true  
  });
</script>

<div id="container_notlike">
YOU DONT LIKE
</div>

<div id="container_like">
YOU LIKE
</div>

The CSS :

body {
width:520px;
margin:0; padding:0; border:0;
font-family: verdana;
background:url(repeat.png) repeat;
margin-bottom:10px;
}
p, h1 {width:450px; margin-left:50px; color:#FFF;}
p {font-size:11px;}

#container_notlike, #container_like {
    display:none
}

And finally the javascript :

$(document).ready(function(){

    FB.login(function(response) {
      if (response.session) {

          var user_id = response.session.uid;
          var page_id = "40796308305"; //coca cola
          var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
          var the_query = FB.Data.query(fql_query);

          the_query.wait(function(rows) {

              if (rows.length == 1 && rows[0].uid == user_id) {
                  $("#container_like").show();

                  //here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.

              } else {
                  $("#container_notlike").show();
                  //and here you could get the content for a non liker in ajax...
              }
          });


      } else {
        // user is not logged in
      }
    });

});

So what what does it do ?

First it logins to FB (if you already have the USER ID, and you are sure your user is already logged in facebook, you can bypass the login stuff and replace response.session.uid with YOUR_USER_ID (from your rails app for example)

After that it makes a FQL query on the page_fan table, and the meaning is that if the user is a fan of the page, it returns the user id and otherwise it returns an empty array, after that and depending on the results its show a div or the other.

Also there is a working demo here : http://jsfiddle.net/dwarfy/X4bn6/

It's using the coca-cola page as an example, try it go and like/unlike the coca cola page and run it again ...

Finally some related docs :

FQL page_fan table

FBJS FB.Data.query

Don't hesitate if you have any question ..

Cheers

UPDATE 2

As stated by somebody, jQuery is required for the javascript version to work BUT you could easily remove it (it's only used for the document.ready and show/hide).

For the document.ready, you could wrap your code in a function and use body onload="your_function" or something more complicated like here : Javascript - How to detect if document has loaded (IE 7/Firefox 3) so that we replace document ready.

And for the show and hide stuff you could use something like : document.getElementById("container_like").style.display = "none" or "block" and for more reliable cross browser techniques see here : http://www.webmasterworld.com/forum91/441.htm

But jQuery is so easy :)

UPDATE

Relatively to the comment I posted here below here is some ruby code to decode the "signed_request" that facebook POST to your CANVAS URL when it fetches it for display inside facebook.

In your action controller :

decoded_request = Canvas.parse_signed_request(params[:signed_request])

And then its a matter of checking the decoded request and display one page or another .. (Not sure about this one, I'm not comfortable with ruby)

decoded_request['page']['liked']

And here is the related Canvas Class (from fbgraph ruby library) :

 class Canvas

    class << self
      def parse_signed_request(secret_id,request)
        encoded_sig, payload = request.split('.', 2)
        sig = ""
        urldecode64(encoded_sig).each_byte { |b|
          sig << "%02x" % b
        }
        data = JSON.parse(urldecode64(payload))
          if data['algorithm'].to_s.upcase != 'HMAC-SHA256'
          raise "Bad signature algorithm: %s" % data['algorithm']
        end
        expected_sig = OpenSSL::HMAC.hexdigest('sha256', secret_id, payload)
        if expected_sig != sig
          raise "Bad signature"
        end
        data
      end

      private

      def urldecode64(str)
        encoded_str = str.gsub('-','+').gsub('_','/')
        encoded_str += '=' while !(encoded_str.size % 4).zero?
        Base64.decode64(encoded_str)
      end
    end  

 end

Eclipse change project files location

This link shows how to edit the eclipse workspace metadata to update the project's location manually, useful if the location has already changed or you have a lot of projects to move and don't want to do several clicks and waits for each one: https://web.archive.org/web/20160421171614/http://www.joeflash.ca/blog/2008/11/moving-a-fb-workspace-update.html

?: operator (the 'Elvis operator') in PHP

Be careful with arrays. We must write a checking variable after ?, because:

  $params = ['param1' => 'value1',
             'param2' => 'value2',
             'param3' => 'value3',];

  $param1 = isset($params['param1'])?:null;
  $param2 = !empty($params['param2'])?:null;
  $param3 = $params['param3']?:null; // get E_NOTICE, if $params['param3'] eq false

  var_dump($param1,$param2,$param3);
  true // would like to expect `value1`
  true // would like to expect `value2`
  param3 // properly, but problem above

Updated

From RFC. In PHP 7 the operator Null Coalesce Operator will do it, for example:

$param1 = $params['param1'] ?? null;
// Equivalent to:  $param1 = isset($params['param1']) ? $params['param1'] : null;

How can I get the URL of the current tab from a Google Chrome extension?

Warning! chrome.tabs.getSelected is deprecated. Please use chrome.tabs.query as shown in the other answers.


First, you've to set the permissions for the API in manifest.json:

"permissions": [
    "tabs"
]

And to store the URL :

chrome.tabs.getSelected(null,function(tab) {
    var tablink = tab.url;
});

How to use UTF-8 in resource properties with ResourceBundle

package com.varaneckas.utils;  

import java.io.UnsupportedEncodingException;  
import java.util.Enumeration;  
import java.util.PropertyResourceBundle;  
import java.util.ResourceBundle;  

/** 
 * UTF-8 friendly ResourceBundle support 
 *  
 * Utility that allows having multi-byte characters inside java .property files. 
 * It removes the need for Sun's native2ascii application, you can simply have 
 * UTF-8 encoded editable .property files. 
 *  
 * Use:  
 * ResourceBundle bundle = Utf8ResourceBundle.getBundle("bundle_name"); 
 *  
 * @author Tomas Varaneckas <[email protected]> 
 */  
public abstract class Utf8ResourceBundle {  

    /** 
     * Gets the unicode friendly resource bundle 
     *  
     * @param baseName 
     * @see ResourceBundle#getBundle(String) 
     * @return Unicode friendly resource bundle 
     */  
    public static final ResourceBundle getBundle(final String baseName) {  
        return createUtf8PropertyResourceBundle(  
                ResourceBundle.getBundle(baseName));  
    }  

    /** 
     * Creates unicode friendly {@link PropertyResourceBundle} if possible. 
     *  
     * @param bundle  
     * @return Unicode friendly property resource bundle 
     */  
    private static ResourceBundle createUtf8PropertyResourceBundle(  
            final ResourceBundle bundle) {  
        if (!(bundle instanceof PropertyResourceBundle)) {  
            return bundle;  
        }  
        return new Utf8PropertyResourceBundle((PropertyResourceBundle) bundle);  
    }  

    /** 
     * Resource Bundle that does the hard work 
     */  
    private static class Utf8PropertyResourceBundle extends ResourceBundle {  

        /** 
         * Bundle with unicode data 
         */  
        private final PropertyResourceBundle bundle;  

        /** 
         * Initializing constructor 
         *  
         * @param bundle 
         */  
        private Utf8PropertyResourceBundle(final PropertyResourceBundle bundle) {  
            this.bundle = bundle;  
        }  

        @Override  
        @SuppressWarnings("unchecked")  
        public Enumeration getKeys() {  
            return bundle.getKeys();  
        }  

        @Override  
        protected Object handleGetObject(final String key) {  
            final String value = bundle.getString(key);  
            if (value == null)  
                return null;  
            try {  
                return new String(value.getBytes("ISO-8859-1"), "UTF-8");  
            } catch (final UnsupportedEncodingException e) {  
                throw new RuntimeException("Encoding not supported", e);  
            }  
        }  
    }  
}  

How to access the php.ini file in godaddy shared hosting linux

Follow below if you use godaddy shared hosting.. its very simple: we need to access root folder of the server via ftp, create a "php5.ini" named file under public_html folder... and then add 3 stupid lines... also "php5" because I'm using php5.4 for 1 of my client. you can check your version via control panel and search php version. Adding a new file with php5.ini will not hamper anything on server end, but it will only overwrite whatever we are commanding it to do.

steps are simple: go to file manager.. click on public_html.. a new window will appear.. Click on "+"sign and create a new file in the name: "php5.ini" ... click ok/save. Now right click on that newly created php5.ini file and click on edit... a new window will appear... copy paste these below lines & click on save and close the window.

memory_limit = 128M

upload_max_filesize = 60M

max_input_vars = 5000

HTML5 Video // Completely Hide Controls

You could hide controls using CSS Pseudo Selectors like Demo: https://jsfiddle.net/g1rsasa3

_x000D_
_x000D_
//For Firefox we have to handle it in JavaScript _x000D_
var vids = $("video"); _x000D_
$.each(vids, function(){_x000D_
       this.controls = false; _x000D_
}); _x000D_
//Loop though all Video tags and set Controls as false_x000D_
_x000D_
$("video").click(function() {_x000D_
  //console.log(this); _x000D_
  if (this.paused) {_x000D_
    this.play();_x000D_
  } else {_x000D_
    this.pause();_x000D_
  }_x000D_
});
_x000D_
video::-webkit-media-controls {_x000D_
  display: none;_x000D_
}_x000D_
_x000D_
/* Could Use thise as well for Individual Controls */_x000D_
video::-webkit-media-controls-play-button {}_x000D_
_x000D_
video::-webkit-media-controls-volume-slider {}_x000D_
_x000D_
video::-webkit-media-controls-mute-button {}_x000D_
_x000D_
video::-webkit-media-controls-timeline {}_x000D_
_x000D_
video::-webkit-media-controls-current-time-display {}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>_x000D_
<!-- Hiding HTML5 Video Controls using CSS Pseudo selectors -->_x000D_
_x000D_
<video width="800" autoplay controls="false">_x000D_
  <source src="http://clips.vorwaerts-gmbh.de/VfE_html5.mp4" type="video/mp4">_x000D_
</video>
_x000D_
_x000D_
_x000D_

Bootstrap 3 - How to load content in modal body via AJAX?

In the case where you need to update the same modal with content from different Ajax / API calls here's a working solution.

$('.btn-action').click(function(){
    var url = $(this).data("url"); 
    $.ajax({
        url: url,
        dataType: 'json',
        success: function(res) {

            // get the ajax response data
            var data = res.body;

            // update modal content here
            // you may want to format data or 
            // update other modal elements here too
            $('.modal-body').text(data);

            // show modal
            $('#myModal').modal('show');

        },
        error:function(request, status, error) {
            console.log("ajax call went wrong:" + request.responseText);
        }
    });
});

Bootstrap 3 Demo
Bootstrap 4 Demo

Debugging PHP Mail() and/or PHPMailer

It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

I've always used phpMailer's SMTP feature:

$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:

$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only

How to return a complex JSON response with Node.js?

[Edit] After reviewing the Mongoose documentation, it looks like you can send each query result as a separate chunk; the web server uses chunked transfer encoding by default so all you have to do is wrap an array around the items to make it a valid JSON object.

Roughly (untested):

app.get('/users/:email/messages/unread', function(req, res, next) {
  var firstItem=true, query=MessageInfo.find(/*...*/);
  res.writeHead(200, {'Content-Type': 'application/json'});
  query.each(function(docs) {
    // Start the JSON array or separate the next element.
    res.write(firstItem ? (firstItem=false,'[') : ',');
    res.write(JSON.stringify({ msgId: msg.fileName }));
  });
  res.end(']'); // End the JSON array and response.
});

Alternatively, as you mention, you can simply send the array contents as-is. In this case the response body will be buffered and sent immediately, which may consume a large amount of additional memory (above what is required to store the results themselves) for large result sets. For example:

// ...
var query = MessageInfo.find(/*...*/);
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(query.map(function(x){ return x.fileName })));

JPA: unidirectional many-to-one and cascading delete

Relationships in JPA are always unidirectional, unless you associate the parent with the child in both directions. Cascading REMOVE operations from the parent to the child will require a relation from the parent to the child (not just the opposite).

You'll therefore need to do this:

  • Either, change the unidirectional @ManyToOne relationship to a bi-directional @ManyToOne, or a unidirectional @OneToMany. You can then cascade REMOVE operations so that EntityManager.remove will remove the parent and the children. You can also specify orphanRemoval as true, to delete any orphaned children when the child entity in the parent collection is set to null, i.e. remove the child when it is not present in any parent's collection.
  • Or, specify the foreign key constraint in the child table as ON DELETE CASCADE. You'll need to invoke EntityManager.clear() after calling EntityManager.remove(parent) as the persistence context needs to be refreshed - the child entities are not supposed to exist in the persistence context after they've been deleted in the database.

When is a language considered a scripting language?

The most commonly know essay written on the topic by a note-worthy source I know of is called Ousterhout's dichotomy. It is highly criticized as being fairly arbitrary and often jokingly refereed to as Ousterhout's false dichotomy. That being said in a discussion about the topic it deserves a citation.

I personally agree that this is a false dichotomy and I wouldn't trust anyone answering this question that proposes to have firm properties as to what defines a scripting language. Comments like "a scripting language must be dynamically typed" are false and comments like "scripting languages must be interpreted" don't even make sense because contrary to popular belief, compilation vs. interpretation is not a property of the language at all.

There are lots of properties that people have mentioned above as roughly matching scripting languages, thankfully most of them properly explaining that this term has no rigorous definition. So I won't duplicate my ideas of what they are here. For my experience people consider a language a scripting language if they can easily write some quick throwaway programs in them without writing much boiler plate. I'm mostly answering to give you the citation to Ousterhout which I don't see here.

Use of min and max functions in C++

If your implementation provides a 64-bit integer type, you may get a different (incorrect) answer by using fmin or fmax. Your 64-bit integers will be converted to doubles, which will (at least usually) have a significand that's smaller than 64-bits. When you convert such a number to a double, some of the least significant bits can/will be lost completely.

This means that two numbers that were really different could end up equal when converted to double -- and the result will be that incorrect number, that's not necessarily equal to either of the original inputs.

How to find patterns across multiple lines using grep?

With ugrep released a few months ago:

ugrep 'abc(\n|.)+?efg'

This tool is highly optimized for speed. It's also GNU/BSD/PCRE-grep compatible.

Note that we should use a lazy repetition +?, unless you want to match all lines with efg together until the last efg in the file.

How to check that a JCheckBox is checked?

By using itemStateChanged(ItemListener) you can track selecting and deselecting checkbox (and do whatever you want based on it):

myCheckBox.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
            //do something...
        } else {//checkbox has been deselected
            //do something...
        };
    }
});

Java Swing itemStateChanged docu should help too. By using isSelected() method you can just test if actual is checkbox selected:

if(myCheckBox.isSelected()){_do_something_if_selected_}

Convert seconds to hh:mm:ss in Python

Not being a Python person, but the easiest without any libraries is just:

total   = 3800
seconds = total % 60
total   = total - seconds
hours   = total / 3600
total   = total - (hours * 3600)
mins    = total / 60

How to replace url parameter with javascript/jquery?

UpdatE: Make it into a nice function for you: http://jsfiddle.net/wesbos/KH25r/1/

function swapOutSource(url, newSource) {
    params = url.split('&');
    var src = params[0].split('=');
    params.shift();
    src[1] = newSource;
    var newUrl = ( src.join('=') + params.join('&')); 
    return newUrl; 
}

Then go at it!

var newUrl = swapOutSource("http://localhost/mysite/includes/phpThumb.php?src=http://media2.jupix.co.uk/v3/clients/4/properties/795/IMG_795_1_large.jpg&w=592&aoe=1&q=100","http://link/to/new.jpg");


console.log(newUrl);

Android SDK Manager gives "Failed to fetch URL https://dl-ssl.google.com/android/repository/repository.xml" error when selecting repository

If you enter the URL in a browser and then look at the source code of the page you will see that an XML document is returned.

The reason why that URL would work in a browser but not in the android manager might be that you are required to specify a proxy server. In Eclipse (3.5.2) the proxy settings can be found here: "Window" -> "Preferences" -> "General" -> "Network Connections"

Check if specific input file is empty

simple :

if($_FILES['cover_image']['error'] > 0)
    // cover_image is empty

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

The reason a List<Dog> is not a List<Animal>, is that, for example, you can insert a Cat into a List<Animal>, but not into a List<Dog>... you can use wildcards to make generics more extensible where possible; for example, reading from a List<Dog> is the similar to reading from a List<Animal> -- but not writing.

The Generics in the Java Language and the Section on Generics from the Java Tutorials have a very good, in-depth explanation as to why some things are or are not polymorphic or permitted with generics.

Sending HTML Code Through JSON

In PHP:

$data = "<html>....";
exit(json_encode($data));

Then you should use AJAX to retrieve the data and do what you want with it. I suggest using JQuery: http://api.jquery.com/jQuery.getJSON/

MySQL skip first 10 results

If your table has ordering by id, you could easily done by:

select * from table where id > 10

Apple Cover-flow effect using jQuery or other library?

http://www.jacksasylum.eu/ContentFlow/

  • is the best I ever found. a true 'CoverFlow', highly configurable, cross-browser, very smooth action, has relections and supports scroll wheel + keyboard control. - has to be what your looking for!

curl error 18 - transfer closed with outstanding read data remaining

I had this problem working with pycurl and I solved it using

c.setopt(pycurl.HTTP_VERSION, pycurl.CURL_HTTP_VERSION_1_0) 

like Eric Caron says.

How to create timer in angular2

With rxjs 6.2.2 and Angular 6.1.7, I was getting an:

Observable.timer is not a function

error. This was resolved by replacing Observable.timer with timer:

import { timer, Subscription } from 'rxjs';

private myTimerSub: Subscription;    

ngOnInit(){    
    const ti = timer(2000,1000);    
    this.myTimerSub = ti.subscribe(t => {    
        console.log("Tick");    
    });    
}    

ngOnDestroy() {    
    this.myTimerSub.unsubscribe();    
}

Error: package or namespace load failed for ggplot2 and for data.table

Faced same issue and solved by :

remove.packages("ggplot2")
install.packages('ggplot2', dependencies = TRUE)

Visual Studio breakpoints not being hit

Solved. Ended up being an incorrect configuration selected in the debug menu. I had mistakenly switched it to a release configuration that could not load the symbols for the document. Switched it to a debug configuration and the breakpoints hit just fine now.

To add on to what Abacus mentioned below, it could also be a web.config transform that is messing with your build. In our case, we have Release configurations that remove the debug attribute from the web.config's compilation section. Below is a screenshot of an example and Visual Studio's dropdown list of build configurations.

NOTE: Also make sure your Platform is correct along with the configuration. In my case, Dev.Debug|Mixed Platforms does not correctly build the solution but Dev.Debug|Any CPU will.

Build Configuration List

How does one make random number between range for arc4random_uniform()?

The answer is just 1 line code:

let randomNumber = arc4random_uniform(8999) + 1000 //for 4 digit random number
let randomNumber = arc4random_uniform(899999999) + 100000000 //for 9 digit random number
let randomNumber = arc4random_uniform(89) + 10    //for 2 digit random number
let randomNumber = arc4random_uniform(899) + 100  //for 3 digit random number

The alternate solution is:

    func generateRandomNumber(numDigits: Int) -> Int{
    var place = 1
    var finalNumber = 0;
    var finanum = 0;
    for var i in 0 ..< numDigits {
        place *= 10
        let randomNumber = arc4random_uniform(10)         
        finalNumber += Int(randomNumber) * place
        finanum = finalNumber / 10
           i += 1
    }
    return finanum
}

Although the drawback is that number cannot start from 0.

restart mysql server on windows 7

use net stop mysql57 instead, it should be the version that is not specified