Programs & Examples On #Intentfilter

In Android, an IntentFilter expresses a component's interest in or ability to handle particular data or actions. can match against actions, categories, and data (via its type, scheme, and/or path) in an Intent. It also includes a "priority" value which is used to order multiple matching filters.

How to implement my very own URI scheme on Android

Another alternate approach to Diego's is to use a library:

https://github.com/airbnb/DeepLinkDispatch

You can easily declare the URIs you'd like to handle and the parameters you'd like to extract through annotations on the Activity, like:

@DeepLink("path/to/what/i/want")
public class SomeActivity extends Activity {
  ...
}

As a plus, the query parameters will also be passed along to the Activity as well.

Unable to start Service Intent

I've found the same problem. I lost almost a day trying to start a service from OnClickListener method - outside the onCreate and after 1 day, I still failed!!!! Very frustrating! I was looking at the sample example RemoteServiceController. Theirs works, but my implementation does not work!

The only way that was working for me, was from inside onCreate method. None of the other variants worked and believe me I've tried them all.

Conclusion:

  • If you put your service class in different package than the mainActivity, I'll get all kind of errors
  • Also the one "/" couldn't find path to the service, tried starting with Intent(package,className) and nothing , also other type of Intent starting

  • I moved the service class in the same package of the activity Final form that works

  • Hopefully this helps someone by defining the listerners onClick inside the onCreate method like this:

    public void onCreate() {
    //some code......
        Button btnStartSrv  = (Button)findViewById(R.id.btnStartService);
        Button btnStopSrv  = (Button)findViewById(R.id.btnStopService);
    
        btnStartSrv.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                startService(new Intent("RM_SRV_AIDL"));
            }
        });
    
        btnStopSrv.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                stopService(new Intent("RM_SRV_AIDL"));
            }
        });
    
    } // end onCreate
    

Also very important for the Manifest file, be sure that service is child of application:

<application ... >
    <activity ... >
     ...
    </activity>
    <service
        android:name="com.mainActivity.MyRemoteGPSService"
        android:label="GPSService"
        android:process=":remote">

        <intent-filter>
             <action android:name="RM_SRV_AIDL" />
        </intent-filter>
    </service>
</application>

Pick any kind of file via an Intent in Android

The other answers are not incorrect. However, now there are more options for opening files. For example, if you want the app to have long term, permanent acess to a file, you can use ACTION_OPEN_DOCUMENT instead. Refer to the official documentation: Open files using storage access framework. Also refer to this answer.

What are intent-filters in Android?

First change the xml, mark your second activity as DEFAULT

<activity android:name=".AddNewActivity" android:label="@string/app_name">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

Now you can initiate this activity using StartActivity method.

Launch custom android application from android browser

The following link gives information on launching the app (if installed) directly from browser. Otherwise it directly opens up the app in play store so that user can seamlessly download.

https://developer.chrome.com/multidevice/android/intents

Android Respond To URL in Intent

I did it! Using <intent-filter>. Put the following into your manifest file:

<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
  <data android:host="www.youtube.com" android:scheme="http" />
</intent-filter>

This works perfectly!

Redirecting 404 error with .htaccess via 301 for SEO etc

I came up with the solution and posted it on my blog

http://web.archive.org/web/20130310123646/http://onlinemarketingexperts.com.au/2013/01/how-to-permanently-redirect-301-all-404-missing-pages-in-htaccess/

here is the htaccess code also

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . / [L,R=301]

but I posted other solutions on my blog too, it depends what you need really

asynchronous vs non-blocking

Putting this question in the context of NIO and NIO.2 in java 7, async IO is one step more advanced than non-blocking. With java NIO non-blocking calls, one would set all channels (SocketChannel, ServerSocketChannel, FileChannel, etc) as such by calling AbstractSelectableChannel.configureBlocking(false). After those IO calls return, however, you will likely still need to control the checks such as if and when to read/write again, etc.
For instance,

while (!isDataEnough()) {
    socketchannel.read(inputBuffer);
    // do something else and then read again
}

With the asynchronous api in java 7, these controls can be made in more versatile ways. One of the 2 ways is to use CompletionHandler. Notice that both read calls are non-blocking.

asyncsocket.read(inputBuffer, 60, TimeUnit.SECONDS /* 60 secs for timeout */, 
    new CompletionHandler<Integer, Object>() {
        public void completed(Integer result, Object attachment) {...}  
        public void failed(Throwable e, Object attachment) {...}
    }
}

Chrome violation : [Violation] Handler took 83ms of runtime

It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.

4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.

If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.

Check whether an array is empty

From the PHP-documentation:

Returns FALSE if var has a non-empty and non-zero value.

The following things are considered to be empty:

"" (an empty string)
0 (0 as an integer)
0.0 (0 as a float)
"0" (0 as a string)
NULL
FALSE
array() (an empty array)
var $var; (a variable declared, but without a value in a class)

How do I install soap extension?

find this line in php.ini :

;extension=soap

then remove the semicolon ; and restart Apache server

SQLite Query in Android to count rows

DatabaseUtils.queryNumEntries (since api:11) is useful alternative that negates the need for raw SQL(yay!).

SQLiteDatabase db = getReadableDatabase();
DatabaseUtils.queryNumEntries(db, "users",
                "uname=? AND pwd=?", new String[] {loginname,loginpass});

How to create PDF files in Python

If you are familiar with LaTex you might want to consider pylatex

One of the advantages of pylatex is that it is easy to control the image quality. The images in your pdf will be of the same quality as the original images. When using reportlab, I experienced that the images were automatically compressed, and the image quality reduced.

The disadvantage of pylatex is that, since it is based on LaTex, it can be hard to place images exactly where you want on the page. However, I have found that using the position argument in the Figure class, and sometimes Subfigure, gives good enough results.

Example code for creating a pdf with a single image:

from pylatex import Document, Figure

doc = Document(documentclass="article")
with doc.create(Figure(position='p')) as fig:
fig.add_image('Lenna.png')

doc.generate_pdf('test', compiler='latexmk', compiler_args=["-pdf", "-pdflatex=pdflatex"], clean_tex=True)

In addition to installing pylatex (pip install pylatex), you need to install LaTex. For Ubuntu and other Debian systems you can run sudo apt-get install texlive-full. If you are using Windows I would recommend MixTex

Find a value in an array of objects in Javascript

You can use query-objects from npm. You can search an array of objects using filters.

const queryable = require('query-objects');

const users = [
    {
      firstName: 'George',
      lastName: 'Eracleous',
      age: 28
    },
    {
      firstName: 'Erica',
      lastName: 'Archer',
      age: 50
    },
    {
      firstName: 'Leo',
      lastName: 'Andrews',
      age: 20
    }
];

const filters = [
    {
      field: 'age',
      value: 30,
      operator: 'lt'
    },
    {
      field: 'firstName',
      value: 'Erica',
      operator: 'equals'
    }
];

// Filter all users that are less than 30 years old AND their first name is Erica
const res = queryable(users).and(filters);

// Filter all users that are less than 30 years old OR their first name is Erica
const res = queryable(users).or(filters);

Can I get a patch-compatible output from git-diff?

A useful trick to avoid creating temporary patch files:

git diff | patch -p1 -d [dst-dir]

How can I rename a conda environment?

Based upon dwanderson's helpful comment, I was able to do this in a Bash one-liner:

conda create --name envpython2 --file <(conda list -n env1 -e )

My badly named env was "env1" and the new one I wish to clone from it is "envpython2".

Is there a Google Sheets formula to put the name of the sheet into a cell?

I got this to finally work in a semi-automatic fashion without the use of scripts... but it does take up 3 cells to pull it off. Borrowing from a bit from previous answers, I start with a cell that has nothing more than =NOW() it in to show the time. For example, we'll put this into cell A1...

=NOW()

This function updates automatically every minute. In the next cell, put a pointer formula using the sheets own name to point to the previous cell. For example, we'll put this in A2...

='Sheet Name'!A1

Cell formatting aside, cell A1 and A2 should at this point display the same content... namely the current time.

And, the last cell is the part I'm borrowing from previous solutions using a regex expression to pull the fomula from the second cell and then strip out the name of the sheet from said formula. For example, we'll put this into cell A3...

=REGEXREPLACE(FORMULATEXT(A2),"='?([^']+)'?!.*","$1")

At this point, the resultant value displayed in A3 should be the name of the sheet.

From my experience, as soon as the name of the sheet is changed, the formula in A2 is immediately updated. However that's not enough to trigger A3 to update. But, every minute when cell A1 recalculates the time, the result of the formula in cell A2 is subsequently updated and then that in turn triggers A3 to update with the new sheet name. It's not a compact solution... but it does seem to work.

VB.NET - Click Submit Button on Webbrowser page

You could try giving an ID to the form, in order to get ahold of it, and then call form.submit() from a Javascript call.

How do I convert an interval into a number of hours with postgres?

select floor((date_part('epoch', order_time - '2016-09-05 00:00:00') / 3600)), count(*)
from od_a_week
group by floor((date_part('epoch', order_time - '2016-09-05 00:00:00') / 3600));

The ::int conversion follows the principle of rounding. If you want a different result such as rounding down, you can use the corresponding math function such as floor.

IIS URL Rewrite and Web.config

Just tried this rule, and it worked with GoDaddy hosting since they've already have the Microsoft URL Rewriting module installed for every IIS 7 account.

<rewrite>
  <rules>
    <rule name="enquiry" stopProcessing="true">
      <match url="^enquiry$" />
      <action type="Rewrite" url="/Enquiry.aspx" />
    </rule>
  </rules>
</rewrite>

How to ensure a <select> form field is submitted when it is disabled?

Disable the fields and then enable them before the form is submitted:

jQuery code:

jQuery(function ($) {        
  $('form').bind('submit', function () {
    $(this).find(':input').prop('disabled', false);
  });
});

How to compare strings

In C++ the std::string class implements the comparison operators, so you can perform the comparison using == just as you would expect:

if (string == "add") { ... }

When used properly, operator overloading is an excellent C++ feature.

How to delete an instantiated object Python?

What do you mean by delete? In Python, removing a reference (or a name) can be done with the del keyword, but if there are other names to the same object that object will not be deleted.

--> test = 3
--> print(test)
3
--> del test
--> print(test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined

compared to:

--> test = 5
--> other is test  # check that both name refer to the exact same object
True
--> del test       # gets rid of test, but the object is still referenced by other
--> print(other)
5

Errors in SQL Server while importing CSV file despite varchar(MAX) being used for each column

This answer may not apply universally, but it fixed the occurrence of this error I was encountering when importing a small text file. The flat file provider was importing based on fixed 50-character text columns in the source, which was incorrect. No amount of remapping the destination columns affected the issue.

To solve the issue, in the "Choose a Data Source" for the flat-file provider, after selecting the file, a "Suggest Types.." button appears beneath the input column list. After hitting this button, even if no changes were made to the enusing dialog, the Flat File provider then re-queried the source .csv file and then correctly determined the lengths of the fields in the source file.

Once this was done, the import proceeded with no further issues.

Check if URL has certain string with PHP

You can try an .htaccess method similar to the concept of how wordpress works.

Reference: http://monkeytooth.net/2010/12/htaccess-php-how-to-wordpress-slugs/

But I'm not sure if thats what your looking for exactly per say..

How can I download a specific Maven artifact in one command line?

You could use the maven dependency plugin which has a nice dependency:get goal since version 2.1. No need for a pom, everything happens on the command line.

To make sure to find the dependency:get goal, you need to explicitly tell maven to use the version 2.1, i.e. you need to use the fully qualified name of the plugin, including the version:

mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get \
    -DrepoUrl=url \
    -Dartifact=groupId:artifactId:version

UPDATE: With older versions of Maven (prior to 2.1), it is possible to run dependency:get normally (without using the fully qualified name and version) by forcing your copy of maven to use a given version of a plugin.

This can be done as follows:

1. Add the following line within the <settings> element of your ~/.m2/settings.xml file:

<usePluginRegistry>true</usePluginRegistry>

2. Add the file ~/.m2/plugin-registry.xml with the following contents:

<?xml version="1.0" encoding="UTF-8"?>
<pluginRegistry xsi:schemaLocation="http://maven.apache.org/PLUGIN_REGISTRY/1.0.0 http://maven.apache.org/xsd/plugin-registry-1.0.0.xsd"
xmlns="http://maven.apache.org/PLUGIN_REGISTRY/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-dependency-plugin</artifactId>
      <useVersion>2.1</useVersion>
      <rejectedVersions/>
    </plugin>
  </plugins>
</pluginRegistry>

But this doesn't seem to work anymore with maven 2.1/2.2. Actually, according to the Introduction to the Plugin Registry, features of the plugin-registry.xml have been redesigned (for portability) and the plugin registry is currently in a semi-dormant state within Maven 2. So I think we have to use the long name for now (when using the plugin without a pom, which is the idea behind dependency:get).

Moment JS start and end of given month

const dates = getDatesFromDateRange("2014-05-02", "2018-05-12", "YYYY/MM/DD", 1);           
console.log(dates);
// you get the whole from-to date ranges as per parameters
var onlyStartDates = dates.map(dateObj => dateObj["to"]);
console.log(onlyStartDates);
// moreover, if you want only from dates then you can grab by "map" function

function getDatesFromDateRange( startDate, endDate, format, counter ) {
    startDate = moment(startDate, format);
    endDate = moment(endDate, format);

    let dates = [];
    let fromDate = startDate.clone();
    let toDate = fromDate.clone().add(counter, "month").startOf("month").add(-1, "day");
    do {
        dates.push({
            "from": fromDate.format(format),
            "to": ( toDate < endDate ) ? toDate.format(format) : endDate.format(format)
        });
        fromDate = moment(toDate, format).add(1, "day").clone();
        toDate = fromDate.clone().add(counter, "month").startOf("month").add(-1, "day");
    } while ( fromDate < endDate );
    return dates;
}

Please note, .clone() is essential in momentjs else it'll override the value. It seems in your case.

It's more generic, to get bunch of dates that fall between dates.

Script parameters in Bash

I needed to make sure that my scripts are entirely portable between various machines, shells and even cygwin versions. Further, my colleagues who were the ones I had to write the scripts for, are programmers, so I ended up using this:

for ((i=1;i<=$#;i++)); 
do

    if [ ${!i} = "-s" ] 
    then ((i++)) 
        var1=${!i};

    elif [ ${!i} = "-log" ];
    then ((i++)) 
        logFile=${!i};  

    elif [ ${!i} = "-x" ];
    then ((i++)) 
        var2=${!i};    

    elif [ ${!i} = "-p" ]; 
    then ((i++)) 
        var3=${!i};

    elif [ ${!i} = "-b" ];
    then ((i++)) 
        var4=${!i};

    elif [ ${!i} = "-l" ];
    then ((i++)) 
        var5=${!i}; 

    elif [ ${!i} = "-a" ];
    then ((i++)) 
        var6=${!i};
    fi

done;

Rationale: I included a launcher.sh script as well, since the whole operation had several steps which were quasi independent on each other (I'm saying "quasi", because even though each script could be run on its own, they were usually all run together), and in two days I found out, that about half of my colleagues, being programmers and all, were too good to be using the launcher file, follow the "usage", or read the HELP which was displayed every time they did something wrong and they were making a mess of the whole thing, running scripts with arguments in the wrong order and complaining that the scripts didn't work properly. Being the choleric I am I decided to overhaul all my scripts to make sure that they are colleague-proof. The code segment above was the first thing.

How to list only files and not directories of a directory Bash?

find files: ls -l /home | grep "^-" | tr -s ' ' | cut -d ' ' -f 9

find directories: ls -l /home | grep "^d" | tr -s ' ' | cut -d ' ' -f 9

find links: ls -l /home | grep "^l" | tr -s ' ' | cut -d ' ' -f 9

tr -s ' ' turns the output into a space-delimited file the cut command says the delimiter is a space, and return the 9th field (always the filename/directory name/linkname).

I use this all the time!

Remove certain characters from a string

You can use Replace function as;

REPLACE ('Your String with cityname here', 'cityname', 'xyz')
--Results
'Your String with xyz here'

If you apply this to a table column where stringColumnName, cityName both are columns of YourTable

SELECT REPLACE(stringColumnName, cityName, '')
FROM YourTable

Or if you want to remove 'cityName' string from out put of a column then

SELECT REPLACE(stringColumnName, 'cityName', '')
FROM yourTable

EDIT: Since you have given more details now, REPLACE function is not the best method to sort your problem. Following is another way of doing it. Also @MartinSmith has given a good answer. Now you have the choice to select again.

SELECT RIGHT (O.Ort, LEN(O.Ort) - LEN(C.CityName)-1) As WithoutCityName
FROM   tblOrtsteileGeo O
       JOIN dbo.Cities C
         ON C.foo = O.foo
WHERE  O.GKZ = '06440004'

Unit test naming best practices

See: http://googletesting.blogspot.com/2007/02/tott-naming-unit-tests-responsibly.html

For test method names, I personally find using verbose and self-documented names very useful (alongside Javadoc comments that further explain what the test is doing).

Extract time from moment js object

Use format method with a specific pattern to extract the time. Working example

_x000D_
_x000D_
var myDate = "2017-08-30T14:24:03";_x000D_
console.log(moment(myDate).format("HH:mm")); // 24 hour format_x000D_
console.log(moment(myDate).format("hh:mm a")); // use 'A' for uppercase AM/PM_x000D_
console.log(moment(myDate).format("hh:mm:ss A")); // with milliseconds
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
_x000D_
_x000D_

Check if list contains element that contains a string and get that element

To keep it simple use this;

foreach(string item in myList)//Iterate through each item.
{
 if(item.Contains("Search Term")//True if the item contains search pattern.
 {
   return item;//Return the matched item.
 }
}

Alternatively,to do this with for loop,use this;

    for (int iterator = 0; iterator < myList.Count; iterator++)
    {
        if (myList[iterator].Contains("String Pattern"))
        {
            return myList[iterator];
        }
    }

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

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

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

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

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

and css classes:

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

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

Protecting cells in Excel but allow these to be modified by VBA script

I selected the cells I wanted locked out in sheet1 and place the suggested code in the open_workbook() function and worked like a charm.

ThisWorkbook.Worksheets("Sheet1").Protect Password:="Password", _
UserInterfaceOnly:=True

Chrome desktop notification example

<!DOCTYPE html>

<html>

<head>
<title>Hello!</title>
<script>
function notify(){

if (Notification.permission !== "granted") {
Notification.requestPermission();
}
 else{
var notification = new Notification('hello', {
  body: "Hey there!",
});
notification.onclick = function () {
  window.open("http://google.com");
};
}
}
</script>
</head>

<body>
<button onclick="notify()">Notify</button>
</body>

Use jQuery to get the file input's selected filename without the path

var filename=location.href.substr(location.href.lastIndexOf("/")+1);
alert(filename);

Using Javascript: How to create a 'Go Back' link that takes the user to a link if there's no history for the tab or window?

Added a new answer to display the code formatted:

The thing is that you were checking for document.referer, because you were in ff it was returning always true, then it was navigating to http://mysite.com. Try the following:

function backAway(){
    if (document.referrer) {
        //firefox, chrome, etc..
        i = 0;
    } else {
        // under ie
        i = 1;
    }
    if (history.length>i)
    {
        // there are items in history property
        history.back();
    } else {
        window.location = 'http://www.mysite.com/';
    }
    return false;
}

How can you use php in a javascript function

In the above given code

assign the php value to javascript variable.

<html>
<?php
 $num = 1;
 echo $num;
?>
  <input type = "button" name = "lol" value = "Click to increment" onclick = "Inc()">
  <br>
  <script>
   var numeric = <?php echo $num; ?>"; //assigns value of the $num to javascript var             numeric 
  function Inc()
   {
     numeric = eVal(numeric) + 1;
     alert("Increamented value: "+numeric);
   }
  </script>
</html>

One thing in combination of PHP and Javsacript is you can not assign javascript value to PHP value. You can assign PHP value to javascript variable.

Why use Redux over Facebook Flux?

In Quora, somebody says:

First of all, it is totally possible to write apps with React without Flux.

Also this visual diagram which I've created to show a quick view of both, probably a quick answer for the people who don't want to read the whole explanation: Flux vs Redux

But if you still interested knowing more, read on.

I believe you should start with pure React, then learn Redux and Flux. After you will have some REAL experience with React, you will see whether Redux is helpful for you or not.

Maybe you will feel that Redux is exactly for your app and maybe you will find out, that Redux is trying to solve a problem you are not really experiencing.

If you start directly with Redux, you may end up with over-engineered code, code harder to maintain and with even more bugs and than without Redux.

From Redux docs:

Motivation
As the requirements for JavaScript single-page applications have become increasingly complicated, our code must manage more state than ever before. This state can include server responses and cached data, as well as locally created data that has not yet been persisted to the server. UI state is also increasing in complexity, as we need to manage active routes, selected tabs, spinners, pagination controls, and so on.

Managing this ever-changing state is hard. If a model can update another model, then a view can update a model, which updates another model, and this, in turn, might cause another view to update. At some point, you no longer understand what happens in your app as you have lost control over the when, why, and how of its state. When a system is opaque and non-deterministic, it's hard to reproduce bugs or add new features.

As if this wasn't bad enough, consider the new requirements becoming common in front-end product development. As developers, we are expected to handle optimistic updates, server-side rendering, fetching data before performing route transitions, and so on. We find ourselves trying to manage a complexity that we have never had to deal with before, and we inevitably ask the question: Is it time to give up? The answer is No.

This complexity is difficult to handle as we're mixing two concepts that are very hard for the human mind to reason about: mutation and asynchronicity. I call them Mentos and Coke. Both can be great when separated, but together they create a mess. Libraries like React attempt to solve this problem in the view layer by removing both asynchrony and direct DOM manipulation. However, managing the state of your data is left up to you. This is where Redux comes in.

Following in the footsteps of Flux, CQRS, and Event Sourcing, Redux attempts to make state mutations predictable by imposing certain restrictions on how and when updates can happen. These restrictions are reflected in the three principles of Redux.

Also from Redux docs:

Core Concepts
Redux itself is very simple.

Imagine your app's state is described as a plain object. For example, the state of a todo app might look like this:

{
  todos: [{
    text: 'Eat food',
    completed: true
  }, {
    text: 'Exercise',
    completed: false
  }],
  visibilityFilter: 'SHOW_COMPLETED'
}

This object is like a "model" except that there are no setters. This is so that different parts of the code can’t change the state arbitrarily, causing hard-to-reproduce bugs.

To change something in the state, you need to dispatch an action. An action is a plain JavaScript object (notice how we don't introduce any magic?) that describes what happened. Here are a few example actions:

{ type: 'ADD_TODO', text: 'Go to swimming pool' }
{ type: 'TOGGLE_TODO', index: 1 }
{ type: 'SET_VISIBILITY_FILTER', filter: 'SHOW_ALL' }

Enforcing that every change is described as an action lets us have a clear understanding of what’s going on in the app. If something changed, we know why it changed. Actions are like breadcrumbs of what has happened. Finally, to tie state and actions together, we write a function called a reducer. Again, nothing magic about it — it's just a function that takes state and action as arguments, and returns the next state of the app. It would be hard to write such a function for a big app, so we write smaller functions managing parts of the state:

function visibilityFilter(state = 'SHOW_ALL', action) {
  if (action.type === 'SET_VISIBILITY_FILTER') {
    return action.filter;
  } else {
    return state;
  }
}

function todos(state = [], action) {
  switch (action.type) {
  case 'ADD_TODO':
    return state.concat([{ text: action.text, completed: false }]);
  case 'TOGGLE_TODO':
    return state.map((todo, index) =>
      action.index === index ?
        { text: todo.text, completed: !todo.completed } :
        todo
   )
  default:
    return state;
  }
}

And we write another reducer that manages the complete state of our app by calling those two reducers for the corresponding state keys:

function todoApp(state = {}, action) {
  return {
    todos: todos(state.todos, action),
    visibilityFilter: visibilityFilter(state.visibilityFilter, action)
  };
}

This is basically the whole idea of Redux. Note that we haven't used any Redux APIs. It comes with a few utilities to facilitate this pattern, but the main idea is that you describe how your state is updated over time in response to action objects, and 90% of the code you write is just plain JavaScript, with no use of Redux itself, its APIs, or any magic.

Sending credentials with cross-domain posts?

In jQuery 3 and perhaps earlier versions, the following simpler config also works for individual requests:

$.ajax(
        'https://foo.bar.com,
        {
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            success: successFunc
        }
    );

The full error I was getting in Firefox Dev Tools -> Network tab (in the Security tab for an individual request) was:

An error occurred during a connection to foo.bar.com.SSL peer was unable to negotiate an acceptable set of security parameters.Error code: SSL_ERROR_HANDSHAKE_FAILURE_ALERT

Best way to check if a drop down list contains a value?

What about this:

ListItem match = ddlCustomerNumber.Items.FindByText(
    GetCustomerNumberCookie().ToString());
if (match == null)
    ddlCustomerNumber.SelectedIndex = 0;
//else
//    match.Selected = true; // you'll probably select that cookie value

Getting attributes of a class

two function:

def get_class_attr(Cls) -> []:
    import re
    return [a for a, v in Cls.__dict__.items()
              if not re.match('<function.*?>', str(v))
              and not (a.startswith('__') and a.endswith('__'))]

def get_class_attr_val(cls):
    attr = get_class_attr(type(cls))
    attr_dict = {}
    for a in attr:
        attr_dict[a] = getattr(cls, a)
    return attr_dict

use:

>>> class MyClass:
    a = "12"
    b = "34"
    def myfunc(self):
        return self.a

>>> m = MyClass()
>>> get_class_attr_val(m)
{'a': '12', 'b': '34'}

Can anyone confirm that phpMyAdmin AllowNoPassword works with MySQL databases?

I tested the statement:

$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true; 

It did not work out for me.

Instead

$cfg['Servers'][$i]['AllowNoPassword'] = true; 

worked.

Thanks!

Is there a better way to compare dictionary values

Not sure if this helps but in my app I had to check if a dictionary has changed.

Doing this will not work since basically it's still the same object:

val={'A':1,'B':2}
old_val=val

val['A']=10
if old_val != val:
  print('changed')

Using copy/deepcopy works:

import copy
val={'A':1,'B':2}
old_val=copy.deepcopy(val)

val['A']=10
if old_val != val:
  print('changed')

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

    public RoundedImageView(Context context) {
        super(context);
    }

    public RoundedImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

How do I print out the contents of a vector?

In C++11 you can now use a range-based for loop:

for (auto const& c : path)
    std::cout << c << ' ';

How to get a DOM Element from a JQuery Selector

I needed to get the element as a string.

jQuery("#bob").get(0).outerHTML;

Which will give you something like:

<input type="text" id="bob" value="hello world" />

...as a string rather than a DOM element.

What is the purpose of nameof?

The purpose of the nameof operator is to provide the source name of the artifacts.

Usually the source name is the same name as the metadata name:

public void M(string p)
{
    if (p == null)
    {
        throw new ArgumentNullException(nameof(p));
    }
    ...
}

public int P
{
    get
    {
        return p;
    }
    set
    {
        p = value;
        NotifyPropertyChanged(nameof(P));
    }
}

But this may not always be the case:

using i = System.Int32;
...
Console.WriteLine(nameof(i)); // prints "i"

Or:

public static string Extension<T>(this T t)
{
    return nameof(T); returns "T"
}

One use I've been giving to it is for naming resources:

[Display(
    ResourceType = typeof(Resources),
    Name = nameof(Resources.Title_Name),
    ShortName = nameof(Resources.Title_ShortName),
    Description = nameof(Resources.Title_Description),
    Prompt = nameof(Resources.Title_Prompt))]

The fact is that, in this case, I didn't even need the generated properties to access the resources, but now I have a compile time check that the resources exist.

assembly to compare two numbers

The basic technique (on most modern systems) is to subtract the two numbers and then to check the sign bit of the result, i.e. see if the result is greater than/equal to/less than zero. In the assembly code instead of getting the result directly (into a register), you normally just branch depending on the state:

; Compare r1 and r2
    CMP $r1, $r2
    JLT lessthan
greater_or_equal:
    ; print "r1 >= r2" somehow
    JMP l1
lessthan:
    ; print "r1 < r2" somehow
l1:

Laravel Eloquent ORM Transactions

You can do this:

DB::transaction(function() {
      //
});

Everything inside the Closure executes within a transaction. If an exception occurs it will rollback automatically.

What is the default text size on Android?

Default values in appcompat-v7

<dimen name="abc_text_size_body_1_material">14sp</dimen>
<dimen name="abc_text_size_body_2_material">14sp</dimen>
<dimen name="abc_text_size_button_material">14sp</dimen>
<dimen name="abc_text_size_caption_material">12sp</dimen>
<dimen name="abc_text_size_display_1_material">34sp</dimen>
<dimen name="abc_text_size_display_2_material">45sp</dimen>
<dimen name="abc_text_size_display_3_material">56sp</dimen>
<dimen name="abc_text_size_display_4_material">112sp</dimen>
<dimen name="abc_text_size_headline_material">24sp</dimen>
<dimen name="abc_text_size_large_material">22sp</dimen>
<dimen name="abc_text_size_medium_material">18sp</dimen>
<dimen name="abc_text_size_menu_material">16sp</dimen>
<dimen name="abc_text_size_small_material">14sp</dimen>
<dimen name="abc_text_size_subhead_material">16sp</dimen>
<dimen name="abc_text_size_subtitle_material_toolbar">16dp</dimen>
<dimen name="abc_text_size_title_material">20sp</dimen>
<dimen name="abc_text_size_title_material_toolbar">20dp</dimen>

How to use glOrtho() in OpenGL?

Minimal runnable example

glOrtho: 2D games, objects close and far appear the same size:

enter image description here

glFrustrum: more real-life like 3D, identical objects further away appear smaller:

enter image description here

main.c

#include <stdlib.h>

#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glut.h>

static int ortho = 0;

static void display(void) {
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();
    if (ortho) {
    } else {
        /* This only rotates and translates the world around to look like the camera moved. */
        gluLookAt(0.0, 0.0, -3.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);
    }
    glColor3f(1.0f, 1.0f, 1.0f);
    glutWireCube(2);
    glFlush();
}

static void reshape(int w, int h) {
    glViewport(0, 0, w, h);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    if (ortho) {
        glOrtho(-2.0, 2.0, -2.0, 2.0, -1.5, 1.5);
    } else {
        glFrustum(-1.0, 1.0, -1.0, 1.0, 1.5, 20.0);
    }
    glMatrixMode(GL_MODELVIEW);
}

int main(int argc, char** argv) {
    glutInit(&argc, argv);
    if (argc > 1) {
        ortho = 1;
    }
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(500, 500);
    glutInitWindowPosition(100, 100);
    glutCreateWindow(argv[0]);
    glClearColor(0.0, 0.0, 0.0, 0.0);
    glShadeModel(GL_FLAT);
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();
    return EXIT_SUCCESS;
}

GitHub upstream.

Compile:

gcc -ggdb3 -O0 -o main -std=c99 -Wall -Wextra -pedantic main.c -lGL -lGLU -lglut

Run with glOrtho:

./main 1

Run with glFrustrum:

./main

Tested on Ubuntu 18.10.

Schema

Ortho: camera is a plane, visible volume a rectangle:

enter image description here

Frustrum: camera is a point,visible volume a slice of a pyramid:

enter image description here

Image source.

Parameters

We are always looking from +z to -z with +y upwards:

glOrtho(left, right, bottom, top, near, far)
  • left: minimum x we see
  • right: maximum x we see
  • bottom: minimum y we see
  • top: maximum y we see
  • -near: minimum z we see. Yes, this is -1 times near. So a negative input means positive z.
  • -far: maximum z we see. Also negative.

Schema:

Image source.

How it works under the hood

In the end, OpenGL always "uses":

glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0);

If we use neither glOrtho nor glFrustrum, that is what we get.

glOrtho and glFrustrum are just linear transformations (AKA matrix multiplication) such that:

  • glOrtho: takes a given 3D rectangle into the default cube
  • glFrustrum: takes a given pyramid section into the default cube

This transformation is then applied to all vertexes. This is what I mean in 2D:

Image source.

The final step after transformation is simple:

  • remove any points outside of the cube (culling): just ensure that x, y and z are in [-1, +1]
  • ignore the z component and take only x and y, which now can be put into a 2D screen

With glOrtho, z is ignored, so you might as well always use 0.

One reason you might want to use z != 0 is to make sprites hide the background with the depth buffer.

Deprecation

glOrtho is deprecated as of OpenGL 4.5: the compatibility profile 12.1. "FIXED-FUNCTION VERTEX TRANSFORMATIONS" is in red.

So don't use it for production. In any case, understanding it is a good way to get some OpenGL insight.

Modern OpenGL 4 programs calculate the transformation matrix (which is small) on the CPU, and then give the matrix and all points to be transformed to OpenGL, which can do the thousands of matrix multiplications for different points really fast in parallel.

Manually written vertex shaders then do the multiplication explicitly, usually with the convenient vector data types of the OpenGL Shading Language.

Since you write the shader explicitly, this allows you to tweak the algorithm to your needs. Such flexibility is a major feature of more modern GPUs, which unlike the old ones that did a fixed algorithm with some input parameters, can now do arbitrary computations. See also: https://stackoverflow.com/a/36211337/895245

With an explicit GLfloat transform[] it would look something like this:

glfw_transform.c

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

#define GLEW_STATIC
#include <GL/glew.h>

#include <GLFW/glfw3.h>

static const GLuint WIDTH = 800;
static const GLuint HEIGHT = 600;
/* ourColor is passed on to the fragment shader. */
static const GLchar* vertex_shader_source =
    "#version 330 core\n"
    "layout (location = 0) in vec3 position;\n"
    "layout (location = 1) in vec3 color;\n"
    "out vec3 ourColor;\n"
    "uniform mat4 transform;\n"
    "void main() {\n"
    "    gl_Position = transform * vec4(position, 1.0f);\n"
    "    ourColor = color;\n"
    "}\n";
static const GLchar* fragment_shader_source =
    "#version 330 core\n"
    "in vec3 ourColor;\n"
    "out vec4 color;\n"
    "void main() {\n"
    "    color = vec4(ourColor, 1.0f);\n"
    "}\n";
static GLfloat vertices[] = {
/*   Positions          Colors */
     0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f,
    -0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f,
     0.0f,  0.5f, 0.0f, 0.0f, 0.0f, 1.0f
};

/* Build and compile shader program, return its ID. */
GLuint common_get_shader_program(
    const char *vertex_shader_source,
    const char *fragment_shader_source
) {
    GLchar *log = NULL;
    GLint log_length, success;
    GLuint fragment_shader, program, vertex_shader;

    /* Vertex shader */
    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex_shader, 1, &vertex_shader_source, NULL);
    glCompileShader(vertex_shader);
    glGetShaderiv(vertex_shader, GL_COMPILE_STATUS, &success);
    glGetShaderiv(vertex_shader, GL_INFO_LOG_LENGTH, &log_length);
    log = malloc(log_length);
    if (log_length > 0) {
        glGetShaderInfoLog(vertex_shader, log_length, NULL, log);
        printf("vertex shader log:\n\n%s\n", log);
    }
    if (!success) {
        printf("vertex shader compile error\n");
        exit(EXIT_FAILURE);
    }

    /* Fragment shader */
    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment_shader, 1, &fragment_shader_source, NULL);
    glCompileShader(fragment_shader);
    glGetShaderiv(fragment_shader, GL_COMPILE_STATUS, &success);
    glGetShaderiv(fragment_shader, GL_INFO_LOG_LENGTH, &log_length);
    if (log_length > 0) {
        log = realloc(log, log_length);
        glGetShaderInfoLog(fragment_shader, log_length, NULL, log);
        printf("fragment shader log:\n\n%s\n", log);
    }
    if (!success) {
        printf("fragment shader compile error\n");
        exit(EXIT_FAILURE);
    }

    /* Link shaders */
    program = glCreateProgram();
    glAttachShader(program, vertex_shader);
    glAttachShader(program, fragment_shader);
    glLinkProgram(program);
    glGetProgramiv(program, GL_LINK_STATUS, &success);
    glGetProgramiv(program, GL_INFO_LOG_LENGTH, &log_length);
    if (log_length > 0) {
        log = realloc(log, log_length);
        glGetProgramInfoLog(program, log_length, NULL, log);
        printf("shader link log:\n\n%s\n", log);
    }
    if (!success) {
        printf("shader link error");
        exit(EXIT_FAILURE);
    }

    /* Cleanup. */
    free(log);
    glDeleteShader(vertex_shader);
    glDeleteShader(fragment_shader);
    return program;
}

int main(void) {
    GLint shader_program;
    GLint transform_location;
    GLuint vbo;
    GLuint vao;
    GLFWwindow* window;
    double time;

    glfwInit();
    window = glfwCreateWindow(WIDTH, HEIGHT, __FILE__, NULL, NULL);
    glfwMakeContextCurrent(window);
    glewExperimental = GL_TRUE;
    glewInit();
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
    glViewport(0, 0, WIDTH, HEIGHT);

    shader_program = common_get_shader_program(vertex_shader_source, fragment_shader_source);

    glGenVertexArrays(1, &vao);
    glGenBuffers(1, &vbo);
    glBindVertexArray(vao);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    /* Position attribute */
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    /* Color attribute */
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(1);
    glBindVertexArray(0);

    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(shader_program);
        transform_location = glGetUniformLocation(shader_program, "transform");
        /* THIS is just a dummy transform. */
        GLfloat transform[] = {
            0.0f, 0.0f, 0.0f, 0.0f,
            0.0f, 0.0f, 0.0f, 0.0f,
            0.0f, 0.0f, 1.0f, 0.0f,
            0.0f, 0.0f, 0.0f, 1.0f,
        };
        time = glfwGetTime();
        transform[0] = 2.0f * sin(time);
        transform[5] = 2.0f * cos(time);
        glUniformMatrix4fv(transform_location, 1, GL_FALSE, transform);

        glBindVertexArray(vao);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        glBindVertexArray(0);
        glfwSwapBuffers(window);
    }
    glDeleteVertexArrays(1, &vao);
    glDeleteBuffers(1, &vbo);
    glfwTerminate();
    return EXIT_SUCCESS;
}

GitHub upstream.

Compile and run:

gcc -ggdb3 -O0 -o glfw_transform.out -std=c99 -Wall -Wextra -pedantic glfw_transform.c -lGL -lGLU -lglut -lGLEW -lglfw -lm
./glfw_transform.out

Output:

enter image description here

The matrix for glOrtho is really simple, composed only of scaling and translation:

scalex, 0,      0,      translatex,
0,      scaley, 0,      translatey,
0,      0,      scalez, translatez,
0,      0,      0,      1

as mentioned in the OpenGL 2 docs.

The glFrustum matrix is not too hard to calculate by hand either, but starts getting annoying. Note how frustum cannot be made up with only scaling and translations like glOrtho, more info at: https://gamedev.stackexchange.com/a/118848/25171

The GLM OpenGL C++ math library is a popular choice for calculating such matrices. http://glm.g-truc.net/0.9.2/api/a00245.html documents both an ortho and frustum operations.

How to set a JVM TimeZone Properly

In win7, if you want to set the correct timezone as a parameter in JRE, you have to edit the file deployment.properties stored in path c:\users\%username%\appdata\locallow\sun\java\deployment adding the string deployment.javaws.jre.1.args=-Duser.timezone\=my_time_zone

Iterator Loop vs index loop

Iterators make your code more generic.
Every standard library container provides an iterator hence if you change your container class in future the loop wont be affected.

AngularJS: No "Access-Control-Allow-Origin" header is present on the requested resource

This is a server side issue. You don't need to add any headers in angular for cors. You need to add header on the server side:

Access-Control-Allow-Headers: Content-Type
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Origin: *

First two answers here: How to enable CORS in AngularJs

What is the reason for having '//' in Python?

To complement Alex's response, I would add that starting from Python 2.2.0a2, from __future__ import division is a convenient alternative to using lots of float(…)/…. All divisions perform float divisions, except those with //. This works with all versions from 2.2.0a2 on.

PHP - Debugging Curl

You can enable the CURLOPT_VERBOSE option:

curl_setopt($curlhandle, CURLOPT_VERBOSE, true);

When CURLOPT_VERBOSE is set, output is written to STDERR or the file specified using CURLOPT_STDERR. The output is very informative.

You can also use tcpdump or wireshark to watch the network traffic.

SOAP request to WebService with java

I have come across other similar question here. Both of above answers are perfect, but here trying to add additional information for someone looking for SOAP1.1, and not SOAP1.2.

Just change one line code provided by @acdcjunior, use SOAPMessageFactory1_1Impl implementation, it will change namespace to xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/", which is SOAP1.1 implementation.

Change callSoapWebService method first line to following.

SOAPMessage soapMessage = SOAPMessageFactory1_1Impl.newInstance().createMessage();

I hope it will be helpful to others.

What is the easiest way to get the current day of the week in Android?

Using both method you find easy if you wont last seven days you use (currentdaynumber+7-1)%7,(currentdaynumber+7-2)%7.....upto 6

public static String getDayName(int day){
    switch(day){
        case 0:
            return "Sunday";
        case 1:
            return "Monday";
        case 2:
            return "Tuesday";
        case 3:
            return "Wednesday";
        case 4:
            return "Thursday";
        case 5:
            return  "Friday";
        case 6:
            return "Saturday";
    }

    return "Worng Day";
}
public static String getCurrentDay(){
    SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE", Locale.US);
    Calendar calendar = Calendar.getInstance();
    return dayFormat.format(calendar.getTime());

}

How do I rename both a Git local and remote branch name?

Attaching a Simple Snippet for renaming your current branch (local and on origin):

git branch -m <oldBranchName> <newBranchName>
git push origin :<oldBranchName>
git push --set-upstream origin <newBranchName>

Explanation from git docs:

git branch -m or -M option, will be renamed to . If had a corresponding reflog, it is renamed to match , and a reflog entry is created to remember the branch renaming. If exists, -M must be used to force the rename to happen.

The special refspec : (or +: to allow non-fast-forward updates) directs Git to push "matching" branches: for every branch that exists on the local side, the remote side is updated if a branch of the same name already exists on the remote side.

--set-upstream Set up 's tracking information so is considered 's upstream branch. If no is specified, then it defaults to the current branch.

define a List like List<int,string>?

Since your example uses a generic List, I assume you don't need an index or unique constraint on your data. A List may contain duplicate values. If you want to insure a unique key, consider using a Dictionary<TKey, TValue>().

var list = new List<Tuple<int,string>>();

list.Add(Tuple.Create(1, "Andy"));
list.Add(Tuple.Create(1, "John"));
list.Add(Tuple.Create(3, "Sally"));

foreach (var item in list)
{
    Console.WriteLine(item.Item1.ToString());
    Console.WriteLine(item.Item2);
}

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

This happened to me on VS2013(Update 5)/ASP.NET 4.5, under project type "Web Application" that includes MVC and Web API 2. Error happened right after creating the project and before adding any code. Adding the following configuration fix it for me. After resolving "System.Web.Helpers" issue two more similar errors surfaced for "System.Web.Mvc" and "System.Web.WebPages".

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.2.3.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>

/bin/sh: apt-get: not found

If you are looking inside dockerfile while creating image, add this line:

RUN apk add --update yourPackageName

What values can I pass to the event attribute of the f:ajax tag?

The event attribute of <f:ajax> can hold at least all supported DOM events of the HTML element which is been generated by the JSF component in question. An easy way to find them all out is to check all on* attribues of the JSF input component of interest in the JSF tag library documentation and then remove the "on" prefix. For example, the <h:inputText> component which renders <input type="text"> lists the following on* attributes (of which I've already removed the "on" prefix so that it ultimately becomes the DOM event type name):

  • blur
  • change
  • click
  • dblclick
  • focus
  • keydown
  • keypress
  • keyup
  • mousedown
  • mousemove
  • mouseout
  • mouseover
  • mouseup
  • select

Additionally, JSF has two more special event names for EditableValueHolder and ActionSource components, the real HTML DOM event being rendered depends on the component type:

  • valueChange (will render as change on text/select inputs and as click on radio/checkbox inputs)
  • action (will render as click on command links/buttons)

The above two are the default events for the components in question.

Some JSF component libraries have additional customized event names which are generally more specialized kinds of valueChange or action events, such as PrimeFaces <p:ajax> which supports among others tabChange, itemSelect, itemUnselect, dateSelect, page, sort, filter, close, etc depending on the parent <p:xxx> component. You can find them all in the "Ajax Behavior Events" subsection of each component's chapter in PrimeFaces Users Guide.

Fixed position but relative to container

The answer is yes, as long as you don't set left: 0 or right: 0 after you set the div position to fixed.

http://jsfiddle.net/T2PL5/85/

Checkout the sidebar div. It is fixed, but related to the parent, not to the window view point.

_x000D_
_x000D_
body {
  background: #ccc;
}

.wrapper {
  margin: 0 auto;
  height: 1400px;
  width: 650px;
  background: green;
}

.sidebar {
  background-color: #ddd;
  float: left;
  width: 300px;
  height: 100px;
  position: fixed;
}

.main {
  float: right;
  background-color: yellow;
  width: 300px;
  height: 1400px;
}
_x000D_
<div class="wrapper">wrapper
  <div class="sidebar">sidebar</div>
  <div class="main">main</div>
</div>
_x000D_
_x000D_
_x000D_

Transpose a data frame

Take advantage of as.matrix:

# keep the first column 
names <-  df.aree[,1]

# Transpose everything other than the first column
df.aree.T <- as.data.frame(as.matrix(t(df.aree[,-1])))

# Assign first column as the column names of the transposed dataframe
colnames(df.aree.T) <- names

jQuery check if an input is type checkbox?

$("#myinput").attr('type') == 'checkbox'

Formatting NSDate into particular styles for both year, month, day, and hour, minute, seconds

For swift

var dateString:String = "2014-05-20";
var dateFmt = NSDateFormatter()
// the format you want
dateFmt.dateFormat = "yyyy-MM-dd"
var date1:NSDate = dateFmt.dateFromString(dateString)!;

how to save and read array of array in NSUserdefaults in swift?

Just to add on to what @Zaph says in the comments.

I have the same problem as you, as to know, the array of String is not saved. Even though Apple bridges types such as String and NSString, I wasn't able to save an array of [String] neither of [AnyObject].

However an array of [NSString] works for me.

So your code could look like that :

var key = "keySave"

var array1: [NSString] = [NSString]()
array1.append("value 1")
array1.append("value 2")

//save
var defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(array1, forKey: key)
defaults.synchronize()

//read
if let testArray : AnyObject? = defaults.objectForKey(key) {
    var readArray : [NSString] = testArray! as [NSString]
}

Note that I created an array of NSString and not a dictionary. I didn't check if it works with a dictionary, but probably you will have to define the things as [NSString : NSString] to have it working.

EDIT

Re-reading your question and your title, you are talking of array of array. I think that as long as you stay with NSString, an array of array will work. However, if you think my answer is irrelevant, just let me know in the comments and I will remove it.

How do you get/set media volume (not ringtone volume) in Android?

private AudioManager audio;

Inside onCreate:

audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

Override onKeyDown:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_UP:
        audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
        return true;
    default:
        return false;
    }
}

Why should I prefer to use member initialization lists?

Before the body of the constructor is run, all of the constructors for its parent class and then for its fields are invoked. By default, the no-argument constructors are invoked. Initialization lists allow you to choose which constructor is called and what arguments that constructor receives.

If you have a reference or a const field, or if one of the classes used does not have a default constructor, you must use an initialization list.

Java: Literal percent sign in printf statement

Escaped percent sign is double percent (%%):

System.out.printf("2 out of 10 is %d%%", 20);

Python functions call by reference

Python is neither pass-by-value nor pass-by-reference. It's more of "object references are passed by value" as described here:

  1. Here's why it's not pass-by-value. Because

    def append(list):
        list.append(1)
    
    list = [0]
    reassign(list)
    append(list)
    

returns [0,1] showing that some kind of reference was clearly passed as pass-by-value does not allow a function to alter the parent scope at all.

Looks like pass-by-reference then, hu? Nope.

  1. Here's why it's not pass-by-reference. Because

    def reassign(list):
      list = [0, 1]
    
    list = [0]
    reassign(list)
    print list
    

returns [0] showing that the original reference was destroyed when list was reassigned. pass-by-reference would have returned [0,1].

For more information look here:

If you want your function to not manipulate outside scope, you need to make a copy of the input parameters that creates a new object.

from copy import copy

def append(list):
  list2 = copy(list)
  list2.append(1)
  print list2

list = [0]
append(list)
print list

How do I tell matplotlib that I am done with a plot?

Just enter plt.hold(False) before the first plt.plot, and you can stick to your original code.

.htaccess not working apache

Go to /etc/apache2/apache2.conf

You have to edit that file (you should have root permission). Change directory text as bellow:

<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted

Now you have to restart apache.

service apache2 restart

Can't connect to local MySQL server through socket homebrew

  1. If you are able to see "mysql stopped" when you run below command;

    brew services list
    
  2. and if you are able to start mysql with below command;

    mysql server start
    

this means; mysql is able to start manually, but it doesn't start automatically when the operating system is started. Adding mysql to services will fix this problem. To do so, you can run below command;

brew services start mysql

After that, you may restart your operating system and try connecting to mysql to see if it started automatically. I did the same and stop receiving below error;

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)

I hope this helps.

How to save a dictionary to a file?

For a dictionary of strings such as the one you're dealing with, it could be done using only Python's built-in text processing capabilities.

(Note this wouldn't work if the values are something else.)

with open('members.txt') as file:
    mdict={}
    for line in file:
        a, b, c, d = line.strip().split(':')
        mdict[a] = b + ':' + c + ':' + d

a = input('ID: ')
if a not in mdict:
    print('ID {} not found'.format(a))
else:
    b, c, d = mdict[a].split(':')
    d = input('phone: ')
    mdict[a] = b + ':' + c + ':' + d  # update entry
    with open('members.txt', 'w') as file:  # rewrite file
        for id, values in mdict.items():
            file.write(':'.join([id] + values.split(':')) + '\n')

What is "loose coupling?" Please provide examples

It's a pretty general concept, so code examples are not going to give the whole picture.

One guy here at work said to me, "patterns are like fractals, you can see them when you zoom in really close, and when you zoom way out to the architecture level."

Reading the brief wikipedia page can give you a sense of this generalness:

http://en.wikipedia.org/wiki/Loose_coupling

As far as a specific code example...

Here's one loose coupling I've worked with recently, from the Microsoft.Practices.CompositeUI stuff.

    [ServiceDependency]
    public ICustomizableGridService CustomizableGridService
    {
        protected get { return _customizableGridService; }
        set { _customizableGridService = value; }
    }

This code is declaring that this class has a dependency on a CustomizableGridService. Instead of just directly referencing the exact implementation of the service, it simply states that it requires SOME implementation of that service. Then at runtime, the system resolves that dependency.

If that's not clear, you can read a more detailed explanation here:

http://en.wikipedia.org/wiki/Dependency_injection

Imagine that ABCCustomizableGridService is the imlpementation I intend to hook up here.

If I choose to, I can yank that out and replace it with XYZCustomizableGridService, or StubCustomizableGridService with no change at all to the class with this dependency.

If I had directly referenced ABCCustomizableGridService, then I would need to make changes to that/those reference/s in order to swap in another service implementation.

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

// in the HTML code I used some razor
@Html.Hidden("RedirectTo", Url.Action("Action", "Controller"));

// now down in the script I do this
<script type="text/javascript">

var url = $("#RedirectTo").val();

$(document).ready(function () {
    $.ajax({
        dataType: 'json',
        type: 'POST',
        url: '/Controller/Action',
        success: function (result) {
            if (result.UserFriendlyErrMsg === 'Some Message') {
                // display a prompt
                alert("Message: " + result.UserFriendlyErrMsg);
                // redirect us to the new page
                location.href = url;
            }
            $('#friendlyMsg').html(result.UserFriendlyErrMsg);
        }
    });
</script>

There can be only one auto column

CREATE TABLE book (
   id INT AUTO_INCREMENT primary key NOT NULL,
   accepted_terms BIT(1) NOT NULL,
   accepted_privacy BIT(1) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1

What's the best way to add a full screen background image in React Native

I solved my background image issue using this code.

import React from 'react';
import { StyleSheet, Text, View,Alert,ImageBackground } from 'react-native';

import { TextInput,Button,IconButton,Colors,Avatar } from 'react-native-paper';

class SignInScreen extends React.Component {

    state = {
       UsernameOrEmail  : '',
       Password : '',
     }
    render() {
      return (
             <ImageBackground  source={require('../assets/icons/background3.jpg')} style {styles.backgroundImage}>
              <Text>React Native App</Text>
            </ImageBackground>
          );
    }
  }


    export default SignInScreen;

    const styles = StyleSheet.create({
     backgroundImage: {
      flex: 1,
      resizeMode: 'cover', // or 'stretch'
     }
   });

How do I create a copy of an object in PHP?

In PHP 5+ objects are passed by reference. In PHP 4 they are passed by value (that's why it had runtime pass by reference, which became deprecated).

You can use the 'clone' operator in PHP5 to copy objects:

$objectB = clone $objectA;

Also, it's just objects that are passed by reference, not everything as you've said in your question...

how to refresh Select2 dropdown menu after ajax loading different content?

Initialize again select2 by new id or class like below

when the page load

$(".mynames").select2();

call again when came by ajax after success ajax function

$(".names").select2();

MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

In addition to the above answers ; After executing the below command

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'

If you get an error as :

[ERROR] Column count of mysql.user is wrong. Expected 42, found 44. The table is probably corrupted

Then try in the cmd as admin; set the path to MySQL server bin folder in the cmd

set path=%PATH%;D:\xampp\mysql\bin;

and then run the command :

mysql_upgrade --force -uroot -p

This should update the server and the system tables.

Then you should be able to successfully run the below commands in a Query in the Workbench :

 ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password'    

then remember to execute the following command:

flush privileges;

After all these steps should be able to successfully connect to your MySQL database. Hope this helps...

Replace all occurrences of a String using StringBuilder?

java.util.regex.Pattern.matcher(CharSequence s) can use a StringBuilder as an argument so you can find and replace each occurence of your pattern using start() and end() without calling builder.toString()

#1273 - Unknown collation: 'utf8mb4_unicode_ci' cPanel

The easiest way to do is export your database to .sql, open it on Notepad++ and "Search and Replace" the utf8mb4_unicode_ci to utf8_unicode_ci and also replace utf8mb4 to utf8. Also don't forget to change the database collation to utf8_unicode_ci (Operations > Collation).

How to write loop in a Makefile?

THE major reason to use make IMHO is the -j flag. make -j5 will run 5 shell commands at once. This is good if you have 4 CPUs say, and a good test of any makefile.

Basically, you want make to see something like:

.PHONY: all
all: job1 job2 job3

.PHONY: job1
job1: ; ./a.out 1

.PHONY: job2
job2: ; ./a.out 2

.PHONY: job3
job3: ; ./a.out 3

This is -j friendly (a good sign). Can you spot the boiler-plate? We could write:

.PHONY: all job1 job2 job3
all: job1 job2 job3
job1 job2 job3: job%:
    ./a.out $*

for the same effect (yes, this is the same as the previous formulation as far as make is concerned, just a bit more compact).

A further bit of parameterisation so that you can specify a limit on the command-line (tedious as make does not have any good arithmetic macros, so I'll cheat here and use $(shell ...))

LAST := 1000
NUMBERS := $(shell seq 1 ${LAST})
JOBS := $(addprefix job,${NUMBERS})
.PHONY: all ${JOBS}
all: ${JOBS} ; echo "$@ success"
${JOBS}: job%: ; ./a.out $*

You run this with make -j5 LAST=550, with LAST defaulting to 1000.

How to get distinct results in hibernate with joins and row-based limiting (paging)?

NullPointerException in some cases! Without criteria.setProjection(Projections.distinct(Projections.property("id"))) all query goes well! This solution is bad!

Another way is use SQLQuery. In my case following code works fine:

List result = getSession().createSQLQuery(
"SELECT distinct u.id as usrId, b.currentBillingAccountType as oldUser_type,"
+ " r.accountTypeWhenRegister as newUser_type, count(r.accountTypeWhenRegister) as numOfRegUsers"
+ " FROM recommendations r, users u, billing_accounts b WHERE "
+ " r.user_fk = u.id and"
+ " b.user_fk = u.id and"
+ " r.activated = true and"
+ " r.audit_CD > :monthAgo and"
+ " r.bonusExceeded is null and"
+ " group by u.id, r.accountTypeWhenRegister")
.addScalar("usrId", Hibernate.LONG)
.addScalar("oldUser_type", Hibernate.INTEGER)
.addScalar("newUser_type", Hibernate.INTEGER)
.addScalar("numOfRegUsers", Hibernate.BIG_INTEGER)
.setParameter("monthAgo", monthAgo)
.setMaxResults(20)
.list();

Distinction is done in data base! In opposite to:

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

where distinction is done in memory, after load entities!

Changing selection in a select with the Chosen plugin

From the "Updating Chosen Dynamically" section in the docs: You need to trigger the 'chosen:updated' event on the field

$(document).ready(function() {

    $('select').chosen();

    $('button').click(function() {
        $('select').val(2);
        $('select').trigger("chosen:updated");
    });

});

NOTE: versions prior to 1.0 used the following:

$('select').trigger("liszt:updated");

error running apache after xampp install

www.example.com:443:0 server certificate does NOT include an ID which matches the server name

I was getting this error when trying to start Apache, there is no error with Apache. It's an dependency error on windows 8 - probably the same for 7. Just right click and run as Admin :)

If you're still getting an error check your Antivirus/Firewall is not blocking Xampp or port 443.

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

Wasted 4+ hours on this.

I have Visual Studio 2017 Enterprise, one of the projects has below error:

The builds tools for v120 (Platform Toolset = 'v120') cannot be found

To resolve above error, I tried to install all below:

However, none of the above worked.

Later, installed Visual Studio 2013 Ultimate, then all worked fine.

Looks like, the older Visual studio is a must to resolve this.

Hope it helps.

Bootstrap combining rows (rowspan)

Divs stack vertically by default, so there is no need for special handling of "rows" within a column.

_x000D_
_x000D_
div {_x000D_
  height:50px;_x000D_
}_x000D_
.short-div {_x000D_
  height:25px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<div class="container">_x000D_
  <h1>Responsive Bootstrap</h1>_x000D_
  <div class="row">_x000D_
    <div class="col-lg-5 col-md-5 col-sm-5 col-xs-5" style="background-color:red;">Span 5</div>_x000D_
    <div class="col-lg-3 col-md-3 col-sm-3 col-xs-3" style="background-color:blue">Span 3</div>_x000D_
    <div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="padding:0px">_x000D_
      <div class="short-div" style="background-color:green">Span 2</div>_x000D_
      <div class="short-div" style="background-color:purple">Span 2</div>_x000D_
    </div>_x000D_
    <div class="col-lg-2 col-md-2 col-sm-3 col-xs-2" style="background-color:yellow">Span 2</div>_x000D_
  </div>_x000D_
</div>_x000D_
<div class="container-fluid">_x000D_
  <div class="row-fluid">_x000D_
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6">_x000D_
      <div class="short-div" style="background-color:#999">Span 6</div>_x000D_
      <div class="short-div">Span 6</div>_x000D_
    </div>_x000D_
    <div class="col-lg-6 col-md-6 col-sm-6 col-xs-6" style="background-color:#ccc">Span 6</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's the fiddle.

How to detect a USB drive has been plugged in?

It is easy to check for removable devices. However, there's no guarantee that it is a USB device:

var drives = DriveInfo.GetDrives()
    .Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);

This will return a list of all removable devices that are currently accessible. More information:

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

What are these new categories of expressions?

The FCD (n3092) has an excellent description:

— An lvalue (so called, historically, because lvalues could appear on the left-hand side of an assignment expression) designates a function or an object. [ Example: If E is an expression of pointer type, then *E is an lvalue expression referring to the object or function to which E points. As another example, the result of calling a function whose return type is an lvalue reference is an lvalue. —end example ]

— An xvalue (an “eXpiring” value) also refers to an object, usually near the end of its lifetime (so that its resources may be moved, for example). An xvalue is the result of certain kinds of expressions involving rvalue references (8.3.2). [ Example: The result of calling a function whose return type is an rvalue reference is an xvalue. —end example ]

— A glvalue (“generalized” lvalue) is an lvalue or an xvalue.

— An rvalue (so called, historically, because rvalues could appear on the right-hand side of an assignment expressions) is an xvalue, a temporary object (12.2) or subobject thereof, or a value that is not associated with an object.

— A prvalue (“pure” rvalue) is an rvalue that is not an xvalue. [ Example: The result of calling a function whose return type is not a reference is a prvalue. The value of a literal such as 12, 7.3e5, or true is also a prvalue. —end example ]

Every expression belongs to exactly one of the fundamental classifications in this taxonomy: lvalue, xvalue, or prvalue. This property of an expression is called its value category. [ Note: The discussion of each built-in operator in Clause 5 indicates the category of the value it yields and the value categories of the operands it expects. For example, the built-in assignment operators expect that the left operand is an lvalue and that the right operand is a prvalue and yield an lvalue as the result. User-defined operators are functions, and the categories of values they expect and yield are determined by their parameter and return types. —end note

I suggest you read the entire section 3.10 Lvalues and rvalues though.

How do these new categories relate to the existing rvalue and lvalue categories?

Again:

Taxonomy

Are the rvalue and lvalue categories in C++0x the same as they are in C++03?

The semantics of rvalues has evolved particularly with the introduction of move semantics.

Why are these new categories needed?

So that move construction/assignment could be defined and supported.

JQuery - $ is not defined

As stated above, it happens due to the conflict of $ variable.

I resolved this issue by reserving a secondary variable for jQuery with no conflict.

var $j = jQuery.noConflict();

and then use it anywhere

$j( "div" ).hide();

more details can be found here

Detect Click into Iframe using JavaScript

Just found this solution... I tried it, I loved it..

Works for cross domain iframes for desktop and mobile!

Don't know if it is foolproof yet

window.addEventListener('blur',function(){
      if(document.activeElement.id == 'CrossDomainiframeId'){
        //do something :-)
      }
});

Happy coding

Difference between jar and war in Java

JAR files allow to package multiple files in order to use it as a library, plugin, or any kind of application. On the other hand, WAR files are used only for web applications.

JAR can be created with any desired structure. In contrast, WAR has a predefined structure with WEB-INF and META-INF directories.

A JAR file allows Java Runtime Environment (JRE) to deploy an entire application including the classes and the associated resources in a single request. On the other hand, a WAR file allows testing and deploying a web application easily.

Why is my JavaScript function sometimes "not defined"?

This can happen when using framesets. In one frame, my variables and methods were defined. In another, they were not. It was especially confusing when using the debugger and seeing my variable defined, then undefined at a breakpoint inside a frame.

How to catch SQLServer timeout exceptions

Updated for c# 6:

    try
    {
        // some code
    }
    catch (SqlException ex) when (ex.Number == -2)  // -2 is a sql timeout
    {
        // handle timeout
    }

Very simple and nice to look at!!

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

This literally means that the mentioned class com.example.Bean doesn't have a public (non-static!) getter method for the mentioned property foo. Note that the field itself is irrelevant here!

The public getter method name must start with get, followed by the property name which is capitalized at only the first letter of the property name as in Foo.

public Foo getFoo() {
    return foo;
}

You thus need to make sure that there is a getter method matching exactly the property name, and that the method is public (non-static) and that the method does not take any arguments and that it returns non-void. If you have one and it still doesn't work, then chances are that you were busy editing code forth and back without firmly cleaning the build, rebuilding the code and redeploying/restarting the application. You need to make sure that you have done so.

For boolean (not Boolean!) properties, the getter method name must start with is instead of get.

public boolean isFoo() {
    return foo;
}

Regardless of the type, the presence of the foo field itself is thus not relevant. It can have a different name, or be completely absent, or even be static. All of below should still be accessible by ${bean.foo}.

public Foo getFoo() {
    return bar;
}
public Foo getFoo() {
    return new Foo("foo");
}
public Foo getFoo() {
    return FOO_CONSTANT;
}

You see, the field is not what counts, but the getter method itself. Note that the property name itself should not be capitalized in EL. In other words, ${bean.Foo} won't ever work, it should be ${bean.foo}.

See also:

What is the LDF file in SQL Server?

ldf saves the log of the db, certainly doesn't saves any real data, but is very important for the proper function of the database.

You can however change the log model to the database to simple so this log does not grow too fast.

Check this for example.

Check here for reference.

Java SecurityException: signer information does not match

I had a similar exception:

java.lang.SecurityException: class "org.hamcrest.Matchers"'s signer information does not match signer information of other classes in the same package

The root problem was that I included the Hamcrest library twice. Once using Maven pom file. And I also added the JUnit 4 library (which also contains a Hamcrest library) to the project's build path. I simply had to remove JUnit from the build path and everything was fine.

Using env variable in Spring Boot's application.properties

This is in response to a number of comments as my reputation isn't high enough to comment directly.

You can specify the profile at runtime as long as the application context has not yet been loaded.

// Previous answers incorrectly used "spring.active.profiles" instead of
// "spring.profiles.active" (as noted in the comments).
// Use AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME to avoid this mistake.

System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, environment);
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/META-INF/spring/applicationContext.xml");

How to clear a chart from a canvas so that hover events cannot be triggered?

Chart.js has a bug: Chart.controller(instance) registers any new chart in a global property Chart.instances[] and deletes it from this property on .destroy().

But at chart creation Chart.js also writes ._meta property to dataset variable:

var meta = dataset._meta[me.id];
if (!meta) {
   meta = dataset._meta[me.id] = {
       type: null,
       data: [],
       dataset: null,
       controller: null,
       hidden: null,     // See isDatasetVisible() comment
       xAxisID: null,
       yAxisID: null
   };

and it doesn't delete this property on destroy().

If you use your old dataset object without removing ._meta property, Chart.js will add new dataset to ._meta without deletion previous data. Thus, at each chart's re-initialization your dataset object accumulates all previous data.

In order to avoid this, destroy dataset object after calling Chart.destroy().

PowerShell: how to grep command output?

If you truly want to "grep" the formatted output (display strings) then go with Mike's approach. There are definitely times where this comes in handy. However if you want to try embracing PowerShell's object pipeline nature, then try this. First, check out the properties on the objects flowing down the pipeline:

PS> alias | Get-Member


   TypeName: System.Management.Automation.AliasInfo

Name                MemberType     Definition
----                ----------     ----------
Equals              Method         bool Equals(System.Object obj)
GetHashCode         Method         int GetHashCode()
GetType             Method         type GetType()
ToString            Method         string ToString()
<snip>
*Definition*        Property       System.String Definition {get;}
<snip>

Note the Definition property which is a header you see when you display the output of Get-Alias (alias) e.g.:

PS> alias

CommandType     Name           *Definition*
-----------     ----           ----------
Alias           %              ForEach-Object
<snip>

Usually the header title matches the property name but not always. That is where using Get-Member comes in handy. It shows you what you need to "script" against. Now if what you want to "grep" is the Definition property contents then consider this. Rather than just grepping that one property's value, you can instead filter each AliasInfo object in the pipepline by the contents of this property and you can use a regex to do it e.g.:

PS> alias | Where-Object {$_.Definition -match 'alias'}

CommandType     Name                   Definition
-----------     ----                   ----------
Alias           epal                   Export-Alias
Alias           gal                    Get-Alias
Alias           ipal                   Import-Alias
Alias           nal                    New-Alias
Alias           sal                    Set-Alias

In this example I use the Where-Object cmdlet to filter objects based on some arbitrary script. In this case, I filter by the Defintion property matched against the regex 'alias'. Only those objects that return true for that filter are allowed to propagate down the pipeline and get formatted for display on the host.

BTW if you're typing this, then you can use one of two aliases for Where-Object - 'Where' or '?'. For example:

PS> gal | ?{$_.Definition -match '-Item*'}

Parse string to DateTime in C#

DateTime.Parse() should work fine for that string format. Reference:

http://msdn.microsoft.com/en-us/library/1k1skd40.aspx#Y1240

Is it throwing a FormatException for you?

Format numbers to strings in Python

str() in python on an integer will not print any decimal places.

If you have a float that you want to ignore the decimal part, then you can use str(int(floatValue)).

Perhaps the following code will demonstrate:

>>> str(5)
'5'
>>> int(8.7)
8

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

Installing dev bits for mysql got rid of the config-win.h error I was having, and threw another. Failed to load and parse the manifest. The system cannot find the file specified. I found the answer to my problem in this post: http://www.fuyun.org/2009/12/install-mysql-for-python-on-windows/.

I copied the file 'C:\Python26\Lib\distutils\msvc9compiler.py` into my virtualenv, made the edit suggested in the above link, and things are working fine.

HTML5 Audio stop function

shamangeorge wrote:

by setting currentTime manually one may fire the 'canplaythrough' event on the audio element.

This is indeed what will happen, and pausing will also trigger the pause event, both of which make this technique unsuitable for use as a "stop" method. Moreover, setting the src as suggested by zaki will make the player try to load the current page's URL as a media file (and fail) if autoplay is enabled - setting src to null is not allowed; it will always be treated as a URL. Short of destroying the player object there seems to be no good way of providing a "stop" method, so I would suggest just dropping the dedicated stop button and providing pause and skip back buttons instead - a stop button wouldn't really add any functionality.

Auto reloading python Flask app upon code changes

Flask applications can optionally be executed in debug mode. In this mode, two very convenient modules of the development server called the reloader and the debugger are enabled by default. When the reloader is enabled, Flask watches all the source code files of your project and automatically restarts the server when any of the files are modified.

By default, debug mode is disabled. To enable it, set a FLASK_DEBUG=1 environment variable before invoking flask run:

(venv) $ export FLASK_APP=hello.py for Windows use > set FLASK_APP=hello.py

(venv) $ export FLASK_DEBUG=1 for Windows use > set FLASK_DEBUG=1

(venv) $ flask run

* Serving Flask app "hello"
* Forcing debug mode on
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger PIN: 273-181-528

Having a server running with the reloader enabled is extremely useful during development, because every time you modify and save a source file, the server automatically restarts and picks up the change.

What's the difference between all the Selection Segues?

For clarity, I'd like to illustrate @Joey's answer above with these gifs :

Show

enter image description here

Show Detail

enter image description here

Present Modally

enter image description here

Present As Popover

enter image description here

How can I set a cookie in react?

You can use default javascript cookies set method. this working perfect.

createCookieInHour: (cookieName, cookieValue, hourToExpire) => {
    let date = new Date();
    date.setTime(date.getTime()+(hourToExpire*60*60*1000));
    document.cookie = cookieName + " = " + cookieValue + "; expires = " +date.toGMTString();
},

call java scripts funtion in react method as below,

createCookieInHour('cookieName', 'cookieValue', 5);

and you can use below way to view cookies.

let cookie = document.cookie.split(';');
console.log('cookie : ', cookie);

please refer below document for more information - URL

Can I dynamically add HTML within a div tag from C# on load event?

Use asp:Panel for that. It translates into a div.

Python:Efficient way to check if dictionary is empty or not

As far as I know the for loop uses the iter function and you should not mess with a structure while iterating over it.

Does it have to be a dictionary? If you use a list something like this might work:

while len(my_list) > 0:
    #get last item from list
    key, value = my_list.pop()
    #do something with key and value
    #maybe
    my_list.append((key, value))

Note that my_list is a list of the tuple (key, value). The only disadvantage is that you cannot access by key.

EDIT: Nevermind, the answer above is mostly the same.

use std::fill to populate vector with increasing numbers

You should use std::iota algorithm (defined in <numeric>):

  std::vector<int> ivec(100);
  std::iota(ivec.begin(), ivec.end(), 0); // ivec will become: [0..99]

Because std::fill just assigns the given fixed value to the elements in the given range [n1,n2). And std::iota fills the given range [n1, n2) with sequentially increasing values, starting with the initial value and then using ++value.You can also use std::generate as an alternative.

Don't forget that std::iota is C++11 STL algorithm. But a lot of modern compilers support it e.g. GCC, Clang and VS2012 : http://msdn.microsoft.com/en-us/library/vstudio/jj651033.aspx

P.S. This function is named after the integer function ? from the programming language APL, and signifies a Greek letter iota. I speculate that originally in APL this odd name was chosen because it resembles an “integer” (even though in mathematics iota is widely used to denote the imaginary part of a complex number).

Understanding slice notation

This is just for some extra info... Consider the list below

>>> l=[12,23,345,456,67,7,945,467]

Few other tricks for reversing the list:

>>> l[len(l):-len(l)-1:-1]
[467, 945, 7, 67, 456, 345, 23, 12]

>>> l[:-len(l)-1:-1]
[467, 945, 7, 67, 456, 345, 23, 12]

>>> l[len(l)::-1]
[467, 945, 7, 67, 456, 345, 23, 12]

>>> l[::-1]
[467, 945, 7, 67, 456, 345, 23, 12]

>>> l[-1:-len(l)-1:-1]
[467, 945, 7, 67, 456, 345, 23, 12]

How to convert from int to string in objective c: example code

== shouldn't be used to compare objects in your if. For NSString use isEqualToString: to compare them.

How can I ignore a property when serializing using the DataContractSerializer?

Additionally, DataContractSerializer will serialize items marked as [Serializable] and will also serialize unmarked types in .NET 3.5 SP1 and later, to allow support for serializing anonymous types.

So, it depends on how you've decorated your class as to how to keep a member from serializing:

  • If you used [DataContract], then remove the [DataMember] for the property.
  • If you used [Serializable], then add [NonSerialized] in front of the field for the property.
  • If you haven't decorated your class, then you should add [IgnoreDataMember] to the property.

xsd:boolean element type accept "true" but not "True". How can I make it accept it?

xs:boolean is predefined with regard to what kind of input it accepts. If you need something different, you have to define your own enumeration:

 <xs:simpleType name="my:boolean">
    <xs:restriction base="xs:string">
      <xs:enumeration value="True"/>
      <xs:enumeration value="False"/>
    </xs:restriction>
  </xs:simpleType>

Correct way to initialize empty slice

As an addition to @ANisus' answer...

below is some information from the "Go in action" book, which I think is worth mentioning:

Difference between nil & empty slices

If we think of a slice like this:

[pointer] [length] [capacity]

then:

nil slice:   [nil][0][0]
empty slice: [addr][0][0] // points to an address

nil slice

They’re useful when you want to represent a slice that doesn’t exist, such as when an exception occurs in a function that returns a slice.

// Create a nil slice of integers.
var slice []int

empty slice

Empty slices are useful when you want to represent an empty collection, such as when a database query returns zero results.

// Use make to create an empty slice of integers.
slice := make([]int, 0)

// Use a slice literal to create an empty slice of integers.
slice := []int{}

Regardless of whether you’re using a nil slice or an empty slice, the built-in functions append, len, and cap work the same.


Go playground example:

package main

import (
    "fmt"
)

func main() {

    var nil_slice []int
    var empty_slice = []int{}

    fmt.Println(nil_slice == nil, len(nil_slice), cap(nil_slice))
    fmt.Println(empty_slice == nil, len(empty_slice), cap(empty_slice))

}

prints:

true 0 0
false 0 0

Can I have an IF block in DOS batch file?

Instead of this goto mess, try using the ampersand & or double ampersand && (conditional to errorlevel 0) as command separators.

I fixed a script snippet with this trick, to summarize, I have three batch files, one which calls the other two after having found which letters the external backup drives have been assigned. I leave the first file on the primary external drive so the calls to its backup routine worked fine, but the calls to the second one required an active drive change. The code below shows how I fixed it:

for %%b in (d e f g h i j k l m n o p q r s t u v w x y z) DO (
if exist "%%b:\Backup.cmd" %%b: & CALL "%%b:\Backup.cmd"
)

PHP output showing little black diamonds with a question mark

For global purposes.

Instead of converting, codifying, decodifying each text I prefer to let them as they are and instead change the server php settings. So,

  1. Let the diamonds

  2. From the browser, on the view menu select "text encoding" and find the one which let's you see your text correctly.

  3. Edit your php.ini and add:

    default_charset = "ISO-8859-1"

or instead of ISO-8859 the one which fits your text encoding.

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

df1 = pd.DataFrame({"gi":[232,66,34,43],"ptt":[342,56,662,123]})
p = df1.index.values
df1.insert( 0, column="new",value = p)
df1

    new     gi     ptt
0    0      232    342
1    1      66     56 
2    2      34     662
3    3      43     123

How to control the width and height of the default Alert Dialog in Android?

If you wanna add dynamic width and height based on your device frame, you can do these calculations and assign the height and width.

 AlertDialog.Builder builderSingle = new 
 AlertDialog.Builder(getActivity());
 builderSingle.setTitle("Title");

 final AlertDialog alertDialog = builderSingle.create();
 alertDialog.show();

 Rect displayRectangle = new Rect();
 Window window = getActivity().getWindow();

 window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);

 alertDialog.getWindow().setLayout((int)(displayRectangle.width() * 
 0.8f), (int)(displayRectangle.height() * 0.8f));

P.S : Show the dialog first and then try to modify the window's layout attributes

Why is sed not recognizing \t as a tab?

I think others have clarified this adequately for other approaches (sed, AWK, etc.). However, my bash-specific answers (tested on macOS High Sierra and CentOS 6/7) follow.

1) If OP wanted to use a search-and-replace method similar to what they originally proposed, then I would suggest using perl for this, as follows. Notes: backslashes before parentheses for regex shouldn't be necessary, and this code line reflects how $1 is better to use than \1 with perl substitution operator (e.g. per Perl 5 documentation).

perl -pe 's/(.*)/\t$1/' $filename > $sedTmpFile && mv $sedTmpFile $filename

2) However, as pointed out by ghostdog74, since the desired operation is actually to simply add a tab at the start of each line before changing the tmp file to the input/target file ($filename), I would recommend perl again but with the following modification(s):

perl -pe 's/^/\t/' $filename > $sedTmpFile && mv $sedTmpFile $filename
## OR
perl -pe $'s/^/\t/' $filename > $sedTmpFile && mv $sedTmpFile $filename

3) Of course, the tmp file is superfluous, so it's better to just do everything 'in place' (adding -i flag) and simplify things to a more elegant one-liner with

perl -i -pe $'s/^/\t/' $filename

How to simulate target="_blank" in JavaScript

This is how I do it with jQuery. I have a class for each link that I want to be opened in new window.

$(function(){

    $(".external").click(function(e) {
        e.preventDefault();
        window.open(this.href);
    });
});

keyword not supported data source

What you have is a valid ADO.NET connection string - but it's NOT a valid Entity Framework connection string.

The EF connection string would look something like this:

<connectionStrings> 
  <add name="NorthwindEntities" connectionString=
     "metadata=.\Northwind.csdl|.\Northwind.ssdl|.\Northwind.msl;
      provider=System.Data.SqlClient;
      provider connection string=&quot;Data Source=SERVER\SQL2000;Initial Catalog=Northwind;Integrated Security=True;MultipleActiveResultSets=False&quot;" 
      providerName="System.Data.EntityClient" /> 
</connectionStrings>

You're missing all the metadata= and providerName= elements in your EF connection string...... you basically only have what's contained in the provider connection string part.

Using the EDMX designer should create a valid EF connection string for you, in your web.config or app.config.

Marc

UPDATE: OK, I understand what you're trying to do: you need a second "ADO.NET" connection string just for ASP.NET user / membership database. Your string is OK, but the providerName is wrong - it would have to be "System.Data.SqlClient" - this connection doesn't use ENtity Framework - don't specify the "EntityClient" for it then!

<add name="ASPNETMembership" 
     connectionString="Data Source=MONTGOMERY-DEV\SQLEXPRESS;Initial Catalog=ASPNETDB;Integrated Security=True;" 
     providerName="System.Data.SqlClient" />

If you specify providerName=System.Data.EntityClient ==> Entity Framework connection string (with the metadata= and everything).

If you need and specify providerName=System.Data.SqlClient ==> straight ADO.NET SQL Server connection string without all the EF additions

Static Vs. Dynamic Binding in Java

With the static method in the parent and child class: Static Binding

public class test1 {   
    public static void main(String args[]) {
        parent pc = new child(); 
        pc.start(); 
    }
}

class parent {
    static public void start() {
        System.out.println("Inside start method of parent");
    }
}

class child extends parent {

    static public void start() {
        System.out.println("Inside start method of child");
    }
}

// Output => Inside start method of parent

Dynamic Binding :

public class test1 {   
    public static void main(String args[]) {
        parent pc = new child();
        pc.start(); 
    }
}

class parent {
   public void start() {
        System.out.println("Inside start method of parent");
    }
}

class child extends parent {

   public void start() {
        System.out.println("Inside start method of child");
    }
}

// Output => Inside start method of child

What is a bus error?

You can also get SIGBUS when a code page cannot be paged in for some reason.

How do I position one image on top of another in HTML?

It may be a little late but for this you can do:

enter image description here

HTML

<!-- html -->
<div class="images-wrapper">
  <img src="images/1" alt="image 1" />
  <img src="images/2" alt="image 2" />
  <img src="images/3" alt="image 3" />
  <img src="images/4" alt="image 4" />
</div>

SASS

// In _extra.scss
$maxImagesNumber: 5;

.images-wrapper {
  img {
    position: absolute;
    padding: 5px;
    border: solid black 1px;
  }

  @for $i from $maxImagesNumber through 1 {
    :nth-child(#{ $i }) {
      z-index: #{ $maxImagesNumber - ($i - 1) };
      left: #{ ($i - 1) * 30 }px;
    }
  }
}

How to get the root dir of the Symfony2 application?

You can also use regular expression in addition to this:

    $directoryPath = $this->container->getParameter('kernel.root_dir') . '/../web/bundles/yourbundle/';
    $directoryPath = preg_replace("/app..../i", "", $directoryPath);
    echo $directoryPath;

Comparing two NumPy arrays for equality, element-wise

Usually two arrays will have some small numeric errors,

You can use numpy.allclose(A,B), instead of (A==B).all(). This returns a bool True/False

How to check if a service is running via batch file and start it, if it is not running?

I just found this thread and wanted to add to the discussion if the person doesn't want to use a batch file to restart services. In Windows there is an option if you go to Services, service properties, then recovery. Here you can set parameters for the service. Like to restart the service if the service stops. Also, you can even have a second fail attempt do something different as in restart the computer.

Send password when using scp to copy files from one server to another

Just pass with sshpass -p "your password" at the beginning of your scp command

sshpass -p "your password" scp ./abc.txt hostname/abc.txt

.NET String.Format() to add commas in thousands place for a number

String.Format("0,###.###"); also works with decimal places

.NET - How do I retrieve specific items out of a Dataset?

You can do like...

If you want to access using ColumnName

Int32 First = Convert.ToInt32(ds.Tables[0].Rows[0]["column4Name"].ToString());
Int32 Second = Convert.ToInt32(ds.Tables[0].Rows[0]["column5Name"].ToString());

OR, if you want to access using Index

Int32 First = Convert.ToInt32(ds.Tables[0].Rows[0][4].ToString());
Int32 Second = Convert.ToInt32(ds.Tables[0].Rows[0][5].ToString());

Correct use of transactions in SQL Server

Add a try/catch block, if the transaction succeeds it will commit the changes, if the transaction fails the transaction is rolled back:

BEGIN TRANSACTION [Tran1]

  BEGIN TRY

      INSERT INTO [Test].[dbo].[T1] ([Title], [AVG])
      VALUES ('Tidd130', 130), ('Tidd230', 230)

      UPDATE [Test].[dbo].[T1]
      SET [Title] = N'az2' ,[AVG] = 1
      WHERE [dbo].[T1].[Title] = N'az'

      COMMIT TRANSACTION [Tran1]

  END TRY

  BEGIN CATCH

      ROLLBACK TRANSACTION [Tran1]

  END CATCH  

Get time of specific timezone

The .getTimezoneOffset() method should work. This will get the time between your time zone and GMT. You can then calculate to whatever you want.

How to SELECT a dropdown list item by value programmatically

If anyone else is trying this and facing problem then let me point one possible problem: If you are using Web Application then inside Page_Load if you are loading drop-down from DB and at the sametime you want to load data, then first load your drop-down lists and then load your data with selected drop-down conditions.

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        LoadDropdown(); //drop-downs generated first
        LoadData(); // other data loading and drop-down value selection logic here
    }
}

And for successfully selecting drop-down from code follow the approved answer above which is

ddl.SelectedValue = "2";.

Hope it solves the problem

jQuery checkbox event handling

$('#myform input:checkbox').click(
 function(e){
   alert($(this).is(':checked'))
 }
)

Creating a new ArrayList in Java

    ArrayList<Class> myArray = new ArrayList<Class>();

Here ArrayList of the particular Class will be made. In general one can have any datatype like int,char, string or even an array in place of Class.

These are added to the array list using

    myArray.add();

And the values are retrieved using

    myArray.get();

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

another cheap hack, which seems to do the trick:

style="padding-bottom: 250px; margin-bottom: -250px;" on the element where the vertical overflow is getting cutoff, with 250 representing as many pixels as you need for your dropdown, etc.

Javascript loading CSV file into an array

You can't use AJAX to fetch files from the user machine. This is absolutely the wrong way to go about it.

Use the FileReader API:

<input type="file" id="file input">

js:

console.log(document.getElementById("file input").files); // list of File objects

var file = document.getElementById("file input").files[0];
var reader = new FileReader();
content = reader.readAsText(file);
console.log(content);

Then parse content as CSV. Keep in mind that your parser currently does not deal with escaped values in CSV like: value1,value2,"value 3","value ""4"""

Error pushing to GitHub - insufficient permission for adding an object to repository database

Try to do following:

Go to your Server

    cd rep.git
    chmod -R g+ws *
    chgrp -R git *
    git config core.sharedRepository true

Then go to your working copy(local repository) and repack it by git repack master

Works perfectly to me.

android splash screen sizes for ldpi,mdpi, hdpi, xhdpi displays ? - eg : 1024X768 pixels for ldpi

  • Xlarge screens are at least 960dp x 720dp
  • List item large screens are at least 640dp x 480dp
  • List item normal screens are at least 470dp x 320dp
  • List item small screens are at least 426dp x 320dp

Use this to create your images and put them in specific resource folder.

JPA Query selecting only specific columns without using Criteria Query?

Yes, like in plain sql you could specify what kind of properties you want to select:

SELECT i.firstProperty, i.secondProperty FROM ObjectName i WHERE i.id=10

Executing this query will return a list of Object[], where each array contains the selected properties of one object.

Another way is to wrap the selected properties in a custom object and execute it in a TypedQuery:

String query = "SELECT NEW CustomObject(i.firstProperty, i.secondProperty) FROM ObjectName i WHERE i.id=10";
TypedQuery<CustomObject> typedQuery = em.createQuery(query , CustomObject.class);
List<CustomObject> results = typedQuery.getResultList();

Examples can be found in this article.

UPDATE 29.03.2018:

@Krish:

@PatrickLeitermann for me its giving "Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: Unable to locate class ***" exception . how to solve this ?

I guess you’re using JPA in the context of a Spring application, don't you? Some other people had exactly the same problem and their solution was adding the fully qualified name (e. g. com.example.CustomObject) after the SELECT NEW keywords.

Maybe the internal implementation of the Spring data framework only recognizes classes annotated with @Entity or registered in a specific orm file by their simple name, which causes using this workaround.

Socket transport "ssl" in PHP not enabled

I also ran into this issue just now while messing with laravel.

I am using wampserver for windows and had to copy the /bin/apache/apacheversion/bin/php.ini file to /bin/php/phpversion/php.ini

What does int argc, char *argv[] mean?

The first parameter is the number of arguments provided and the second parameter is a list of strings representing those arguments.

Double vs. BigDecimal?

If you write down a fractional value like 1 / 7 as decimal value you get

1/7 = 0.142857142857142857142857142857142857142857...

with an infinite sequence of 142857. Since you can only write a finite number of digits you will inevitably introduce a rounding (or truncation) error.

Numbers like 1/10 or 1/100 expressed as binary numbers with a fractional part also have an infinite number of digits after the decimal point:

1/10 = binary 0.0001100110011001100110011001100110...

Doubles store values as binary and therefore might introduce an error solely by converting a decimal number to a binary number, without even doing any arithmetic.

Decimal numbers (like BigDecimal), on the other hand, store each decimal digit as is (binary coded, but each decimal on its own). This means that a decimal type is not more precise than a binary floating point or fixed point type in a general sense (i.e. it cannot store 1/7 without loss of precision), but it is more accurate for numbers that have a finite number of decimal digits as is often the case for money calculations.

Java's BigDecimal has the additional advantage that it can have an arbitrary (but finite) number of digits on both sides of the decimal point, limited only by the available memory.

Rotating a point about another point (2D)

I struggled while working MS OCR Read API which returns back angle of rotation in range (-180, 180]. So I have to do an extra step of converting negative angles to positive. I hope someone struggling with point rotation with negative or positive angles can use the following.

def rotate(origin, point, angle):
    """
    Rotate a point counter-clockwise by a given angle around a given origin.
    """
    # Convert negative angles to positive
    angle = normalise_angle(angle)

    # Convert to radians
    angle = math.radians(angle)

    # Convert to radians
    ox, oy = origin
    px, py = point
    
    # Move point 'p' to origin (0,0)
    _px = px - ox
    _py = py - oy
    
    # Rotate the point 'p' 
    qx = (math.cos(angle) * _px) - (math.sin(angle) * _py)
    qy = (math.sin(angle) * _px) + (math.cos(angle) * _py)
    
    # Move point 'p' back to origin (ox, oy)
    qx = ox + qx
    qy = oy + qy
    
    return [qx, qy]


def normalise_angle(angle):
    """ If angle is negative then convert it to positive. """
    if (angle != 0) & (abs(angle) == (angle * -1)):
        angle = 360 + angle
    return angle

Firing events on CSS class changes in jQuery

using latest jquery mutation

var $target = jQuery(".required-entry");
            var observer = new MutationObserver(function(mutations) {
                mutations.forEach(function(mutation) {
                    if (mutation.attributeName === "class") {
                        var attributeValue = jQuery(mutation.target).prop(mutation.attributeName);
                        if (attributeValue.indexOf("search-class") >= 0){
                            // do what you want
                        }
                    }
                });
            });
            observer.observe($target[0],  {
                attributes: true
            });

// any code which update div having class required-entry which is in $target like $target.addClass('search-class');

How to query for Xml values and attributes from table in SQL Server?

Actually you're close to your goal, you just need to use nodes() method to split your rows and then get values:

select
    s.SqmId,
    m.c.value('@id', 'varchar(max)') as id,
    m.c.value('@type', 'varchar(max)') as type,
    m.c.value('@unit', 'varchar(max)') as unit,
    m.c.value('@sum', 'varchar(max)') as [sum],
    m.c.value('@count', 'varchar(max)') as [count],
    m.c.value('@minValue', 'varchar(max)') as minValue,
    m.c.value('@maxValue', 'varchar(max)') as maxValue,
    m.c.value('.', 'nvarchar(max)') as Value,
    m.c.value('(text())[1]', 'nvarchar(max)') as Value2
from sqm as s
    outer apply s.data.nodes('Sqm/Metrics/Metric') as m(c)

sql fiddle demo

Redirect to a page/URL after alert button is pressed

<head>
<script>
    function myFunction() {
        var x;
        var r = confirm("Do you want to clear data?");
        if (r == true) {
            x = "Your Data is Cleared";
            window.location.href = "firstpage.php";
        }
        else {
            x = "You pressed Cancel!";
        }
        document.getElementById("demo").innerHTML = x;
    }
</script>
</head>
<body>
<button onclick="myFunction()">Retest</button>

<p id="demo"></p>
</body>
</html>

This will redirect to new php page.

Javascript loop through object array?

You can use forEach method to iterate over array of objects.

data.messages.forEach(function(message){
    console.log(message)
});

Refer: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

How to sparsely checkout only one single file from a git repository?

First clone the repo with the -n option, which suppresses the default checkout of all files, and the --depth 1 option, which means it only gets the most recent revision of each file

git clone -n git://path/to/the_repo.git --depth 1

Then check out just the file you want like so:

cd the_repo
git checkout HEAD name_of_file

Django set field value after a form is initialized

To throw yet another way into the mix: this works too, with a bit more modern notation. It just works around the fact that a QueryDict is immutable.

>>> the_form.data = {**f.data.dict(), 'some_field': 47}
>>> the_form['some_field'].as_widget()
'<input type="hidden" name="some_field" value="47"
        class="field-some_field" id="id_some_field">'

Pylint, PyChecker or PyFlakes?

pep8 was recently added to PyPi.

  • pep8 - Python style guide checker
  • pep8 is a tool to check your Python code against some of the style conventions in PEP 8.

It is now super easy to check your code against pep8.

See http://pypi.python.org/pypi/pep8

Left align block of equations

Try this:

\begin{flalign*}
    &|\vec a| = \sqrt{3^{2}+1^{2}} = \sqrt{10} & \\
    &|\vec b| = \sqrt{1^{2}+23^{2}} = \sqrt{530} &\\ 
    &\cos v = \frac{26}{\sqrt{10} \cdot \sqrt{530}} &\\
    &v = \cos^{-1} \left(\frac{26}{\sqrt{10} \cdot \sqrt{530}}\right) &\\
\end{flalign*}

The & sign separates two columns, so an & at the beginning of a line means that the line starts with a blank column.

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

I'm glad that worked out, so I guess you had to explicitly set 'auto' on IE6 in order for it to mimic other browsers!

I actually recently found another technique for scaling images, again designed for backgrounds. This technique has some interesting features:

  1. The image aspect ratio is preserved
  2. The image's original size is maintained (that is, it can never shrink only grow)

The markup relies on a wrapper element:

<div id="wrap"><img src="test.png" /></div>

Given the above markup you then use these rules:

#wrap {
  height: 100px;
  width: 100px;
}
#wrap img {
  min-height: 100%;
  min-width: 100%;
}

If you then control the size of wrapper you get the interesting scale effects that I list above.

To be explicit, consider the following base state: A container that is 100x100 and an image that is 10x10. The result is a scaled image of 100x100.

  1. Starting at the base state, the container resized to 20x100, the image stays resized at 100x100.
  2. Starting at the base state, the image is changed to 10x20, the image resizes to 100x200.

So, in other words, the image is always at least as big as the container, but will scale beyond it to maintain it's aspect ratio.

This probably isn't useful for your site, and it doesn't work in IE6. But, it is useful to get a scaled background for your view port or container.

How does inline Javascript (in HTML) work?

The best way to answer your question is to see it in action.

<a id="test" onclick="alert('test')"> test </a> ?

In the js

var test = document.getElementById('test');
console.log( test.onclick ); 

As you see in the console, if you're using chrome it prints an anonymous function with the event object passed in, although it's a little different in IE.

function onclick(event) {
   alert('test')
}

I agree with some of your points about inline event handlers. Yes they are easy to write, but i don't agree with your point about having to change code in multiple places, if you structure your code well, you shouldn't need to do this.

How do you change the document font in LaTeX?

As second says, most of the "design" decisions made for TeX documents are backed up by well researched usability studies, so changing them should be undertaken with care. It is, however, relatively common to replace Computer Modern with Times (also a serif face).

Try \usepackage{times}.

invalid types 'int[int]' for array subscript

Just for completeness, this error can happen also in a different situation: when you declare an array in an outer scope, but declare another variable with the same name in an inner scope, shadowing the array. Then, when you try to index the array, you are actually accessing the variable in the inner scope, which might not even be an array, or it might be an array with fewer dimensions.

Example:

int a[10];  // a global scope

void f(int a)   // a declared in local scope, overshadows a in global scope
{
  printf("%d", a[0]);  // you trying to access the array a, but actually addressing local argument a
}

Iterating over Typescript Map

es6

for (let [key, value] of map) {
    console.log(key, value);
}

es5

for (let entry of Array.from(map.entries())) {
    let key = entry[0];
    let value = entry[1];
}

HttpServletRequest get JSON POST data

Normaly you can GET and POST parameters in a servlet the same way:

request.getParameter("cmd");

But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.

If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:

BufferedReader reader = request.getReader();

Json post processing example (uses org.json package )

public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException {

  StringBuffer jb = new StringBuffer();
  String line = null;
  try {
    BufferedReader reader = request.getReader();
    while ((line = reader.readLine()) != null)
      jb.append(line);
  } catch (Exception e) { /*report an error*/ }

  try {
    JSONObject jsonObject =  HTTP.toJSONObject(jb.toString());
  } catch (JSONException e) {
    // crash and burn
    throw new IOException("Error parsing JSON request string");
  }

  // Work with the data using methods like...
  // int someInt = jsonObject.getInt("intParamName");
  // String someString = jsonObject.getString("stringParamName");
  // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
  // JSONArray arr = jsonObject.getJSONArray("arrayParamName");
  // etc...
}

What data type to use for hashed password field and what length?

Update: Simply using a hash function is not strong enough for storing passwords. You should read the answer from Gilles on this thread for a more detailed explanation.

For passwords, use a key-strengthening hash algorithm like Bcrypt or Argon2i. For example, in PHP, use the password_hash() function, which uses Bcrypt by default.

$hash = password_hash("rasmuslerdorf", PASSWORD_DEFAULT);

The result is a 60-character string similar to the following (but the digits will vary, because it generates a unique salt).

$2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a

Use the SQL data type CHAR(60) to store this encoding of a Bcrypt hash. Note this function doesn't encode as a string of hexadecimal digits, so we can't as easily unhex it to store in binary.

Other hash functions still have uses, but not for storing passwords, so I'll keep the original answer below, written in 2008.


It depends on the hashing algorithm you use. Hashing always produces a result of the same length, regardless of the input. It is typical to represent the binary hash result in text, as a series of hexadecimal digits. Or you can use the UNHEX() function to reduce a string of hex digits by half.

  • MD5 generates a 128-bit hash value. You can use CHAR(32) or BINARY(16)
  • SHA-1 generates a 160-bit hash value. You can use CHAR(40) or BINARY(20)
  • SHA-224 generates a 224-bit hash value. You can use CHAR(56) or BINARY(28)
  • SHA-256 generates a 256-bit hash value. You can use CHAR(64) or BINARY(32)
  • SHA-384 generates a 384-bit hash value. You can use CHAR(96) or BINARY(48)
  • SHA-512 generates a 512-bit hash value. You can use CHAR(128) or BINARY(64)
  • BCrypt generates an implementation-dependent 448-bit hash value. You might need CHAR(56), CHAR(60), CHAR(76), BINARY(56) or BINARY(60)

As of 2015, NIST recommends using SHA-256 or higher for any applications of hash functions requiring interoperability. But NIST does not recommend using these simple hash functions for storing passwords securely.

Lesser hashing algorithms have their uses (like internal to an application, not for interchange), but they are known to be crackable.

How to delete a cookie using jQuery?

it is the problem of misunderstand of cookie. Browsers recognize cookie values for not just keys also compare the options path & domain. So Browsers recognize different value which cookie values that key is 'name' with server setting option(path='/'; domain='mydomain.com') and key is 'name' with no option.

T-SQL Subquery Max(Date) and Joins

All other answers must work, but using your same syntax (and understanding why the error)

SELECT * FROM MyParts LEFT JOIN MyPrice ON MyParts.Partid = MyPrice.Partid WHERE 
MyPart.PriceDate = (SELECT MAX(MyPrice2.PriceDate) FROM MyPrice as MyPrice2 
WHERE MyPrice2.Partid =  MyParts.Partid)

Table is marked as crashed and should be repaired

I had the same issue when my server free disk space available was 0

You can use the command (there must be ample space for the mysql files)

REPAIR TABLE `<table name>`;

for repairing individual tables

Save and load MemoryStream to/from a file

The stream should really by disposed of even if there's an exception (quite likely on file I/O) - using clauses are my favourite approach for this, so for writing your MemoryStream, you can use:

using (FileStream file = new FileStream("file.bin", FileMode.Create, FileAccess.Write)) {
    memoryStream.WriteTo(file);
}

And for reading it back:

using (FileStream file = new FileStream("file.bin", FileMode.Open, FileAccess.Read)) {
    byte[] bytes = new byte[file.Length];
    file.Read(bytes, 0, (int)file.Length);
    ms.Write(bytes, 0, (int)file.Length);
}

If the files are large, then it's worth noting that the reading operation will use twice as much memory as the total file size. One solution to that is to create the MemoryStream from the byte array - the following code assumes you won't then write to that stream.

MemoryStream ms = new MemoryStream(bytes, writable: false);

My research (below) shows that the internal buffer is the same byte array as you pass it, so it should save memory.

byte[] testData = new byte[] { 104, 105, 121, 97 };
var ms = new MemoryStream(testData, 0, 4, false, true);
Assert.AreSame(testData, ms.GetBuffer());

javascript regex : only english letters allowed

Another option is to use the case-insensitive flag i, then there's no need for the extra character range A-Z.

var reg = /^[a-z]+$/i;
console.log( reg.test("somethingELSE") ); //true
console.log( "somethingELSE".match(reg)[0] ); //"somethingELSE"

Here's a DEMO on how this regex works with test() and match().

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

if you can, use flexbox:

<ul>
    <li>HOME</li>
    <li>ABOUT US</li>
    <li>SERVICES</li>
    <li>PREVIOUS PROJECTS</li>
    <li>TESTIMONIALS</li>
    <li>NEWS</li>
    <li>RESEARCH &amp; DEV</li>
    <li>CONTACT</li>
</ul>

ul {
  display: flex;
  justify-content:space-between;
  list-style-type: none;
}

jsfiddle: http://jsfiddle.net/RAaJ8/

Browser support is actually quite good (with prefixes an other nasty stuff): http://caniuse.com/flexbox

Get Bitmap attached to ImageView

try this code:

Bitmap bitmap;
bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();

Copy data from one existing row to another existing row in SQL?

Try this:

UPDATE barang
SET ID FROM(SELECT tblkatalog.tblkatalog_id FROM tblkatalog 
WHERE tblkatalog.tblkatalog_nomor = barang.NO_CAT) WHERE barang.NO_CAT <>'';

Pods stuck in Terminating status

I stumbled upon this recently when removing rook ceph namespace - it got stuck in Terminating state.

The only thing that helped was removing kubernetes finalizer by directly calling k8s api with curl as suggested here.

  • kubectl get namespace rook-ceph -o json > tmp.json
  • delete kubernetes finalizer in tmp.json (leave empty array "finalizers": [])
  • run kubectl proxy in another terminal for auth purposes and run following curl request to returned port
  • curl -k -H "Content-Type: application/json" -X PUT --data-binary @tmp.json 127.0.0.1:8001/k8s/clusters/c-mzplp/api/v1/namespaces/rook-ceph/finalize
  • namespace is gone

Detailed rook ceph teardown here.

MongoDB: How to find out if an array field contains an element?

I am trying to explain by putting problem statement and solution to it. I hope it will help

Problem Statement:

Find all the published products, whose name like ABC Product or PQR Product, and price should be less than 15/-

Solution:

Below are the conditions that need to be taken care of

  1. Product price should be less than 15
  2. Product name should be either ABC Product or PQR Product
  3. Product should be in published state.

Below is the statement that applies above criterion to create query and fetch data.

$elements = $collection->find(
             Array(
                [price] => Array( [$lt] => 15 ),
                [$or] => Array(
                            [0]=>Array(
                                    [product_name]=>Array(
                                       [$in]=>Array(
                                            [0] => ABC Product,
                                            [1]=> PQR Product
                                            )
                                        )
                                    )
                                ),
                [state]=>Published
                )
            );

How to set editable true/false EditText in Android programmatically?

Fetch the KeyListener value of EditText by editText.getKeyListener() and store in the KeyListener type variable, which will contain the Editable property value:

KeyListener variable;
variable = editText.getKeyListener(); 

Set the Editable property of EditText to false as:

 edittext.setKeyListener(null);

Now set Editable property of EditText to true as:

editText.setKeyListener(variable);  

Note: In XML the default Editable property of EditText should be true.

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

Given a filesystem path, is there a shorter way to extract the filename without its extension?

string Location = "C:\\Program Files\\hello.txt";

string FileName = Location.Substring(Location.LastIndexOf('\\') +
    1);

Remove leading comma from a string

Assuming the string is called myStr:

// Strip start and end quotation mark and possible initial comma
myStr=myStr.replace(/^,?'/,'').replace(/'$/,'');

// Split stripping quotations
myArray=myStr.split("','");

Note that if a string can be missing in the list without even having its quotation marks present and you want an empty spot in the corresponding location in the array, you'll need to write the splitting manually for a robust solution.

How to create an Excel File with Nodejs?

Using fs package we can create excel/CSV file from JSON data.

Step 1: Store JSON data in a variable (here it is in jsn variable).

Step 2: Create empty string variable(here it is data).

Step 3: Append every property of jsn to string variable data, while appending put '\t' in-between 2 cells and '\n' after completing the row.

Code:

var fs = require('fs');

var jsn = [{
    "name": "Nilesh",
    "school": "RDTC",
    "marks": "77"
   },{
    "name": "Sagar",
    "school": "RC",
    "marks": "99.99"
   },{
    "name": "Prashant",
    "school": "Solapur",
    "marks": "100"
 }];

var data='';
for (var i = 0; i < jsn.length; i++) {
    data=data+jsn[i].name+'\t'+jsn[i].school+'\t'+jsn[i].marks+'\n';
 }
fs.appendFile('Filename.xls', data, (err) => {
    if (err) throw err;
    console.log('File created');
 });

Output

Change the bullet color of list

Example JS Fiddle

Bullets take the color property of the list:

.listStyle {
    color: red;
}

Note if you want your list text to be a different colour, you have to wrap it in say, a p, for example:

.listStyle p {
    color: black;
}

Example HTML:

<ul class="listStyle">
    <li>
        <p><strong>View :</strong> blah blah.</p>
    </li>
    <li>
        <p><strong>View :</strong> blah blah.</p>
    </li>
</ul>

What exactly is node.js used for?

What can we build with NodeJS:

  • REST APIs and Backend Applications
  • Real-Time services (Chat, Games etc)
  • Blogs, CMS, Social Applications.
  • Utilities and Tools
  • Anything that is not CPU intensive.

Calling a particular PHP function on form submit

PHP is run on a server, Your browser is a client. Once the server sends all the info to the client, nothing can be done on the server until another request is made.

To make another request without refreshing the page you are going to have to look into ajax. Look into jQuery as it makes ajax requests easy

How to make a view with rounded corners?

public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, int pixels) {

        Bitmap roundedBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap
                .getHeight(), Config.ARGB_8888);
        Canvas canvas = new Canvas(roundedBitmap);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
        final RectF rectF = new RectF(rect);
        final float roundPx = pixels;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        return roundedBitmap;
    }

When do I use the PHP constant "PHP_EOL"?

Yes, PHP_EOL is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.

Note that PHP_EOL represents the endline character for the current system. For instance, it will not find a Windows endline when executed on a unix-like system.

ld.exe: cannot open output file ... : Permission denied

Got the same issue. Read this. Disabled the antivirus software (mcaffee). Et voila

Confirmed by the antivirus log:

Blocked by Access Protection rule d:\mingw64\x86_64-w64-mingw32\bin\ld.exe d:\workspace\cpp\bar\foo.exe User-defined Rules:ctx3 Action blocked : Create

How to pass value from <option><select> to form action

you can simply use your own code but add name for the select tag

<form method="POST" action="index.php?action=contact_agent&agent_id=">
    <select name="agent_id">
        <option value="1">Agent Homer</option>
        <option value="2">Agent Lenny</option>
        <option value="3">Agent Carl</option>
    </select>

then you can access it like this

String agent=request.getparameter("agent_id");

Show row number in row header of a DataGridView

You can also draw the string dynamically inside the RowPostPaint event:

private void dgGrid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
    var grid = sender as DataGridView;
    var rowIdx = (e.RowIndex + 1).ToString();

    var centerFormat = new StringFormat() 
    { 
        // right alignment might actually make more sense for numbers
        Alignment = StringAlignment.Center, 
        LineAlignment = StringAlignment.Center
    };

    var headerBounds = new Rectangle(e.RowBounds.Left, e.RowBounds.Top, grid.RowHeadersWidth, e.RowBounds.Height);
    e.Graphics.DrawString(rowIdx, this.Font, SystemBrushes.ControlText, headerBounds, centerFormat);
}

Reading rather large json files in Python

The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.

The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.

The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.

Edit: Also worth a look - kashif's comment about json-streamer and Henrik Heino's comment about bigjson.

How to URL encode a string in Ruby

I created a gem to make URI encoding stuff cleaner to use in your code. It takes care of binary encoding for you.

Run gem install uri-handler, then use:

require 'uri-handler'

str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a".to_uri
# => "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"

It adds the URI conversion functionality into the String class. You can also pass it an argument with the optional encoding string you would like to use. By default it sets to encoding 'binary' if the straight UTF-8 encoding fails.

Add primary key to existing table

ALTER TABLE TABLE_NAME ADD PRIMARY KEY(`persionId`,`Pname`,`PMID`)

Replace first occurrence of string in Python

Use re.sub directly, this allows you to specify a count:

regex.sub('', url, 1)

(Note that the order of arguments is replacement, original not the opposite, as might be suspected.)

Docker CE on RHEL - Requires: container-selinux >= 2.9

[SOLVED] Simple one command to fix this issue.

yum install http://mirror.centos.org/centos/7/extras/x86_64/Packages/container-selinux-2.107-3.el7.noarch.rpm

How to convert strings into integers in Python?

If it's only a tuple of tuples, something like rows=[map(int, row) for row in rows] will do the trick. (There's a list comprehension and a call to map(f, lst), which is equal to [f(a) for a in lst], in there.)

Eval is not what you want to do, in case there's something like __import__("os").unlink("importantsystemfile") in your database for some reason. Always validate your input (if with nothing else, the exception int() will raise if you have bad input).

How to make IPython notebook matplotlib plot inline

Use the %pylab inline magic command.

Fast ceiling of an integer division in C / C++

simplified generic form,

int div_up(int n, int d) {
    return n / d + (((n < 0) ^ (d > 0)) && (n % d));
} //i.e. +1 iff (not exact int && positive result)

For a more generic answer, C++ functions for integer division with well defined rounding strategy

Efficiently sorting a numpy array in descending order?

For short arrays I suggest using np.argsort() by finding the indices of the sorted negatived array, which is slightly faster than reversing the sorted array:

In [37]: temp = np.random.randint(1,10, 10)

In [38]: %timeit np.sort(temp)[::-1]
100000 loops, best of 3: 4.65 µs per loop

In [39]: %timeit temp[np.argsort(-temp)]
100000 loops, best of 3: 3.91 µs per loop

Simplest way to set image as JPanel background

class Logo extends JPanel
{
    Logo()
    {
        //code
    }
    @Override
    public void paintComponent(Graphics g) 
    {
        super.paintComponent(g);
        ImageIcon img = new ImageIcon("logo.jpg");
        g.drawImage(img.getImage(), 0, 0, this.getWidth(), this.getHeight(), null);
    }
}

Difference between mkdir() and mkdirs() in java for java.io.File

mkdir()

creates only one directory at a time, if it is parent that one only. other wise it can create the sub directory(if the specified path is existed only) and do not create any directories in between any two directories. so it can not create smultiple directories in one directory

mkdirs()

create the multiple directories(in between two directories also) at a time.

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

I ran into this having 2 Doctrine DBAL connections, one of those as non-transactional (for important logs), they are intended to run parallel not depending on each other.

CodeExecution(
    TransactionConnectionQuery()
    TransactionlessConnectionQuery()
)

My integration tests were wrapped into transactions for data rollback after very test.

beginTransaction()
CodeExecution(
    TransactionConnectionQuery()
    TransactionlessConnectionQuery() // CONFLICT
)
rollBack()

My solution was to disable the wrapping transaction in those tests and reset the db data in another way.

How do you create a hidden div that doesn't create a line break or horizontal space?

To hide the element visually, but keep it in the html, you can use:

<div style='visibility:hidden; overflow:hidden; height:0; width:0;'>
  [content]
</div>

or

<div style='visibility:hidden; overflow:hidden; position:absolute;'>
  [content]
</div>

What may go wrong with display:none? It removes the element completely from the html, so some functionalities may be broken if they need to access something in the hidden element.

Read Excel sheet in Powershell

This assumes that the content is in column B on each sheet (since it's not clear how you determine the column on each sheet.) and the last row of that column is also the last row of the sheet.

$xlCellTypeLastCell = 11 
$startRow = 5 
$col = 2 

$excel = New-Object -Com Excel.Application
$wb = $excel.Workbooks.Open("C:\Users\Administrator\my_test.xls")

for ($i = 1; $i -le $wb.Sheets.Count; $i++)
{
    $sh = $wb.Sheets.Item($i)
    $endRow = $sh.UsedRange.SpecialCells($xlCellTypeLastCell).Row
    $city = $sh.Cells.Item($startRow, $col).Value2
    $rangeAddress = $sh.Cells.Item($startRow + 1, $col).Address() + ":" + $sh.Cells.Item($endRow, $col).Address()
    $sh.Range($rangeAddress).Value2 | foreach 
    {
        New-Object PSObject -Property @{ City = $city; Area = $_ }
    }
}

$excel.Workbooks.Close()

OS X: equivalent of Linux's wget

brew install wget

Homebrew is a package manager for OSX analogous to yum, apt-get, choco, emerge, etc. Be aware that you will also need to install Xcode and the Command Line Tools. Virtually anyone who uses the command line in OSX will want to install these things anyway.

If you can't or don't want to use homebrew, you could also:

Install wget manually:

curl -# "http://ftp.gnu.org/gnu/wget/wget-1.17.1.tar.xz" -o "wget.tar.xz"
tar xf wget.tar.xz
cd wget-1.17.1
./configure --with-ssl=openssl -with-libssl-prefix=/usr/local/ssl && make -j8 && make install

Or, use a bash alias:

function _wget() { curl "${1}" -o $(basename "${1}") ; };
alias wget='_wget'