Programs & Examples On #Azure queues

Microsoft Azure (formerly Windows Azure before March 25, 2014) is a cloud computing platform and infrastructure, created by Microsoft, for building, deploying and managing applications and services through a global network of Microsoft-managed data centers. Azure Queue storage is used for transporting messages between applications as normally we can consider a MSMQ do that in cloud.

CSS Div width percentage and padding without breaking layout

Try removing the position from header and add overflow to container:

#container {
    position:relative;
    width:80%;
    height:auto;
    overflow:auto;
}
#header {
    width:80%;
    height:50px;
    padding:10px;
}

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

In your last example:

var latestCust = db.Customers
.OrderByDescending(x=> x.CreatedOn)
.FirstOrDefault();//Single or First, or doesn't matter?

Yes it does. If you try to use SingleOrDefault() and the query results in more than record you would get and exception. The only time you can safely use SingleOrDefault() is when you are expecting only 1 and only 1 result...

Relative imports - ModuleNotFoundError: No module named x

As was stated in the comments to the original post, this seemed to be an issue with the python interpreter I was using for whatever reason, and not something wrong with the python scripts. I switched over from the WinPython bundle to the official python 3.6 from python.org and it worked just fine. thanks for the help everyone :)

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

I also had this issue, where trying to run in production without precompiling it would still throw not-precompiled errors. I had to change which line was commented application.rb:

  # If you precompile assets before deploying to production, use this line
  # Bundler.require(*Rails.groups(:assets => %w(development test)))
  # If you want your assets lazily compiled in production, use this line
  Bundler.require(:default, :assets, Rails.env)

What is the perfect counterpart in Python for "while not EOF"

You can use the following code snippet. readlines() reads in the whole file at once and splits it by line.

line = obj.readlines()

Reading/writing an INI file

I want to introduce an IniParser library I've created completely in c#, so it contains no dependencies in any OS, which makes it Mono compatible. Open Source with MIT license -so it can be used in any code.

You can check out the source in GitHub, and it is also available as a NuGet package

It's heavily configurable, and really simple to use.

Sorry for the shameless plug but I hope it can be of help of anyone revisiting this answer.

What is a singleton in C#?

What it is: A class for which there is just one, persistent instance across the lifetime of an application. See Singleton Pattern.

When you should use it: As little as possible. Only when you are absolutely certain that you need it. I'm reluctant to say "never", but there is usually a better alternative, such as Dependency Injection or simply a static class.

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

In the Hibernate mapping file for the id property, if you use any generator class, for that property you should not set the value explicitly by using a setter method.

If you set the value of the Id property explicitly, it will lead the error above. Check this to avoid this error.

How to find length of digits in an integer?

Assuming you are asking for the largest number you can store in an integer, the value is implementation dependent. I suggest that you don't think in that way when using python. In any case, quite a large value can be stored in a python 'integer'. Remember, Python uses duck typing!

Edit: I gave my answer before the clarification that the asker wanted the number of digits. For that, I agree with the method suggested by the accepted answer. Nothing more to add!

Copy files from one directory into an existing directory

If you want to copy something from one directory into the current directory, do this:

cp dir1/* .

This assumes you're not trying to copy hidden files.

How can I do GUI programming in C?

A C compiler itself won't provide you with GUI functionality, but there are plenty of libraries for that sort of thing. The most popular is probably GTK+, but it may be a little too complicated if you are just starting out and want to quickly get a GUI up and running.

For something a little simpler, I would recommend IUP. With it, you can use a simple GUI definition language called LED to layout controls (but you can do it with pure C, if you want to).

Getting a list of associative array keys

for (var key in dictionary) {
  // Do something with key
}

It's the for..in statement.

How to get the PID of a process by giving the process name in Mac OS X ?

Try this one:

echo "$(ps -ceo pid=,comm= | awk '/firefox/ { print $1; exit }')"

The ps command produces output like this, with the PID in the first column and the executable name (only) in the second column:

bookworm% ps -ceo pid=,comm=
    1 launchd
   10 kextd
   11 UserEventAgent
   12 mDNSResponder
   13 opendirectoryd
   14 notifyd
   15 configd

...which awk processes, printing the first column (pid) and exiting after the first match.

Best way to find the months between two dates

You can also use the arrow library. This is a simple example:

from datetime import datetime
import arrow

start = datetime(2014, 1, 17)
end = datetime(2014, 6, 20)

for d in arrow.Arrow.range('month', start, end):
    print d.month, d.format('MMMM')

This will print:

1 January
2 February
3 March
4 April
5 May
6 June

Hope this helps!

How do I get an apk file from an Android device?

On unix systems, you can try this function:

function android_pull_apk() {
    if [ -z "$1" ]; then
        echo "You must pass a package to this function!"
        echo "Ex.: android_pull_apk \"com.android.contacts\""
        return 1
    fi

    if [ -z "$(adb shell pm list packages | grep $1)" ]; then
        echo "You are typed a invalid package!"
        return 1
    fi

    apk_path="`adb shell pm path $1 | sed -e 's/package://g' | tr '\n' ' ' | tr -d '[:space:]'`"
    apk_name="`adb shell basename ${apk_path} | tr '\n' ' ' | tr -d '[:space:]'`"

    destination="$HOME/Documents/Android/APKs"
    mkdir -p "$destination"

    adb pull ${apk_path} ${destination}
    echo -e "\nAPK saved in \"$destination/$apk_name\""
}
  • Example: android_pull_apk com.android.contacts
  • Note: To identify the package: adb shell pm list packages

Defining private module functions in python

This question was not fully answered, since module privacy is not purely conventional, and since using import may or may not recognize module privacy, depending on how it is used.

If you define private names in a module, those names will be imported into any script that uses the syntax, 'import module_name'. Thus, assuming you had correctly defined in your example the module private, _num, in a.py, like so..

#a.py
_num=1

..you would be able to access it in b.py with the module name symbol:

#b.py
import a
...
foo = a._num # 1

To import only non-privates from a.py, you must use the from syntax:

#b.py
from a import *
...
foo = _num # throws NameError: name '_num' is not defined

For the sake of clarity, however, it is better to be explicit when importing names from modules, rather than importing them all with a '*':

#b.py
from a import name1 
from a import name2
...

Get the position of a div/span tag

You can call the method getBoundingClientRect() on a reference to the element. Then you can examine the top, left, right and/or bottom properties...

var offsets = document.getElementById('11a').getBoundingClientRect();
var top = offsets.top;
var left = offsets.left;

If using jQuery, you can use the more succinct code...

var offsets = $('#11a').offset();
var top = offsets.top;
var left = offsets.left;

Adding link a href to an element using css

No. Its not possible to add link through css. But you can use jquery

$('.case').each(function() {
  var link = $(this).html();
  $(this).contents().wrap('<a href="example.com/script.php?id="></a>');
});

Here the demo: http://jsfiddle.net/r5uWX/1/

.NET Console Application Exit Event

If you are using a console application and you are pumping messages, can't you use the WM_QUIT message?

How to concatenate two layers in keras?

You're getting the error because result defined as Sequential() is just a container for the model and you have not defined an input for it.

Given what you're trying to build set result to take the third input x3.

first = Sequential()
first.add(Dense(1, input_shape=(2,), activation='sigmoid'))

second = Sequential()
second.add(Dense(1, input_shape=(1,), activation='sigmoid'))

third = Sequential()
# of course you must provide the input to result which will be your x3
third.add(Dense(1, input_shape=(1,), activation='sigmoid'))

# lets say you add a few more layers to first and second.
# concatenate them
merged = Concatenate([first, second])

# then concatenate the two outputs

result = Concatenate([merged,  third])

ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)

result.compile(optimizer=ada_grad, loss='binary_crossentropy',
               metrics=['accuracy'])

However, my preferred way of building a model that has this type of input structure would be to use the functional api.

Here is an implementation of your requirements to get you started:

from keras.models import Model
from keras.layers import Concatenate, Dense, LSTM, Input, concatenate
from keras.optimizers import Adagrad

first_input = Input(shape=(2, ))
first_dense = Dense(1, )(first_input)

second_input = Input(shape=(2, ))
second_dense = Dense(1, )(second_input)

merge_one = concatenate([first_dense, second_dense])

third_input = Input(shape=(1, ))
merge_two = concatenate([merge_one, third_input])

model = Model(inputs=[first_input, second_input, third_input], outputs=merge_two)
ada_grad = Adagrad(lr=0.1, epsilon=1e-08, decay=0.0)
model.compile(optimizer=ada_grad, loss='binary_crossentropy',
               metrics=['accuracy'])

To answer the question in the comments:

  1. How are result and merged connected? Assuming you mean how are they concatenated.

Concatenation works like this:

  a        b         c
a b c   g h i    a b c g h i
d e f   j k l    d e f j k l

i.e rows are just joined.

  1. Now, x1 is input to first, x2 is input into second and x3 input into third.

change html input type by JS?

Changing the type of an <input type=password> throws a security error in some browsers (old IE and Firefox versions).

You’ll need to create a new input element, set its type to the one you want, and clone all other properties from the existing one.

I do this in my jQuery placeholder plugin: https://github.com/mathiasbynens/jquery-placeholder/blob/master/jquery.placeholder.js#L80-84

To work in Internet Explorer:

  • dynamically create a new element
  • copy the properties of the old element into the new element
  • set the type of the new element to the new type
  • replace the old element with the new element

The function below accomplishes the above tasks for you:

<script>
function changeInputType(oldObject, oType) {
    var newObject = document.createElement('input');
    newObject.type = oType;
    if(oldObject.size) newObject.size = oldObject.size;
    if(oldObject.value) newObject.value = oldObject.value;
    if(oldObject.name) newObject.name = oldObject.name;
    if(oldObject.id) newObject.id = oldObject.id;
    if(oldObject.className) newObject.className = oldObject.className;
    oldObject.parentNode.replaceChild(newObject,oldObject);
    return newObject;
}
</script>

Calculating arithmetic mean (one type of average) in Python

from statistics import mean
avarage=mean(your_list)

for example

from statistics import mean

my_list=[5,2,3,2]
avarage=mean(my_list)
print(avarage)

and result is

3.0

How to get equal width of input and select fields

I tried Gaby's answer (+1) above but it only partially solved my problem. Instead I used the following CSS, where content-box was changed to border-box:

input, select {
    -webkit-box-sizing: border-box;
       -moz-box-sizing: border-box;
            box-sizing: border-box;
}

Disable button in angular with two conditions?

Declare a variable in component.ts and initialize it to some value

 buttonDisabled: boolean;

  ngOnInit() {
    this.buttonDisabled = false;
  }

Now in .html or in the template, you can put following code:

<button disabled="{{buttonDisabled}}"> Click Me </button>

Now you can enable/disable button by changing value of buttonDisabled variable.

Add space between <li> elements

Since you are asking for space between , I would add an override to the last item to get rid of the extra margin there:

_x000D_
_x000D_
li {_x000D_
  background: red;_x000D_
  margin-bottom: 40px;_x000D_
}_x000D_
_x000D_
li:last-child {_x000D_
 margin-bottom: 0px;_x000D_
}_x000D_
_x000D_
ul {_x000D_
  background: silver;_x000D_
  padding: 1px;  _x000D_
  padding-left: 40px;_x000D_
}
_x000D_
<ul>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
<li>Item 1</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

The result of it might not be visual at all times, because of margin-collapsing and stuff... in the example snippets I've included, I've added a small 1px padding to the ul-element to prevent the collapsing. Try removing the li:last-child-rule, and you'll see that the last item now extends the size of the ul-element.

Strip / trim all strings of a dataframe

If you really want to use regex, then

>>> df.replace('(^\s+|\s+$)', '', regex=True, inplace=True)
>>> df
   0   1
0  a  10
1  c   5

But it should be faster to do it like this:

>>> df[0] = df[0].str.strip()

How do I get a specific range of numbers from rand()?

rand() % (max_number + 1 - minimum_number) + minimum_number

So, for 0-65:

rand() % (65 + 1 - 0) + 0

(obviously you can leave the 0 off, but it's there for completeness).

Note that this will bias the randomness slightly, but probably not anything to be concerned about if you're not doing something particularly sensitive.

JavaScript naming conventions

I think that besides some syntax limitations; the naming conventions reasoning are very much language independent. I mean, the arguments in favor of c_style_functions and JavaLikeCamelCase could equally well be used the opposite way, it's just that language users tend to follow the language authors.

having said that, i think most libraries tend to roughly follow a simplification of Java's CamelCase. I find Douglas Crockford advices tasteful enough for me.

How can I run a directive after the dom has finished rendering?

there is a ngcontentloaded event, I think you can use it

.directive('directiveExample', function(){
   return {
       restrict: 'A',
       link: function(scope, elem, attrs){

                $$window = $ $window


                init = function(){
                    contentHeight = elem.outerHeight()
                    //do the things
                }

                $$window.on('ngcontentloaded',init)

       }
   }
});

How can one pull the (private) data of one's own Android app?

You may use this shell script below. It is able to pull files from app cache as well, not like the adb backup tool:

#!/bin/sh

if [ -z "$1" ]; then 
    echo "Sorry script requires an argument for the file you want to pull."
    exit 1
fi

adb shell "run-as com.corp.appName cat '/data/data/com.corp.appNamepp/$1' > '/sdcard/$1'"
adb pull "/sdcard/$1"
adb shell "rm '/sdcard/$1'"

Then you can use it like this:

./pull.sh files/myFile.txt
./pull.sh cache/someCachedData.txt

What is the difference between buffer and cache memory in Linux?

Buffers are associated with a specific block device, and cover caching of filesystem metadata as well as tracking in-flight pages. The cache only contains parked file data. That is, the buffers remember what's in directories, what file permissions are, and keep track of what memory is being written from or read to for a particular block device. The cache only contains the contents of the files themselves.

quote link

Difference between objectForKey and valueForKey?

Here's a great reason to use objectForKey: wherever possible instead of valueForKey: - valueForKey: with an unknown key will throw NSUnknownKeyException saying "this class is not key value coding-compliant for the key ".

How to get class object's name as a string in Javascript?

Short answer: No. myObj isn't the name of the object, it's the name of a variable holding a reference to the object - you could have any number of other variables holding a reference to the same object.

Now, if it's your program, then you make the rules: if you want to say that any given object will only be referenced by one variable, ever, and diligently enforce that in your code, then just set a property on the object with the name of the variable.

That said, i doubt what you're asking for is actually what you really want. Maybe describe your problem in a bit more detail...?


Pedantry: JavaScript doesn't have classes. someObject is a constructor function. Given a reference to an object, you can obtain a reference to the function that created it using the constructor property.


In response to the additional details you've provided:

The answer you're looking for can be found here: JavaScript Callback Scope (and in response to numerous other questions on SO - it's a common point of confusion for those new to JS). You just need to wrap the call to the object member in a closure that preserves access to the context object.

Best practice for localization and globalization of strings and labels

When you’re faced with a problem to solve (and frankly, who isn’t these days?), the basic strategy usually taken by we computer people is called “divide and conquer.” It goes like this:

  • Conceptualize the specific problem as a set of smaller sub-problems.
  • Solve each smaller problem.
  • Combine the results into a solution of the specific problem.

But “divide and conquer” is not the only possible strategy. We can also take a more generalist approach:

  • Conceptualize the specific problem as a special case of a more general problem.
  • Somehow solve the general problem.
  • Adapt the solution of the general problem to the specific problem.

- Eric Lippert

I believe many solutions already exist for this problem in server-side languages such as ASP.Net/C#.

I've outlined some of the major aspects of the problem

  • Issue: We need to load data only for the desired language

    Solution: For this purpose we save data to a separate files for each language

ex. res.de.js, res.fr.js, res.en.js, res.js(for default language)

  • Issue: Resource files for each page should be separated so we only get the data we need

    Solution: We can use some tools that already exist like https://github.com/rgrove/lazyload

  • Issue: We need a key/value pair structure to save our data

    Solution: I suggest a javascript object instead of string/string air. We can benefit from the intellisense from an IDE

  • Issue: General members should be stored in a public file and all pages should access them

    Solution: For this purpose I make a folder in the root of web application called Global_Resources and a folder to store global file for each sub folders we named it 'Local_Resources'

  • Issue: Each subsystems/subfolders/modules member should override the Global_Resources members on their scope

    Solution: I considered a file for each

Application Structure

root/
    Global_Resources/
        default.js
        default.fr.js
    UserManagementSystem/
        Local_Resources/
            default.js
            default.fr.js
            createUser.js
        Login.htm
        CreateUser.htm

The corresponding code for the files:

Global_Resources/default.js

var res = {
    Create : "Create",
    Update : "Save Changes",
    Delete : "Delete"
};

Global_Resources/default.fr.js

var res = {
    Create : "créer",
    Update : "Enregistrer les modifications",
    Delete : "effacer"
};

The resource file for the desired language should be loaded on the page selected from Global_Resource - This should be the first file that is loaded on all the pages.

UserManagementSystem/Local_Resources/default.js

res.Name = "Name";
res.UserName = "UserName";
res.Password = "Password";

UserManagementSystem/Local_Resources/default.fr.js

res.Name = "nom";
res.UserName = "Nom d'utilisateur";
res.Password = "Mot de passe";

UserManagementSystem/Local_Resources/createUser.js

// Override res.Create on Global_Resources/default.js
res.Create = "Create User"; 

UserManagementSystem/Local_Resources/createUser.fr.js

// Override Global_Resources/default.fr.js
res.Create = "Créer un utilisateur";

manager.js file (this file should be load last)

res.lang = "fr";

var globalResourcePath = "Global_Resources";
var resourceFiles = [];

var currentFile = globalResourcePath + "\\default" + res.lang + ".js" ;

if(!IsFileExist(currentFile))
    currentFile = globalResourcePath + "\\default.js" ;
if(!IsFileExist(currentFile)) throw new Exception("File Not Found");

resourceFiles.push(currentFile);

// Push parent folder on folder into folder
foreach(var folder in parent folder of current page)
{
    currentFile = folder + "\\Local_Resource\\default." + res.lang + ".js";

    if(!IsExist(currentFile))
        currentFile = folder + "\\Local_Resource\\default.js";
    if(!IsExist(currentFile)) throw new Exception("File Not Found");

    resourceFiles.push(currentFile);
}

for(int i = 0; i < resourceFiles.length; i++) { Load.js(resourceFiles[i]); }

// Get current page name
var pageNameWithoutExtension = "SomePage";

currentFile = currentPageFolderPath + pageNameWithoutExtension + res.lang + ".js" ;

if(!IsExist(currentFile))
    currentFile = currentPageFolderPath + pageNameWithoutExtension + ".js" ;
if(!IsExist(currentFile)) throw new Exception("File Not Found");

Hope it helps :)

How to run Spyder in virtual environment?

What worked for me :

  1. run spyder from the environment (after source activate)
  2. go to Tools --> preferences --> python Interpreter and select the python file from the env you want to link to spyder ex : /home/you/anaconda3/envs/your_env/bin/python

Worked on ubuntu 16, spyder3, python3.6.

How to split a long array into smaller arrays, with JavaScript

using prototype we can set directly to array class

_x000D_
_x000D_
Array.prototype.chunk = function(n) {_x000D_
  if (!this.length) {_x000D_
    return [];_x000D_
  }_x000D_
  return [this.slice(0, n)].concat(this.slice(n).chunk(n));_x000D_
};_x000D_
console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15].chunk(5));
_x000D_
_x000D_
_x000D_

PHP Warning: Module already loaded in Unknown on line 0

I think you have loaded Xdebug probably twice in php.ini.

  1. check the php.ini, that not have set xdebug.so for the values extension= and zend_extension=.

  2. Check also /etc/php5/apache2 and /etc/php5/cli/. You should not load in each php.ini in these directories the extension xdebug.so. Only one file, php.ini should load it.

    Note: Inside the path is the string /etc/php5. The 5 is the version of PHP. So if you use another version, you always get a different path, like php7.

how to display none through code behind

try this

<div id="login_div" runat="server">

and on the code behind.

login_div.Style.Add("display", "none");

CSS Printing: Avoiding cut-in-half DIVs between pages?

In my case I managed to fix the page break difficulties in webkit by setting my selected divs to page-break-inside:avoid, and also setting all elements to display:inline. So like this:

@media print{
* {
    display:inline;
}
script, style { 
    display:none; 
}
div {
    page-break-inside:avoid;
}

}

It seems like page-break-properties can only be applied to inline elements (in webkit). I tried to only apply display:inline to the particular elements I needed, but this didn't work. The only thing that worked was applying inline to all elements. I guess it's one of the large container div' that's messing things up.

Maybe someone could expand on this.

How do I know the script file name in a Bash script?

echo "$(basename "`test -L ${BASH_SOURCE[0]} \
                   && readlink ${BASH_SOURCE[0]} \
                   || echo ${BASH_SOURCE[0]}`")"

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

I was experiencing this problem on Samsung devices (fine on others). like zyamys suggested in his/her comment, I added the manifest.permission line but in addition to rather than instead of the original line, so:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.Manifest.permission.READ_PHONE_STATE" />

I'm targeting API 22, so don't need to explicitly ask for permissions.

proper name for python * operator?

I say "star-args" and Python people seem to know what i mean.

** is trickier - I think just "qargs" since it is usually used as **kw or **kwargs

Failed to load resource under Chrome

Check the network tab to see if Chrome failed to download any resource file.

What is the difference between dim and set in vba

According to VBA help on SET statement it sets a reference to an object.so if you change a property the actual object will also changes.

Dim newObj as Object
Set var1=Object1(same type as Object)
Set var2=Object1(same type as Object)
Set var3=Object1(same type as Object)
Set var4=Object1(same type as Object)
Var1.property1=NewPropertyValue

the other Vars properties also changes,so:

Var1.property1=Var2.property1=Var3.property1=Var4.property1=Object1.Property1=NewpropertyValue`

actualy all vars are the same!

How to add style from code behind?

If no file available for download, I needed to disable the asp:linkButton, change it to grey and eliminate the underline on the hover. This worked:

.disabled {
    color: grey;
    text-decoration: none !important;
}

LinkButton button = item.FindControl("lnkFileDownload") as LinkButton;
button.Enabled = false;
button.CssClass = "disabled";

CSS Positioning Elements Next to each other

If you want them to be displayed side by side, why is sideContent the child of mainContent? make them siblings then use:

float:left; display:inline; width: 49%;

on both of them.

#mainContent, #sideContent {float:left; display:inline; width: 49%;}

How to disable margin-collapsing?

I had similar problem with margin collapse because of parent having position set to relative. Here are list of commands you can use to disable margin collapsing.

HERE IS PLAYGROUND TO TEST

Just try to assign any parent-fix* class to div.container element, or any class children-fix* to div.margin. Pick the one that fits your needs best.

When

  • margin collapsing is disabled, div.absolute with red background will be positioned at the very top of the page.
  • margin is collapsing div.absolute will be positioned at the same Y coordinate as div.margin

_x000D_
_x000D_
html, body { margin: 0; padding: 0; }_x000D_
_x000D_
.container {_x000D_
  width: 100%;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.absolute {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 50px;_x000D_
  right: 50px;_x000D_
  height: 100px;_x000D_
  border: 5px solid #F00;_x000D_
  background-color: rgba(255, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
.margin {_x000D_
  width: 100%;_x000D_
  height: 20px;_x000D_
  background-color: #444;_x000D_
  margin-top: 50px;_x000D_
  color: #FFF;_x000D_
}_x000D_
_x000D_
/* Here are some examples on how to disable margin _x000D_
   collapsing from within parent (.container) */_x000D_
.parent-fix1 { padding-top: 1px; }_x000D_
.parent-fix2 { border: 1px solid rgba(0,0,0, 0);}_x000D_
.parent-fix3 { overflow: auto;}_x000D_
.parent-fix4 { float: left;}_x000D_
.parent-fix5 { display: inline-block; }_x000D_
.parent-fix6 { position: absolute; }_x000D_
.parent-fix7 { display: flex; }_x000D_
.parent-fix8 { -webkit-margin-collapse: separate; }_x000D_
.parent-fix9:before {  content: ' '; display: table; }_x000D_
_x000D_
/* Here are some examples on how to disable margin _x000D_
   collapsing from within children (.margin) */_x000D_
.children-fix1 { float: left; }_x000D_
.children-fix2 { display: inline-block; }
_x000D_
<div class="container parent-fix1">_x000D_
  <div class="margin children-fix">margin</div>_x000D_
  <div class="absolute"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here is jsFiddle with example you can edit

Merging 2 branches together in GIT

merge is used to bring two (or more) branches together.

a little example:

# on branch A:
# create new branch B
$ git checkout -b B
# hack hack
$ git commit -am "commit on branch B"

# create new branch C from A
$ git checkout -b C A
# hack hack
$ git commit -am "commit on branch C"

# go back to branch A
$ git checkout A
# hack hack
$ git commit -am "commit on branch A"

so now there are three separate branches (namely A B and C) with different heads

to get the changes from B and C back to A, checkout A (already done in this example) and then use the merge command:

# create an octopus merge
$ git merge B C

your history will then look something like this:

…-o-o-x-------A
      |\     /|
      | B---/ |
       \     /
        C---/

if you want to merge across repository/computer borders, have a look at git pull command, e.g. from the pc with branch A (this example will create two new commits):

# pull branch B
$ git pull ssh://host/… B
# pull branch C
$ git pull ssh://host/… C

How to create a POJO?

According to Martin Fowler

The term was coined while Rebecca Parsons, Josh MacKenzie and I were preparing for a talk at a conference in September 2000. In the talk, we were pointing out the many benefits of encoding business logic into regular java objects rather than using Entity Beans. We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it’s caught on very nicely.

Generally, a POJO is not bound to any restriction and any Java object can be called a POJO but there are some directions. A well-defined POJO should follow below directions.

  1. Each variable in a POJO should be declared as private.
  2. Default constructor should be overridden with public accessibility.
  3. Each variable should have its Setter-Getter method with public accessibility.
  4. Generally POJO should override equals(), hashCode() and toString() methods of Object (but it's not mandatory).
  5. Overriding compare() method of Comparable interface used for sorting (Preferable but not mandatory).

And according to Java Language Specification, a POJO should not have to

  1. Extend pre-specified classes
  2. Implement pre-specified interfaces
  3. Contain pre-specified annotations

However, developers and frameworks describe a POJO still requires the use prespecified annotations to implement features like persistence, declarative transaction management etc. So the idea is that if the object was a POJO before any annotations were added would return to POJO status if the annotations are removed then it can still be considered a POJO.

A JavaBean is a special kind of POJO that is Serializable, has a no-argument constructor, and allows access to properties using getter and setter methods that follow a simple naming convention.

Read more on Plain Old Java Object (POJO) Explained.

div background color, to change onhover

simply try "hover" property of CSS. eg:

<html>
<head>
    <style>
        div
        {
            height:100px;
            width:100px;
            border:2px solid red;
        }
        div:hover
        {
            background-color:yellow;
        }
    </style>
</head>
<body>
            <a href="#">
                      <div id="ab">
                                <p> hello there </p>
                      </div>
            </a>
</body>

i hope this will help

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html, css, js etc.

A fact that makes this more confusing is that npm provides some packages which can be used in front-end development as well, like grunt and jshint.

These lines add more meaning

Bower, unlike npm, can have multiple files (e.g. .js, .css, .html, .png, .ttf) which are considered the main file(s). Bower semantically considers these main files, when packaged together, a component.

Edit: Grunt is quite different from Npm and Bower. Grunt is a javascript task runner tool. You can do a lot of things using grunt which you had to do manually otherwise. Highlighting some of the uses of Grunt:

  1. Zipping some files (e.g. zipup plugin)
  2. Linting on js files (jshint)
  3. Compiling less files (grunt-contrib-less)

There are grunt plugins for sass compilation, uglifying your javascript, copy files/folders, minifying javascript etc.

Please Note that grunt plugin is also an npm package.

Question-1

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

It really depends where does this package belong to. If it is a node module(like grunt,request) then it will go in package.json otherwise into bower json.

Question-2

When should I ever install packages explicitly like that without adding them to the file that manages dependencies

It does not matter whether you are installing packages explicitly or mentioning the dependency in .json file. Suppose you are in the middle of working on a node project and you need another project, say request, then you have two options:

  • Edit the package.json file and add a dependency on 'request'
  • npm install

OR

  • Use commandline: npm install --save request

--save options adds the dependency to package.json file as well. If you don't specify --save option, it will only download the package but the json file will be unaffected.

You can do this either way, there will not be a substantial difference.

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

I haven't figure out the reason but reinstalling the .pfx certificate(both in current user and local machine) works for me.

How to calculate difference between two dates in oracle 11g SQL

Oracle support Mathematical Subtract - operator on Data datatype. You may directly put in select clause following statement:

to_char (s.last_upd – s.created, ‘999999D99')

Check the EXAMPLE for more visibility.

In case you need the output in termes of hours, then the below might help;

Select to_number(substr(numtodsinterval([END_TIME]-[START_TIME]),’day’,2,9))*24 +
to_number(substr(numtodsinterval([END_TIME]-[START_TIME],’day’),12,2))
||':’||to_number(substr(numtodsinterval([END_TIME]-[START_TIME],’day’),15,2)) 
from [TABLE_NAME];

Eclipse Error: "Failed to connect to remote VM"

NOTE: For glassfish Server login via admin console -> Configurations -> server-config -> JVM-settings. * Remember to check Enable checkbox for Debug. Now Note the address, this address will be used in port of eclipse Remote Java Application Debug.Check the snap shot in glassfish server here

JUnit 4 compare Sets

with hamcrest:

assertThat(s1, is(s2));

with plain assert:

assertEquals(s1, s2);

NB:t the equals() method of the concrete set class is used

Sublime text 3. How to edit multiple lines?

Thank you for all answers! I found it! It calls "Column selection (for Sublime)" and "Column Mode Editing (for Notepad++)" https://www.sublimetext.com/docs/3/column_selection.html

Change Placeholder Text using jQuery

working example of dynamic placeholder using Javascript and Jquery http://jsfiddle.net/ogk2L14n/1/

<input type="text" id="textbox">
 <select id="selection" onchange="changeplh()">
     <option>one</option>
     <option>two</option>
     <option>three</option>
    </select>

function changeplh(){
    debugger;
 var sel = document.getElementById("selection");
    var textbx = document.getElementById("textbox");
    var indexe = sel.selectedIndex;

    if(indexe == 0) { 
     $("#textbox").attr("placeholder", "age");

}
       if(indexe == 1) { 
     $("#textbox").attr("placeholder", "name");
}
}

Set background image on grid in WPF using C#

In order to avoid path problem, you can simply try this, just keep background image in images folder and add this code

<Grid>
  <Grid.Background>
    <ImageBrush Stretch="Fill" ImageSource="..\Images\background.jpg"
                AlignmentY="Top" AlignmentX="Center"/>
  </Grid.Background>
</Grid>

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

You can go to File -> Preferences -> Keyboard Shortcut. Once you are there, you can search for navigate. Then, you will see all shortcuts set for your VS Code environment related to navigation. In my case, it was only Alt + '-' to get my cursor back.

IndexError: list index out of range and python

In Python, indexing starts at 0. Therefore, if you have a list with 53 items, list[52] will be the last item in the list.

How to change the Spyder editor background to dark?

Yes, that's the intuitive answer. Nothing in Spyder is intuitive. Go to Preferences/Editor and select the scheme you want. Then go to Preferences/Syntax Coloring and adjust the colors if you want to. tcebob

Removing duplicates from a String in Java

Oldschool way (as we wrote such a tasks in Apple ][ Basic, adapted to Java):

int i,j;
StringBuffer str=new StringBuffer();
Scanner in = new Scanner(System.in);
System.out.print("Enter string: ");
str.append(in.nextLine());

for (i=0;i<str.length()-1;i++){
    for (j=i+1;j<str.length();j++){
        if (str.charAt(i)==str.charAt(j))
            str.deleteCharAt(j);
    }
}
System.out.println("Removed non-unique symbols: " + str);

Using '<%# Eval("item") %>'; Handling Null Value and showing 0 against

I don't know ASP.NET very well, but can you use the ternary operator?

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

Something like: (x=Eval("item")) == Null ? 0 : x

Format date and time in a Windows batch script

For a very simple solution for numeric date for use in filenames use the following code:

set month=%date:~4,2%
set day=%date:~7,2%
set curTimestamp=%month%%day%%year%

rem then the you can add a prefix and a file extension easily like this
echo updates%curTimestamp%.txt

Where does MySQL store database files on Windows and what are the names of the files?

For Windows 7: c:\users\all users\MySql\MySql Server x.x\Data\

Where x.x is the version number of the sql server installed in your machine.

Fidel

Is there a better jQuery solution to this.form.submit();?

this.form.submit();

This is probably your best bet. Especially if you are not already using jQuery in your project, there is no need to add it (or any other JS library) just for this purpose.

create table in postgreSQL

Please try this:

CREATE TABLE article (
  article_id bigint(20) NOT NULL serial,
  article_name varchar(20) NOT NULL,
  article_desc text NOT NULL,
  date_added datetime default NULL,
  PRIMARY KEY (article_id)
);

Integration Testing POSTing an entire object to Spring MVC controller

One of the main purposes of integration testing with MockMvc is to verify that model objects are correclty populated with form data.

In order to do it you have to pass form data as they're passed from actual form (using .param()). If you use some automatic conversion from NewObject to from data, your test won't cover particular class of possible problems (modifications of NewObject incompatible with actual form).

Is there a list of screen resolutions for all Android based phones and tablets?

These are the sizes. Try to take a look in Supporting Mutiple Screens

320dp: a typical phone screen (240x320 ldpi, 320x480 mdpi, 480x800 hdpi, etc).
480dp: a tweener tablet like the Streak (480x800 mdpi).
600dp: a 7” tablet (600x1024 mdpi).
720dp: a 10” tablet (720x1280 mdpi, 800x1280 mdpi, etc).

I use this to make more than one layout:

res/layout/main_activity.xml           # For handsets (smaller than 600dp available width)
res/layout-sw600dp/main_activity.xml   # For 7” tablets (600dp wide and bigger)
res/layout-sw720dp/main_activity.xml   # For 10” tablets (720dp wide and bigger)

Better way to set distance between flexbox items

The negative margin trick on the box container works just great. Here is another example working great with order, wrapping and what not.

_x000D_
_x000D_
.container {_x000D_
   border: 1px solid green;_x000D_
   width: 200px;_x000D_
   display: inline-block;_x000D_
}_x000D_
_x000D_
#box {_x000D_
  display: flex;_x000D_
  flex-wrap: wrap-reverse;_x000D_
  margin: -10px;_x000D_
  border: 1px solid red;_x000D_
}_x000D_
.item {_x000D_
  flex: 1 1 auto;_x000D_
  order: 1;_x000D_
  background: gray;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
  margin: 10px;_x000D_
  border: 1px solid blue;_x000D_
}_x000D_
.first {_x000D_
  order: 0;_x000D_
}
_x000D_
<div class=container>_x000D_
<div id='box'>_x000D_
  <div class='item'>1</div>_x000D_
  <div class='item'>2</div>_x000D_
  <div class='item first'>3*</div>_x000D_
  <div class='item'>4</div>_x000D_
  <div class='item'>5</div>_x000D_
</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

syntax error: unexpected token <

I was also having syntax error: unexpected token < while posting a form via ajax. Then I used curl to see what it returns:

curl -X POST --data "firstName=a&lastName=a&[email protected]&pass=aaaa&mobile=12345678901&nID=123456789123456789&age=22&prof=xfd" http://handymama.co/CustomerRegistration.php

I got something like this as a response:

<br />
<b>Warning</b>:  Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>3</b><br />
<br />
<b>Warning</b>:  Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>4</b><br />
<br />
<b>Warning</b>:  Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>7</b><br />
<br />
<b>Warning</b>:  Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>8</b><br />

So all I had to do is just change the log level to only errors rather than warning.

error_reporting(E_ERROR);

"OverflowError: Python int too large to convert to C long" on windows but not mac

Could anyone help explain why

In Python 2 a python "int" was equivalent to a C long. In Python 3 an "int" is an arbitrary precision type but numpy still uses "int" it to represent the C type "long" when creating arrays.

The size of a C long is platform dependent. On windows it is always 32-bit. On unix-like systems it is normally 32 bit on 32 bit systems and 64 bit on 64 bit systems.

or give a solution for the code on windows? Thanks so much!

Choose a data type whose size is not platform dependent. You can find the list at https://docs.scipy.org/doc/numpy/reference/arrays.scalars.html#arrays-scalars-built-in the most sensible choice would probably be np.int64

How does database indexing work?

Simple Description!

The index is nothing but a data structure that stores the values for a specific column in a table. An index is created on a column of a table.

Example: We have a database table called User with three columns – Name, Age and Address. Assume that the User table has thousands of rows.

Now, let’s say that we want to run a query to find all the details of any users who are named 'John'. If we run the following query:

SELECT * FROM User 
WHERE Name = 'John'

The database software would literally have to look at every single row in the User table to see if the Name for that row is ‘John’. This will take a long time.

This is where index helps us: index is used to speed up search queries by essentially cutting down the number of records/rows in a table that needs to be examined.

How to create an index:

CREATE INDEX name_index
ON User (Name)

An index consists of column values(Eg: John) from one table, and those values are stored in a data structure.

So now the database will use the index to find employees named John because the index will presumably be sorted alphabetically by the Users name. And, because it is sorted, it means searching for a name is a lot faster because all names starting with a “J” will be right next to each other in the index!

jQuery get value of selected radio button

Get all radios:

var radios = $("input[type='radio']");

Filter to get the one that's checked

radios.filter(":checked");

OR

Another way you can find radio button value

var RadeoButtonStatusCheck = $('form input[type=radio]:checked').val();

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

Another option is to use the Apache Maven Shade Plugin: This plugin provides the capability to package the artifact in an uber-jar, including its dependencies and to shade - i.e. rename - the packages of some of the dependencies.

add this to your build plugins section

<plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-shade-plugin</artifactId>
</plugin>

querySelectorAll with multiple conditions

Is it possible to make a search by querySelectorAll using multiple unrelated conditions?

Yes, because querySelectorAll accepts full CSS selectors, and CSS has the concept of selector groups, which lets you specify more than one unrelated selector. For instance:

var list = document.querySelectorAll("form, p, legend");

...will return a list containing any element that is a form or p or legend.

CSS also has the other concept: Restricting based on more criteria. You just combine multiple aspects of a selector. For instance:

var list = document.querySelectorAll("div.foo");

...will return a list of all div elements that also (and) have the class foo, ignoring other div elements.

You can, of course, combine them:

var list = document.querySelectorAll("div.foo, p.bar, div legend");

...which means "Include any div element that also has the foo class, any p element that also has the bar class, and any legend element that's also inside a div."

How to call a JavaScript function within an HTML body

Try wrapping the createtable(); statement in a <script> tag:

<table>
        <tr>
            <th>Balance</th>
            <th>Fee</th>

        </tr>
        <script>createtable();</script>
</table>

I would avoid using document.write() and use the DOM if I were you though.

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

One possible explanation is a database trigger that fires for each DROP TABLE statement. To find the trigger, query the _TRIGGERS dictionary views:

select * from all_triggers
where trigger_type in ('AFTER EVENT', 'BEFORE EVENT')

disable any suspicious trigger with

   alter trigger <trigger_name> disable;

and try re-running your DROP TABLE statement

Eclipse error: "The import XXX cannot be resolved"

In my case, I imported a project which has been written on a classmate laptop, the problem is that he was using Java 11 and I was using Java 8, so the project had JDK 11 in it's build path, so I was unable even to import java classes (date, collection,...). So what I've done to solve the problem, is to delete the path of JDK11 and add the my JDK8 path.

Steps:

  1. Click on project on the menu bar then properties
  2. Choose the libraries tab
  3. Click on classpath then on add library from the sidebar
  4. Choose the corresponding library to add (remove older ones)

Execute Insert command and return inserted Id in Sql

The following solution will work with sql server 2005 and above. You can use output to get the required field. inplace of id you can write your key that you want to return. do it like this

FOR SQL SERVER 2005 and above

    using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ) output INSERTED.ID VALUES(@na,@occ)",con))
    {
        cmd.Parameters.AddWithValue("@na", Mem_NA);
        cmd.Parameters.AddWithValue("@occ", Mem_Occ);
        con.Open();

        int modified =(int)cmd.ExecuteScalar();

        if (con.State == System.Data.ConnectionState.Open) 
            con.Close();

        return modified;
    }
}

FOR previous versions

    using(SqlCommand cmd=new SqlCommand("INSERT INTO Mem_Basic(Mem_Na,Mem_Occ)  VALUES(@na,@occ);SELECT SCOPE_IDENTITY();",con))
    {
        cmd.Parameters.AddWithValue("@na", Mem_NA);
        cmd.Parameters.AddWithValue("@occ", Mem_Occ);
        con.Open();

        int modified = Convert.ToInt32(cmd.ExecuteScalar());

        if (con.State == System.Data.ConnectionState.Open) con.Close();
            return modified;
    }
}

How to place the "table" at the middle of the webpage?

Try this :

<style type="text/css">
        .myTableStyle
        {
           position:absolute;
           top:50%;
           left:50%; 

            /*Alternatively you could use: */
           /*
              position: fixed;
               bottom: 50%;
               right: 50%;
           */


        }
    </style>

Resize image with javascript canvas (smoothly)

Based on K3N answer, I rewrite code generally for anyone wants

var oc = document.createElement('canvas'), octx = oc.getContext('2d');
    oc.width = img.width;
    oc.height = img.height;
    octx.drawImage(img, 0, 0);
    while (oc.width * 0.5 > width) {
       oc.width *= 0.5;
       oc.height *= 0.5;
       octx.drawImage(oc, 0, 0, oc.width, oc.height);
    }
    oc.width = width;
    oc.height = oc.width * img.height / img.width;
    octx.drawImage(img, 0, 0, oc.width, oc.height);

UPDATE JSFIDDLE DEMO

Here is my ONLINE DEMO

How to get All input of POST in Laravel

You can use it

$params = request()->all();

without

import Illuminate\Http\Request OR

use Illuminate\Support\Facades\Request OR other.

git pull displays "fatal: Couldn't find remote ref refs/heads/xxxx" and hangs up

I just ran into a similar issue when I tried to commit to a newly created repo with a "." in it's name. I've seen several others have different issues with putting a "." in the repo name.

I just re-created the repo and

replaced "." with "-"

There may be other ways to resolve this, but this was a quick fix for me since it was a new repo.

How to include "zero" / "0" results in COUNT aggregate?

You must use LEFT JOIN instead of INNER JOIN

SELECT person.person_id, COUNT(appointment.person_id) AS "number_of_appointments"
FROM person 
LEFT JOIN appointment ON person.person_id = appointment.person_id
GROUP BY person.person_id;

warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777

This should resolve your problem: chmod go-w {/path/of/user}

Making a drop down list using swift?

Unfortunately if you're looking to apply UIPopoverController in iOS9, you'll get a deprecated class warning. Instead you need to set your desired view's UIModalPresentationPopover property to achieve the same result.

Popover

In a horizontally regular environment, a presentation style where the content is displayed in a popover view. The background content is dimmed and taps outside the popover cause the popover to be dismissed. If you do not want taps to dismiss the popover, you can assign one or more views to the passthroughViews property of the associated UIPopoverPresentationController object, which you can get from the popoverPresentationController property.

In a horizontally compact environment, this option behaves the same as UIModalPresentationFullScreen.

Available in iOS 8.0 and later.

Reference: https://developer.apple.com/documentation/uikit/uiviewcontroller/1621355-modalpresentationstyle

Android: Bitmaps loaded from gallery are rotated in ImageView

I improved upon the answer by Teo Inke. It no longer rotates the image unless it is actually necessary. It is also easier to read, and should run faster.

// Load Image
Bitmap bitmap = BitmapFactory.decodeFile(filePath);

// Rotate Image if Needed
try
{
    // Determine Orientation
    ExifInterface exif = new ExifInterface(filePath);
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, 1);

    // Determine Rotation
    int rotation = 0;
    if      (orientation == 6)      rotation = 90;
    else if (orientation == 3)      rotation = 180;
    else if (orientation == 8)      rotation = 270;

    // Rotate Image if Necessary
    if (rotation != 0)
    {
        // Create Matrix
        Matrix matrix = new Matrix();
        matrix.postRotate(rotation);

        // Rotate Bitmap
        Bitmap rotated = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true); 

        // Pretend none of this ever happened!
        bitmap.recycle();
        bitmap = rotated;
        rotated = null;
     }
}
catch (Exception e)
{
    // TODO: Log Error Messages Here
}

// TODO: Use Result Here
xxx.setBitmap(bitmap);

How do I serialize a C# anonymous type to a JSON string?

Please note this is from 2008. Today I would argue that the serializer should be built in and that you can probably use swagger + attributes to inform consumers about your endpoint and return data.


Iwould argue that you shouldn't be serializing an anonymous type. I know the temptation here; you want to quickly generate some throw-away types that are just going to be used in a loosely type environment aka Javascript in the browser. Still, I would create an actual type and decorate it as Serializable. Then you can strongly type your web methods. While this doesn't matter one iota for Javascript, it does add some self-documentation to the method. Any reasonably experienced programmer will be able to look at the function signature and say, "Oh, this is type Foo! I know how that should look in JSON."

Having said that, you might try JSON.Net to do the serialization. I have no idea if it will work

How to add comments into a Xaml file in WPF?

I assume those XAML namespace declarations are in the parent tag of your control? You can't put comments inside of another tag. Other than that, the syntax you're using is correct.

<UserControl xmlns="...">
    <!-- Here's a valid comment. Notice it's outside the <UserControl> tag's braces -->
    [..snip..]
</UserControl>

iReport not starting using JRE 8

With ireport 4.7.1, after setting jdkhome in etc/ireport.conf, ireport.exe doesn't start. No splash, no window.

When I launch ireport_w.exe in a cmd, I get this message:

Error occurred during initialization of VM

Could not reserve enough space for object heap

Error: Could not create the Java Virtual Machine.

Error: A fatal exception has occurred. Program will exit.

Solution: In file etc/ireport.conf, on the line starting with default_options, I have reduced the value of -J-XX:MaxPermSize to 256m instead of 512m

default_options="--branding ireport -J-Xms256m -J-Xmx512m
    -J-Dorg.netbeans.ProxyClassLoader.level=1000 -J-XX:MaxPermSize=256m"

How to convert array into comma separated string in javascript

The method array.toString() actually calls array.join() which result in a string concatenated by commas. ref

_x000D_
_x000D_
var array = ['a','b','c','d','e','f'];_x000D_
document.write(array.toString()); // "a,b,c,d,e,f"
_x000D_
_x000D_
_x000D_

Also, you can implicitly call Array.toString() by making javascript coerce the Array to an string, like:

//will implicitly call array.toString()
str = ""+array;
str = `${array}`;

Array.prototype.join()

The join() method joins all elements of an array into a string.

Arguments:

It accepts a separator as argument, but the default is already a comma ,

str = arr.join([separator = ','])

Examples:

var array = ['A', 'B', 'C'];
var myVar1 = array.join();      // 'A,B,C'
var myVar2 = array.join(', ');  // 'A, B, C'
var myVar3 = array.join(' + '); // 'A + B + C'
var myVar4 = array.join('');    // 'ABC'

Note:

If any element of the array is undefined or null , it is treated as an empty string.

Browser support:

It is available pretty much everywhere today, since IE 5.5 (1999~2000).

References

Extract a substring from a string in Ruby using a regular expression

"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"

No need to use scan, if we need only one result.
No need to use Python's match, when we have Ruby's String[regexp,#].

See: http://ruby-doc.org/core/String.html#method-i-5B-5D

Note: str[regexp, capture] ? new_str or nil

What is the difference between null=True and blank=True in Django?

null - default is False if True, Django will store empty as null in the database.

blank - default is False if true that field is allowed to be blank

more, goto https://docs.djangoproject.com/en/3.0/topics/db/models/

How to connect access database in c#

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

this.Controls.Add(dataGridView1);

By the way the code is a bit confused

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

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

 SELECT field_names_list FROM _tablename_

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

 string sql  = "SELECT * FROM Clients";

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

how to display progress while loading a url to webview in android?

You will have to over ride onPageStarted and onPageFinished callbacks

mWebView.setWebViewClient(new WebViewClient() {

        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if (progressBar!= null && progressBar.isShowing()) {
                progressBar.dismiss();
            }
            progressBar = ProgressDialog.show(WebViewActivity.this, "Application Name", "Loading...");
        }

        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);

            return true;
        }

        public void onPageFinished(WebView view, String url) {
            if (progressBar.isShowing()) {
                progressBar.dismiss();
            }
        }

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            alertDialog.setTitle("Error");
            alertDialog.setMessage(description);
            alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    return;
                }
            });
            alertDialog.show();
        }
    });

How do I count the number of rows and columns in a file using bash?

awk 'BEGIN{FS=","}END{print "COLUMN NO: "NF " ROWS NO: "NR}' file

You can use any delimiter as field separator and can find numbers of ROWS and columns

Loading context in Spring using web.xml

You can also specify context location relatively to current classpath, which may be preferable

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:applicationContext*.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

How to get instance variables in Python?

Every object has a __dict__ variable containing all the variables and its values in it.

Try this

>>> hi_obj = hi()
>>> hi_obj.__dict__.keys()

What's the difference between "git reset" and "git checkout"?

One simple use case when reverting change:
1. Use reset if you want to undo staging of a modified file.
2. Use checkout if you want to discard changes to unstaged file/s.

Difference between final and effectively final

If you could add the final modifier to a local variable, it was effectively final.

Lambda expressions can access

  • static variables,

  • instance variables,

  • effectively final method parameters, and

  • effectively final local variables.

Source: OCP: Oracle Certified Professional Java SE 8 Programmer II Study Guide, Jeanne Boyarsky, Scott Selikoff

Additionally,

An effectively final variable is a variable whose value is never changed, but it isn’t declared with the final keyword.

Source: Starting Out with Java: From Control Structures through Objects (6th Edition), Tony Gaddis

Furthermore, don't forget the meaning of final that it is initialized exactly once before it is used for the first time.

Rails Model find where not equal

Rails 4

GroupUser.where.not(user_id: me)

How to compare DateTime without time via LINQ?

The .Date answer is misleading since you get the error mentioned before. Another way to compare, other than mentioned DbFunctions.TruncateTime, may also be:

DateTime today = DateTime.Now.date;
var q = db.Games.Where(t => SqlFunctions.DateDiff("dayofyear", today, t.StartDate) <= 0
      && SqlFunctions.DateDiff("year", today, t.StartDate) <= 0)

It looks better(more readable) in the generated SQL query. But I admit it looks worse in the C# code XD. I was testing something and it seemed like TruncateTime was not working for me unfortunately the fault was between keyboard and chair, but in the meantime I found this alternative.

How to add a delay for a 2 or 3 seconds

Use a timer with an interval set to 2–3 seconds.

You have three different options to choose from, depending on which type of application you're writing:

  1. System.Timers.Timer
  2. System.Windows.Forms.Timer
  3. System.Threading.Timer

Don't use Thread.Sleep if your application need to process any inputs on that thread at the same time (WinForms, WPF), as Sleep will completely lock up the thread and prevent it from processing other messages. Assuming a single-threaded application (as most are), your entire application will stop responding, rather than just delaying an operation as you probably intended. Note that it may be fine to use Sleep in pure console application as there are no "events" to handle or on separate thread (also Task.Delay is better option).

In addition to timers and Sleep you can use Task.Delay which is asynchronous version of Sleep that does not block thread from processing events (if used properly - don't turn it into infinite sleep with .Wait()).

 public async void ClickHandler(...)
 {
      // whatever you need to do before delay goes here         

      await Task.Delay(2000);

      // whatever you need to do after delay.
 }

The same await Task.Delay(2000) can be used in a Main method of a console application if you use C# 7.1 (Async main on MSDN blogs).

Note: delaying operation with Sleep has benefit of avoiding race conditions that comes from potentially starting multiple operations with timers/Delay. Unfortunately freezing UI-based application is not acceptable so you need to think about what will happen if you start multiple delays (i.e. if it is triggered by a button click) - consider disabling such button, or canceling the timer/task or making sure delayed operation can be done multiple times safely.

How to handle Pop-up in Selenium WebDriver using Java

When the toastr message poped up on the screen of firefox. the below tag was displayed in fire bug.

<div class="toast-message">Invalid Credentials, Please check Password</div>.

I took the screenshot at that time. And did the below changes in selenium java code.

String alertText = "";
WebDriverWait wait = new WebDriverWait(driver, 5);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.className("toast-message")));
WebElement toast1 = driver.findElement(By.className("toast-message"));  
alertText = toast1.getText();
System.out.println( alertText);

And my issue of toastr popup got resolved.

WebAPI to Return XML

If you don't want the controller to decide the return object type, you should set your method return type as System.Net.Http.HttpResponseMessage and use the below code to return the XML.

public HttpResponseMessage Authenticate()
{
  //process the request 
  .........

  string XML="<note><body>Message content</body></note>";
  return new HttpResponseMessage() 
  { 
    Content = new StringContent(XML, Encoding.UTF8, "application/xml") 
  };
}

This is the quickest way to always return XML from Web API.

jQuery - Appending a div to body, the body is the object?

    $('body').append($('<div/>', {
        id: 'holdy' 
    }));

SQL join format - nested inner joins

For readability, I restructured the query... starting with the apparent top-most level being Table1, which then ties to Table3, and then table3 ties to table2. Much easier to follow if you follow the chain of relationships.

Now, to answer your question. You are getting a large count as the result of a Cartesian product. For each record in Table1 that matches in Table3 you will have X * Y. Then, for each match between table3 and Table2 will have the same impact... Y * Z... So your result for just one possible ID in table 1 can have X * Y * Z records.

This is based on not knowing how the normalization or content is for your tables... if the key is a PRIMARY key or not..

Ex:
Table 1       
DiffKey    Other Val
1          X
1          Y
1          Z

Table 3
DiffKey   Key    Key2  Tbl3 Other
1         2      6     V
1         2      6     X
1         2      6     Y
1         2      6     Z

Table 2
Key    Key2   Other Val
2      6      a
2      6      b
2      6      c
2      6      d
2      6      e

So, Table 1 joining to Table 3 will result (in this scenario) with 12 records (each in 1 joined with each in 3). Then, all that again times each matched record in table 2 (5 records)... total of 60 ( 3 tbl1 * 4 tbl3 * 5 tbl2 )count would be returned.

So, now, take that and expand based on your 1000's of records and you see how a messed-up structure could choke a cow (so-to-speak) and kill performance.

SELECT
      COUNT(*)
   FROM
      Table1 
         INNER JOIN Table3
            ON Table1.DifferentKey = Table3.DifferentKey
            INNER JOIN Table2
               ON Table3.Key =Table2.Key
               AND Table3.Key2 = Table2.Key2 

axios post request to send form data

You can post axios data by using FormData() like:

var bodyFormData = new FormData();

And then add the fields to the form you want to send:

bodyFormData.append('userName', 'Fred');

If you are uploading images, you may want to use .append

bodyFormData.append('image', imageFile); 

And then you can use axios post method (You can amend it accordingly)

axios({
  method: "post",
  url: "myurl",
  data: bodyFormData,
  headers: { "Content-Type": "multipart/form-data" },
})
  .then(function (response) {
    //handle success
    console.log(response);
  })
  .catch(function (response) {
    //handle error
    console.log(response);
  });

Related GitHub issue:

Can't get a .post with 'Content-Type': 'multipart/form-data' to work @ axios/axios

Return background color of selected cell

You can use Cell.Interior.Color, I've used it to count the number of cells in a range that have a given background color (ie. matching my legend).

Error - SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM

DateTime.MinValue and DateTime.MaxValue

DateTime.MinValue = 1/1/0001 12:00:00 AM

DateTime.MaxValue = 23:59:59.9999999, December 31, 9999, 

                exactly one 100-nanosecond tick 

                before 00:00:00, January 1, 10000 

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

If you want this behaviour everywhere in your app and don't want to add anything to individual viewDidAppear etc. then you should create a subclass

class QFNavigationController:UINavigationController, UIGestureRecognizerDelegate, UINavigationControllerDelegate{
    override func viewDidLoad() {
        super.viewDidLoad()
        interactivePopGestureRecognizer?.delegate = self
        delegate = self
    }

    override func pushViewController(_ viewController: UIViewController, animated: Bool) {
        super.pushViewController(viewController, animated: animated)
        interactivePopGestureRecognizer?.isEnabled = false
    }

    func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
        interactivePopGestureRecognizer?.isEnabled = true
    }

    // IMPORTANT: without this if you attempt swipe on
    // first view controller you may be unable to push the next one
    func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
        return viewControllers.count > 1
    }

}

Now, whenever you use QFNavigationController you get the desired experience.

Build not visible in itunes connect

Check your email. You should have issue or missing report on you email. I got email that I miss NSCameraUsageDescription key in Info.plist

enter image description here

Center HTML Input Text Field Placeholder

You can use set in a class like below and set to input text class
CSS:

 .place-holder-center::placeholder {
        text-align: center;
    }

HTML:

<input type="text" class="place-holder-center">

How to install plugin for Eclipse from .zip

It depends on what the zip contains. Take a look to see if it got content.jar and artifacts.jar. If it does, it is an archived updated site. Install from it the same way as you install from a remote site.

If the zip doesn't contain content.jar and artifacts.jar, go to your Eclipse install's dropins directory, create a subfolder (name doesn't matter) and expand your zip into that folder. Restart Eclipse.

Verilog: How to instantiate a module

This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.

The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  clk, rst_n, data_rx_1, data_tx ); 

endmodule

This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.

This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.

module subcomponent(
  input        rst_n,       
  input        clk,
  ...

It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) ); 

endmodule

This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.

Giving each port its own line and indenting correctly adds to the readability and code quality.

subcomponent subcomponent_instance_name (
  .clk      ( clk       ), // input
  .rst_n    ( rst_n     ), // input
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:

clk_gen( 
  .clk      ( clk_sub   ), // output
  .en       ( enable    )  // input

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:

Note that the instance name for the second component has been changed

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.

wire [9:0] data_temp
subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.

Use .port with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk,                    // input **Auto connect**
  .rst_n,                  // input **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

endmodule

This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.

Another trick that I think is even worse than the one above is .* which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.

subcomponent subcomponent_instance_name (
  .*,                      // **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.

Python - Get Yesterday's date as a string in YYYY-MM-DD format

>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'

Flatten nested dictionaries, compressing keys

Using generators:

def flat_dic_helper(prepand,d):
    if len(prepand) > 0:
        prepand = prepand + "_"
    for k in d:
        i=d[k]
        if type(i).__name__=='dict':
            r = flat_dic_helper(prepand+k,i)
            for j in r:
                yield j
        else:
            yield (prepand+k,i)

def flat_dic(d): return dict(flat_dic_helper("",d))

d={'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3]}
print(flat_dic(d))


>> {'a': 1, 'c_a': 2, 'c_b_x': 5, 'd': [1, 2, 3], 'c_b_y': 10}

MacOSX homebrew mysql root password

Terminal 1:

$ mysql_safe

Terminal 2:

$ mysql -u root
mysql> UPDATE mysql.user SET Password=PASSWORD('new-password') WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> quit

python socket.error: [Errno 98] Address already in use

There is obviously another process listening on the port. You might find out that process by using the following command:

$ lsof -i :8000

or change your tornado app's port. tornado's error info not Explicitly on this.

Sleeping in a batch file

Even more lightweight than the Python solution is a Perl one-liner.

To sleep for seven seconds put this in the BAT script:

perl -e "sleep 7"

This solution only provides a resolution of one second.

If you need higher resolution then use the Time::HiRes module from CPAN. It provides usleep() which sleeps in microseconds and nanosleep() which sleeps in nanoseconds (both functions takes only integer arguments). See the Stack Overflow question How do I sleep for a millisecond in Perl? for further details.

I have used ActivePerl for many years. It is very easy to install.

jQuery - Detect value change on hidden input field

Since hidden input does not trigger "change" event on change, I used MutationObserver to trigger this instead.

(Sometimes hidden input value changes are done by some other scripts you can't modify)

This does not work in IE10 and below

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var trackChange = function(element) {
  var observer = new MutationObserver(function(mutations, observer) {
    if(mutations[0].attributeName == "value") {
        $(element).trigger("change");
    }
  });
  observer.observe(element, {
    attributes: true
  });
}

// Just pass an element to the function to start tracking
trackChange( $("input[name=foo]")[0] );

Jackson - Deserialize using generic class

You can wrap it in another class which knows the type of your generic type.

Eg,

class Wrapper {
 private Data<Something> data;
}
mapper.readValue(jsonString, Wrapper.class);

Here Something is a concrete type. You need a wrapper per reified type. Otherwise Jackson does not know what objects to create.

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

If the link is to a valid file url, simply assigning window.location.href will work.

However, sometimes the link is not valid, and an iFrame is required.

Do your normal event.preventDefault to prevent the window from opening, and if you are using jQuery, this will work:

$('<iframe>').attr('src', downloadThing.attr('href')).appendTo('body').on("load", function() {
   $(this).remove();
});

How to get id from URL in codeigniter?

In codeigniter you can't pass parameters in the url as you are doing in core php.So remove the "?" and "product_id" and simply pass the id.If you want more security you can encrypt the id and pass it.

Remove all subviews?

In objective-C, go ahead and create a category method off of the UIView class.

- (void)removeAllSubviews
{
    for (UIView *subview in self.subviews)
        [subview removeFromSuperview];
}

Laravel 5.4 redirection to custom url after login

You should set $redirectTo value to route that you want redirect

$this->redirectTo = route('dashboard');

inside AuthController constructor.

/**
 * Where to redirect users after login / registration.
 *
 * @var string
 */
protected $redirectTo = '/';

/**
 * Create a new authentication controller instance.
 *
 * @return void
 */
public function __construct()
{
    $this->middleware($this->guestMiddleware(), ['except' => 'logout']);
    $this->redirectTo = route('dashboard');
}

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

I wrote a set of scripts that provides a uniform interface for both BSD and GNU version of date.

Follow command will output the Epoch seconds for the date 2010-10-02, and it works with both BSD and GNU version of date.

$ xsh /date/convert "2010-10-02" "+%s"
1286020263

It's an equivalent of the command with GNU version of date:

date -d "2010-10-02" "+%s"

and also the command with BSD version of date:

date -j -f "%F" 2010-10-02 "+%s"

The scripts can be found at:

It's a part of a library called xsh-lib/core. To use them you need both repos xsh and xsh-lib/core, I list them below:

How does the keyword "use" work in PHP and can I import classes with it?

Don’t overthink what a Namespace is.

Namespace is basically just a Class prefix (like directory in Operating System) to ensure the Class path uniqueness.

Also just to make things clear, the use statement is not doing anything only aliasing your Namespaces so you can use shortcuts or include Classes with the same name but different Namespace in the same file.

E.g:

// You can do this at the top of your Class
use Symfony\Component\Debug\Debug;

if ($_SERVER['APP_DEBUG']) {
    // So you can utilize the Debug class it in an elegant way
    Debug::enable();
    // Instead of this ugly one
    // \Symfony\Component\Debug\Debug::enable();
}

If you want to know how PHP Namespaces and autoloading (the old way as well as the new way with Composer) works, you can read the blog post I just wrote on this topic: https://enterprise-level-php.com/2017/12/25/the-magic-behind-autoloading-php-files-using-composer.html

sudo in php exec()

php: the bash console is created, and it executes 1st script, which call sudo to the second one, see below:

$dev = $_GET['device'];
$cmd = '/bin/bash /home/www/start.bash '.$dev;
echo $cmd;
shell_exec($cmd);
  1. /home/www/start.bash

    #!/bin/bash
    /usr/bin/sudo /home/www/myMount.bash $1
    
  2. myMount.bash:

    #!/bin/bash
    function error_exit
    {
      echo "Wrong parameter" 1>&2
      exit 1
    }
    ..........
    

oc, you want to run script from root level without root privileges, to do that create and modify the /etc/sudoers.d/mount file:

www-data ALL=(ALL:ALL) NOPASSWD:/home/www/myMount.bash

dont forget to chmod:

sudo chmod 0440 /etc/sudoers.d/mount

Input text dialog Android

@LukeTaylor: I currently have the same task at hand (creating a popup/dialog that contains an EditText)..
Personally, I find the fully-dynamic route to be somewhat limiting in terms of creativity.

FULLY CUSTOM DIALOG LAYOUT :

Rather than relying entirely upon Code to create the Dialog, you can fully customize it like so :

1) - Create a new Layout Resource file.. This will act as your Dialog, allowing for full creative freedom!
NOTE: Refer to the Material Design guidelines to help keep things clean and on point.

2) - Give ID's to all of your View elements.. In my example code below, I have 1 EditText, and 2 Buttons.

3) - Create an Activity with a Button, for testing purposes.. We'll have it inflate and launch your Dialog!

public void buttonClick_DialogTest(View view) {

    AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);

    //  Inflate the Layout Resource file you created in Step 1
    View mView = getLayoutInflater().inflate(R.layout.timer_dialog_layout, null);

    //  Get View elements from Layout file. Be sure to include inflated view name (mView)
    final EditText mTimerMinutes = (EditText) mView.findViewById(R.id.etTimerValue);
    Button mTimerOk = (Button) mView.findViewById(R.id.btnTimerOk);
    Button mTimerCancel = (Button) mView.findViewById(R.id.btnTimerCancel);

    //  Create the AlertDialog using everything we needed from above
    mBuilder.setView(mView);
    final AlertDialog timerDialog = mBuilder.create();

    //  Set Listener for the OK Button
    mTimerOk.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick (View view) {
            if (!mTimerMinutes.getText().toString().isEmpty()) {
                Toast.makeText(MainActivity.this, "You entered a Value!,", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(MainActivity.this, "Please enter a Value!", Toast.LENGTH_LONG).show();
            }
        }
    });

    //  Set Listener for the CANCEL Button
    mTimerCancel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick (View view) {
            timerDialog.dismiss();
        }
    });

    //  Finally, SHOW your Dialog!
    timerDialog.show();


    //  END OF buttonClick_DialogTest
}


Piece of cake! Full creative freedom! Just be sure to follow Material Guidelines ;)

I hope this helps someone! Let me know what you guys think!

PHP: Limit foreach() statement?

There are many ways, one is to use a counter:

$i = 0;
foreach ($arr as $k => $v) {
    /* Do stuff */
    if (++$i == 2) break;
}

Other way would be to slice the first 2 elements, this isn't as efficient though:

foreach (array_slice($arr, 0, 2) as $k => $v) {
    /* Do stuff */
}

You could also do something like this (basically the same as the first foreach, but with for):

for ($i = 0, reset($arr); list($k,$v) = each($arr) && $i < 2; $i++) {
}

What does "@" mean in Windows batch scripts

It inherits the meaning from DOS. @:

In DOS version 3.3 and later, hides the echo of a batch command. Any output generated by the command is echoed.

Without it, you could turn off command echoing using the echo off command, but that command would be echoed first.

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

I had this problem with an F# project that had been here and there between Visual Studio and MonoDevelop, perhaps originating in the latter (I forget). In VS, the optimize box was unchecked, yet optimization certainly seemed to be occuring as far as the debugger was concerned.

After comparing the XML of the project file against that of a healthy one, the problem was obvious: the healthy project had an explicit <optimize>false</optimize> line, whereas the bad one was missing it completely. VS was obviously inferring from its absence that optimization was disabled, while the compiler was doing the opposite.

The solution was to add this property to the project file, and reload.

Sending HTTP POST Request In Java

Call HttpURLConnection.setRequestMethod("POST") and HttpURLConnection.setDoOutput(true); Actually only the latter is needed as POST then becomes the default method.

Spring MVC Missing URI template variable

This error may happen when mapping variables you defined in REST definition do not match with @PathVariable names.

Example: Suppose you defined in the REST definition

@GetMapping(value = "/{appId}", produces = "application/json", consumes = "application/json")

Then during the definition of the function, it should be

public ResponseEntity<List> getData(@PathVariable String appId)

This error may occur when you use any other variable other than defined in the REST controller definition with @PathVariable. Like, the below code will raise the error as ID is different than appId variable name:

public ResponseEntity<List> getData(@PathVariable String ID)

Commenting out code blocks in Atom

Atom does not have a specific comment-block function, but if you select more rows and then use the normal ctrl-/ (Windows or Linux) cmd-/ (Mac), it will comment all the lines.

Cropping images in the browser BEFORE the upload

The Pixastic library does exactly what you want. However, it will only work on browsers that have canvas support. For those older browsers, you'll either need to:

  1. supply a server-side fallback, or
  2. tell the user that you're very sorry, but he'll need to get a more modern browser.

Of course, option #2 isn't very user-friendly. However, if your intent is to provide a pure client-only tool and/or you can't support a fallback back-end cropper (e.g. maybe you're writing a browser extension or offline Chrome app, or maybe you can't afford a decent hosting provider that provides image manipulation libraries), then it's probably fair to limit your user base to modern browsers.

EDIT: If you don't want to learn Pixastic, I have added a very simple cropper on jsFiddle here. It should be possible to modify and integrate and use the drawCroppedImage function with Jcrop.

Why are only final variables accessible in anonymous class?

Try this code,

Create Array List and put value inside that and return it :

private ArrayList f(Button b, final int a)
{
    final ArrayList al = new ArrayList();
    b.addClickHandler(new ClickHandler() {

         @Override
        public void onClick(ClickEvent event) {
             int b = a*5;
             al.add(b);
        }
    });
    return al;
}

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

word-wrap: break-word recently changed to overflow-wrap: break-word

  • will wrap long words onto the next line.
  • adjusts different words so that they do not break in the middle.

word-break: break-all

  • irrespective of whether it’s a continuous word or many words, breaks them up at the edge of the width limit. (i.e. even within the characters of the same word)

So if you have many fixed-size spans which get content dynamically, you might just prefer using word-wrap: break-word, as that way only the continuous words are broken in between, and in case it’s a sentence comprising many words, the spaces are adjusted to get intact words (no break within a word).

And if it doesn’t matter, go for either.

JavaFX - create custom button with image

A combination of previous 2 answers did the trick. Thanks. A new class which inherits from Button. Note: updateImages() should be called before showing the button.

import javafx.event.EventHandler;
import javafx.scene.control.Button;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.input.MouseEvent;

public class ImageButton extends Button {

    public void updateImages(final Image selected, final Image unselected) {
        final ImageView iv = new ImageView(selected);
        this.getChildren().add(iv);

        iv.setOnMousePressed(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent evt) {
                iv.setImage(unselected);
            }
        });
        iv.setOnMouseReleased(new EventHandler<MouseEvent>() {
            public void handle(MouseEvent evt) {
                iv.setImage(selected);
            }
        });

        super.setGraphic(iv);
    }
}

How to change the link color in a specific class for a div CSS

If you want to add CSS on a:hover to not all the tag, but the some of the tag, best way to do that is by using class. Give the class to all the tags which you want to give style - see the example below.

<style>
a.change_hover_color:hover { 
    color: white !important;
}
</style>

<a class="change_hover_color">FACEBOOK</a>
<a class="change_hover_color">GOOGLE</a>

A full list of all the new/popular databases and their uses?

There are graph databases like:

A graph database stores data as nodes and relationships/edges.This is a good fit for semi-structured data, interconnected information and domains with deep relationships/traversal, for example social networks and knowledge representation. The data model is highly flexible and "whiteboard friendly". The underlying data model of the semantic web, RDF, is also a (labeled, directed multi-)graph.

Other stackoverflow threads with information on graph databases:

How to change app default theme to a different app theme?

Or try to check your mainActivity.xml you make sure that this one
xmlns:app="http://schemas.android.com/apk/res-auto"hereis included

How do I link to a library with Code::Blocks?

At a guess, you used Code::Blocks to create a Console Application project. Such a project does not link in the GDI stuff, because console applications are generally not intended to do graphics, and TextOut is a graphics function. If you want to use the features of the GDI, you should create a Win32 Gui Project, which will be set up to link in the GDI for you.

Python map object is not subscriptable

map() doesn't return a list, it returns a map object.

You need to call list(map) if you want it to be a list again.

Even better,

from itertools import imap
payIntList = list(imap(int, payList))

Won't take up a bunch of memory creating an intermediate object, it will just pass the ints out as it creates them.

Also, you can do if choice.lower() == 'n': so you don't have to do it twice.

Python supports +=: you can do payIntList[i] += 1000 and numElements += 1 if you want.

If you really want to be tricky:

from itertools import count
for numElements in count(1):
    payList.append(raw_input("Enter the pay amount: "))
    if raw_input("Do you wish to continue(y/n)?").lower() == 'n':
         break

and / or

for payInt in payIntList:
    payInt += 1000
    print payInt

Also, four spaces is the standard indent amount in Python.

How to split a string with angularJS

You could try this:

$scope.testdata = [{ 'name': 'name,id' }, {'name':'someName,someId'}]
$scope.array= [];
angular.forEach($scope.testdata, function (value, key) {
    $scope.array.push({ 'name': value.name.split(',')[0], 'id': value.name.split(',')[1] });
});
console.log($scope.array)

This way you can save the data for later use and acces it by using an ng-repeat like this:

<div ng-repeat="item in array">{{item.name}}{{item.id}}</div>


I hope this helped someone,
Plunker link: here
All credits go to @jwpfox and @Mohideen ibn Mohammed from the answer above.

Android list view inside a scroll view

found a solution for scrollview -> viewpager -> FragmentPagerAdapter -> fragment -> dynamic listview, but im not the author. there is some bugs, but at least it works

public class CustomPager extends ViewPager {

    private View mCurrentView;

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

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

    @Override
    public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mCurrentView == null) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;
        }
        int height = 0;
        mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
        int h = mCurrentView.getMeasuredHeight();
        if (h > height) height = h;
        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    public void measureCurrentView(View currentView) {
        mCurrentView = currentView;
        this.post(new Runnable() {
            @Override
            public void run() {
                requestLayout();
            }
        });
    }

    public int measureFragment(View view) {
        if (view == null)
            return 0;

        view.measure(0, 0);
        return view.getMeasuredHeight();
    }
}


public class MyPagerAdapter extends FragmentPagerAdapter {

    private List<Fragment> fragments;
    private int mCurrentPosition = -1;


    public MyPagerAdapter(FragmentManager fm) {
        super(fm);//or u can set them separately, but dont forget to call notifyDataSetChanged()
        this.fragments = new ArrayList<Fragment>();
        fragments.add(new FirstFragment());
        fragments.add(new SecondFragment());
        fragments.add(new ThirdFragment());
        fragments.add(new FourthFragment());
    }

    @Override
    public void setPrimaryItem(ViewGroup container, int position, Object object) {
        super.setPrimaryItem(container, position, object);
        if (position != mCurrentPosition) {
            Fragment fragment = (Fragment) object;
            CustomPager pager = (CustomPager) container;
            if (fragment != null && fragment.getView() != null) {
                mCurrentPosition = position;
                pager.measureCurrentView(fragment.getView());
            }
        }
    }

    @Override
    public Fragment getItem(int position) {
        return fragments.get(position);
    }

    @Override
    public int getCount() {
        return fragments.size();
    }
}

fragments layout can be anything

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:orientation="vertical"
    android:layout_height="match_parent" tools:context="nevet.me.wcviewpagersample.FirstFragment">


    <ListView
        android:id="@+id/lv1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#991199"/>
</LinearLayout>

then somewhere just

lv = (ListView) view.findViewById(R.id.lv1);
        lv.setAdapter(arrayAdapter);
        setListViewHeightBasedOnChildren(lv);
    }

    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null)
            return;

        int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(),
                View.MeasureSpec.UNSPECIFIED);
        int totalHeight = 0;
        View view = null;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            view = listAdapter.getView(i, view, listView);
            if (i == 0)
                view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth,
                        LinearLayout.LayoutParams.WRAP_CONTENT));

            view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
            totalHeight += view.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight
                + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }

referenced before assignment error in python

I think you are using 'global' incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar.

#!/usr/bin/python

total

def checkTotal():
    global total
    total = 0

See this example:

#!/usr/bin/env python

total = 0

def doA():
    # not accessing global total
    total = 10

def doB():
    global total
    total = total + 1

def checkTotal():
    # global total - not required as global is required
    # only for assignment - thanks for comment Greg
    print total

def main():
    doA()
    doB()
    checkTotal()

if __name__ == '__main__':
    main()

Because doA() does not modify the global total the output is 1 not 11.

Python: avoid new line with print command

In Python 2.x just put a , at the end of your print statement. If you want to avoid the blank space that print puts between items, use sys.stdout.write.

import sys

sys.stdout.write('hi there')
sys.stdout.write('Bob here.')

yields:

hi thereBob here.

Note that there is no newline or blank space between the two strings.

In Python 3.x, with its print() function, you can just say

print('this is a string', end="")
print(' and this is on the same line')

and get:

this is a string and this is on the same line

There is also a parameter called sep that you can set in print with Python 3.x to control how adjoining strings will be separated (or not depending on the value assigned to sep)

E.g.,

Python 2.x

print 'hi', 'there'

gives

hi there

Python 3.x

print('hi', 'there', sep='')

gives

hithere

Python - Move and overwrite files and folders

If you also need to overwrite files with read only flag use this:

def copyDirTree(root_src_dir,root_dst_dir):
"""
Copy directory tree. Overwrites also read only files.
:param root_src_dir: source directory
:param root_dst_dir:  destination directory
"""
for src_dir, dirs, files in os.walk(root_src_dir):
    dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1)
    if not os.path.exists(dst_dir):
        os.makedirs(dst_dir)
    for file_ in files:
        src_file = os.path.join(src_dir, file_)
        dst_file = os.path.join(dst_dir, file_)
        if os.path.exists(dst_file):
            try:
                os.remove(dst_file)
            except PermissionError as exc:
                os.chmod(dst_file, stat.S_IWUSR)
                os.remove(dst_file)

        shutil.copy(src_file, dst_dir)

ConcurrentHashMap vs Synchronized HashMap

ConcurrentHashMap allows concurrent access to data. Whole map is divided into segments.

Read operation ie. get(Object key) is not synchronized even at segment level.

But write operations ie. remove(Object key), get(Object key) acquire lock at segment level. Only part of whole map is locked, other threads still can read values from various segments except locked one.

SynchronizedMap on the other hand, acquire lock at object level. All threads should wait for current thread irrespective of operation(Read/Write).

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

Step-1: Your Model class

public class RechargeMobileViewModel
    {
        public string CustomerFullName { get; set; }
        public string TelecomSubscriber { get; set; }
        public int TotalAmount { get; set; }
        public string MobileNumber { get; set; }
        public int Month { get; set; }
        public List<SelectListItem> getAllDaysList { get; set; }

        // Define the list which you have to show in Drop down List
        public List<SelectListItem> getAllWeekDaysList()
        {
            List<SelectListItem> myList = new List<SelectListItem>();
            var data = new[]{
                 new SelectListItem{ Value="1",Text="Monday"},
                 new SelectListItem{ Value="2",Text="Tuesday"},
                 new SelectListItem{ Value="3",Text="Wednesday"},
                 new SelectListItem{ Value="4",Text="Thrusday"},
                 new SelectListItem{ Value="5",Text="Friday"},
                 new SelectListItem{ Value="6",Text="Saturday"},
                 new SelectListItem{ Value="7",Text="Sunday"},
             };
            myList = data.ToList();
            return myList;
        }
}

Step-2: Call this method to fill Drop down in your controller Action

namespace MvcVariousApplication.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
              RechargeMobileViewModel objModel = new RechargeMobileViewModel();
                objModel.getAllDaysList = objModel.getAllWeekDaysList();  
                return View(objModel);
            }
    }
    }

Step-3: Fill your Drop-Down List of View as follows

 @model MvcVariousApplication.Models.RechargeMobileViewModel
    @{
        ViewBag.Title = "Contact";
    }
    @Html.LabelFor(model=> model.CustomerFullName)
    @Html.TextBoxFor(model => model.CustomerFullName)

    @Html.LabelFor(model => model.MobileNumber)
    @Html.TextBoxFor(model => model.MobileNumber)

    @Html.LabelFor(model => model.TelecomSubscriber)
    @Html.TextBoxFor(model => model.TelecomSubscriber)

    @Html.LabelFor(model => model.TotalAmount)
    @Html.TextBoxFor(model => model.TotalAmount)

    @Html.LabelFor(model => model.Month)
    @Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")

How to detect orientation change?

My approach is similar to what bpedit shows above, but with an iOS 9+ focus. I wanted to change the scope of the FSCalendar when the view rotates.

override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
    super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)

    coordinator.animateAlongsideTransition({ (context) in
        if size.height < size.width {
            self.calendar.setScope(.Week, animated: true)
            self.calendar.appearance.cellShape = .Rectangle
        }
        else {
            self.calendar.appearance.cellShape = .Circle
            self.calendar.setScope(.Month, animated: true)

        }

        }, completion: nil)
}

This below worked, but I felt sheepish about it :)

coordinator.animateAlongsideTransition({ (context) in
        if size.height < size.width {
            self.calendar.scope = .Week
            self.calendar.appearance.cellShape = .Rectangle
        }
        }) { (context) in
            if size.height > size.width {
                self.calendar.scope = .Month
                self.calendar.appearance.cellShape = .Circle
            }
    }

CMake output/build directory

Turning my comment into an answer:

In case anyone did what I did, which was start by putting all the build files in the source directory:

cd src
cmake .

cmake will put a bunch of build files and cache files (CMakeCache.txt, CMakeFiles, cmake_install.cmake, etc) in the src dir.

To change to an out of source build, I had to remove all of those files. Then I could do what @Angew recommended in his answer:

mkdir -p src/build
cd src/build
cmake ..

Java SimpleDateFormat for time zone with a colon separator?

If you can use JDK 1.7 or higher, try this:

public class DateUtil {
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");

    public static String format(Date date) {
        return dateFormat.format(date);
    }

    public static Date parse(String dateString) throws AquariusException {
        try {
            return dateFormat.parse(dateString);
        } catch (ParseException e) {
            throw new AquariusException(e);
        }
    }
}

document: https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html which supports a new Time Zone format "XXX" (e.g. -3:00)

While JDK 1.6 only support other formats for Time Zone, which are "z" (e.g. NZST), "zzzz" (e.g. New Zealand Standard Time), "Z" (e.g. +1200), etc.

How to call a function after delay in Kotlin?

A simple example to show a toast after 3 seconds :

fun onBtnClick() {
    val handler = Handler()
    handler.postDelayed({ showToast() }, 3000)
}

fun showToast(){
    Toast.makeText(context, "Its toast!", Toast.LENGTH_SHORT).show()
}

How to remove carriage return and newline from a variable in shell script

You can use sed as follows:

MY_NEW_VAR=$(echo $testVar | sed -e 's/\r//g')
echo ${MY_NEW_VAR} got it

By the way, try to do a dos2unix on your data file.

How do I add an element to array in reducer of React native redux?

I have a sample

import * as types from '../../helpers/ActionTypes';

var initialState = {
  changedValues: {}
};
const quickEdit = (state = initialState, action) => {

  switch (action.type) {

    case types.PRODUCT_QUICKEDIT:
      {
        const item = action.item;
        const changedValues = {
          ...state.changedValues,
          [item.id]: item,
        };

        return {
          ...state,
          loading: true,
          changedValues: changedValues,
        };
      }
    default:
      {
        return state;
      }
  }
};

export default quickEdit;

Find if current time falls in a time range

For checking for a time of day use:

TimeSpan start = new TimeSpan(10, 0, 0); //10 o'clock
TimeSpan end = new TimeSpan(12, 0, 0); //12 o'clock
TimeSpan now = DateTime.Now.TimeOfDay;

if ((now > start) && (now < end))
{
   //match found
}

For absolute times use:

DateTime start = new DateTime(2009, 12, 9, 10, 0, 0)); //10 o'clock
DateTime end = new DateTime(2009, 12, 10, 12, 0, 0)); //12 o'clock
DateTime now = DateTime.Now;

if ((now > start) && (now < end))
{
   //match found
}

Why there is this "clear" class before footer?

A class in HTML means that in order to set attributes to it in CSS, you simply need to add a period in front of it.
For example, the CSS code of that html code may be:

.clear {     height: 50px;     width: 25px; } 

Also, if you, as suggested by abiessu, are attempting to add the CSS clear: both; attribute to the div to prevent anything from floating to the left or right of this div, you can use this CSS code:

.clear {     clear: both; } 

Stop UIWebView from "bouncing" vertically?

Swift 3

webView.scrollView.bounces = false

Why do I get "'property cannot be assigned" when sending an SMTP email?

Finally got working :)

using System.Net.Mail;
using System.Text;

...

// Command line argument must the the SMTP host.
SmtpClient client = new SmtpClient();
client.Port = 587;
client.Host = "smtp.gmail.com";
client.EnableSsl = true;
client.Timeout = 10000;
client.DeliveryMethod = SmtpDeliveryMethod.Network;
client.UseDefaultCredentials = false;
client.Credentials = new System.Net.NetworkCredential("[email protected]","password");

MailMessage mm = new MailMessage("[email protected]", "[email protected]", "test", "test");
mm.BodyEncoding = UTF8Encoding.UTF8;
mm.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;

client.Send(mm);

sorry about poor spelling before

How do I check which version of NumPy I'm using?

>> import numpy
>> print numpy.__version__

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

How can the default node version be set using NVM?

This will set the default to be the most current version of node

nvm alias default node

and then you'll need to run

nvm use default

or exit and open a new tab

Why doesn't catching Exception catch RuntimeException?

I faced similar scenario. It was happening because classA's initilization was dependent on classB's initialization. When classB's static block faced runtime exception, classB was not initialized. Because of this, classB did not throw any exception and classA's initialization failed too.

class A{//this class will never be initialized because class B won't intialize
  static{
    try{
      classB.someStaticMethod();
    }catch(Exception e){
      sysout("This comment will never be printed");
    }
 }
}

class B{//this class will never be initialized
 static{
    int i = 1/0;//throw run time exception 
 }

 public static void someStaticMethod(){}
}

And yes...catching Exception will catch run time exceptions as well.

Navigation Controller Push View Controller

If you are using Swift:

let controller = self.storyboard!.instantiateViewControllerWithIdentifier("controllerID")
self.navigationController!.pushViewController(controller, animated: true)

How to display a loading screen while site content loads

There's actually a pretty easy way to do this. The code should be something like:

<script type="test/javascript">

    function showcontent(x){

      if(window.XMLHttpRequest) {
        xmlhttp = new XMLHttpRequest();
      } else {
        xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
      }

      xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState == 1) {
            document.getElementById('content').innerHTML = "<img src='loading.gif' />";
        }
        if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          document.getElementById('content').innerHTML = xmlhttp.responseText;
        } 
      }

      xmlhttp.open('POST', x+'.html', true);
      xmlhttp.setRequestHeader('Content-type','application/x-www-form-urlencoded');
      xmlhttp.send(null);

    }

And in the HTML:

<body onload="showcontent(main)"> <!-- onload optional -->
<div id="content"><img src="loading.gif"></div> <!-- leave img out if not onload -->
</body>

I did something like that on my page and it works great.

Add timer to a Windows Forms application

Bit more detail:

    private void Form1_Load(object sender, EventArgs e)
    {
        Timer MyTimer = new Timer();
        MyTimer.Interval = (45 * 60 * 1000); // 45 mins
        MyTimer.Tick += new EventHandler(MyTimer_Tick);
        MyTimer.Start();
    }

    private void MyTimer_Tick(object sender, EventArgs e)
    {
        MessageBox.Show("The form will now be closed.", "Time Elapsed");
        this.Close();
    }

How to read request body in an asp.net core webapi controller?

In ASP.Net Core it seems complicated to read several times the body request, however if your first attempt does it the right way, you should be fine for the next attempts.

I read several turnaround for example by substituting the body stream, but I think the following is the cleanest:

The most important points being

  1. to let the request know that you will read its body twice or more times,
  2. to not close the body stream, and
  3. to rewind it to its initial position so the internal process does not get lost.

[EDIT]

As pointed out by Murad, you may also take advantage of the .Net Core 2.1 extension: EnableBuffering It stores large requests onto the disk instead of keeping it in memory, avoiding large-streams issues stored in memory (files, images, ...). You can change the temporary folder by setting ASPNETCORE_TEMP environment variable, and files are deleted once the request is over.

In an AuthorizationFilter, you can do the following:

// Helper to enable request stream rewinds
using Microsoft.AspNetCore.Http.Internal;
[...]
public class EnableBodyRewind : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var bodyStr = "";
        var req = context.HttpContext.Request;

        // Allows using several time the stream in ASP.Net Core
        req.EnableRewind(); 

        // Arguments: Stream, Encoding, detect encoding, buffer size 
        // AND, the most important: keep stream opened
        using (StreamReader reader 
                  = new StreamReader(req.Body, Encoding.UTF8, true, 1024, true))
        {
            bodyStr = reader.ReadToEnd();
        }

        // Rewind, so the core is not lost when it looks the body for the request
        req.Body.Position = 0;

        // Do whatever work with bodyStr here

    }
}



public class SomeController : Controller
{
    [HttpPost("MyRoute")]
    [EnableBodyRewind]
    public IActionResult SomeAction([FromBody]MyPostModel model )
    {
        // play the body string again
    }
}

Then you can use the body again in the request handler.

In your case if you get a null result, it probably means that the body has already been read at an earlier stage. In that case you may need to use a middleware (see below).

However be careful if you handle large streams, that behavior implies that everything is loaded into memory, this should not be triggered in case of a file upload.

You may want to use this as a Middleware

Mine looks like this (again, if you download/upload large files, this should be disabled to avoid memory issues):

public sealed class BodyRewindMiddleware
{
    private readonly RequestDelegate _next;

    public BodyRewindMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    public async Task Invoke(HttpContext context)
    {
        try { context.Request.EnableRewind(); } catch { }
        await _next(context);
        // context.Request.Body.Dipose() might be added to release memory, not tested
    }
}
public static class BodyRewindExtensions
{
    public static IApplicationBuilder EnableRequestBodyRewind(this IApplicationBuilder app)
    {
        if (app == null)
        {
            throw new ArgumentNullException(nameof(app));
        }

        return app.UseMiddleware<BodyRewindMiddleware>();
    }

}

<input type="file"> limit selectable files by extensions

 function uploadFile() {
     var fileElement = document.getElementById("fileToUpload");
        var fileExtension = "";
        if (fileElement.value.lastIndexOf(".") > 0) {
            fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
        }
        if (fileExtension == "odx-d"||fileExtension == "odx"||fileExtension == "pdx"||fileExtension == "cmo"||fileExtension == "xml") {
         var fd = new FormData();
        fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
        var xhr = new XMLHttpRequest();
        xhr.upload.addEventListener("progress", uploadProgress, false);
        xhr.addEventListener("load", uploadComplete, false);
        xhr.addEventListener("error", uploadFailed, false);
        xhr.addEventListener("abort", uploadCanceled, false);
        xhr.open("POST", "/post_uploadReq");
        xhr.send(fd);
        }
        else {
            alert("You must select a valid odx,pdx,xml or cmo file for upload");
            return false;
        }
       
      }

tried this , works very well

My httpd.conf is empty

OK - what you're missing is that its designed to be more industrial and serve many sites, so the config you want is probably:

/etc/apache2/sites-available/default

which on my system is linked to from /etc/apache2/sites-enabled/

if you want to have different sites with different options, copy the file and then change those...

How to specify different Debug/Release output directories in QMake .pro file

It's also useful to have a slightly different name for the output executable. You can't use something like:

release: Target = ProgramName
debug: Target = ProgramName_d

Why it doesn't work is not clear, but it does not. But:

CONFIG(debug, debug|release) {
    TARGET = ProgramName
} else {
    TARGET = ProgramName_d
}

This does work as long as the CONFIG += line precedes it.

How can I protect my .NET assemblies from decompilation?

Host your service in any cloud service provider.

How to delete a file after checking whether it exists

If you are reading from that file using FileStream and then wanting to delete it, make sure you close the FileStream before you call the File.Delete(path). I had this issue.

var filestream = new System.IO.FileStream(@"C:\Test\PutInv.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.ReadWrite);
filestream.Close();
File.Delete(@"C:\Test\PutInv.txt");

How to find the kth largest element in an unsorted array of length n in O(n)?

What I would do is this:

initialize empty doubly linked list l
for each element e in array
    if e larger than head(l)
        make e the new head of l
        if size(l) > k
            remove last element from l

the last element of l should now be the kth largest element

You can simply store pointers to the first and last element in the linked list. They only change when updates to the list are made.

Update:

initialize empty sorted tree l
for each element e in array
    if e between head(l) and tail(l)
        insert e into l // O(log k)
        if size(l) > k
            remove last element from l

the last element of l should now be the kth largest element

How do I read the file content from the Internal storage - Android App

For others looking for an answer to why a file is not readable especially on a sdcard, write the file like this first.. Notice the MODE_WORLD_READABLE

try {
            FileOutputStream fos = Main.this.openFileOutput("exported_data.csv", MODE_WORLD_READABLE);
            fos.write(csv.getBytes());
            fos.close();
            File file = Main.this.getFileStreamPath("exported_data.csv");
            return file.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

JQuery Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'

Create a separate JavaScript function that can be called to close the dialog using the specific object id, and place the function outside of $(document).ready() like this:

function closeDialogWindow() { 
$('#dialogWindow').dialog('close');
}

NOTE: The function must be declared outside of $(document).ready() so jQuery doesn't try to trigger the close event on the dialog before it is created in the DOM.

How do you use window.postMessage across domains?

You should post a message from frame to parent, after loaded.

frame script:

$(document).ready(function() {
    window.parent.postMessage("I'm loaded", "*");
});

And listen it in parent:

function listenMessage(msg) {
    alert(msg);
}

if (window.addEventListener) {
    window.addEventListener("message", listenMessage, false);
} else {
    window.attachEvent("onmessage", listenMessage);
}

Use this link for more info: http://en.wikipedia.org/wiki/Web_Messaging

Jenkins - Configure Jenkins to poll changes in SCM

I think your cron is not correct. According to what you described, you may need to change cron schedule to

*/5 * * * *

What you put in your schedule now mean it will poll the SCM at 5 past of every hour.

Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?

All of these are kinds of indices.

primary: must be unique, is an index, is (likely) the physical index, can be only one per table.

unique: as it says. You can't have more than one row with a tuple of this value. Note that since a unique key can be over more than one column, this doesn't necessarily mean that each individual column in the index is unique, but that each combination of values across these columns is unique.

index: if it's not primary or unique, it doesn't constrain values inserted into the table, but it does allow them to be looked up more efficiently.

fulltext: a more specialized form of indexing that allows full text search. Think of it as (essentially) creating an "index" for each "word" in the specified column.

Display open transactions in MySQL

How can I display these open transactions and commit or cancel them?

There is no open transaction, MySQL will rollback the transaction upon disconnect.
You cannot commit the transaction (IFAIK).

You display threads using

SHOW FULL PROCESSLIST  

See: http://dev.mysql.com/doc/refman/5.1/en/thread-information.html

It will not help you, because you cannot commit a transaction from a broken connection.

What happens when a connection breaks
From the MySQL docs: http://dev.mysql.com/doc/refman/5.0/en/mysql-tips.html

4.5.1.6.3. Disabling mysql Auto-Reconnect

If the mysql client loses its connection to the server while sending a statement, it immediately and automatically tries to reconnect once to the server and send the statement again. However, even if mysql succeeds in reconnecting, your first connection has ended and all your previous session objects and settings are lost: temporary tables, the autocommit mode, and user-defined and session variables. Also, any current transaction rolls back.

This behavior may be dangerous for you, as in the following example where the server was shut down and restarted between the first and second statements without you knowing it:

Also see: http://dev.mysql.com/doc/refman/5.0/en/auto-reconnect.html

How to diagnose and fix this
To check for auto-reconnection:

If an automatic reconnection does occur (for example, as a result of calling mysql_ping()), there is no explicit indication of it. To check for reconnection, call mysql_thread_id() to get the original connection identifier before calling mysql_ping(), then call mysql_thread_id() again to see whether the identifier has changed.

Make sure you keep your last query (transaction) in the client so that you can resubmit it if need be.
And disable auto-reconnect mode, because that is dangerous, implement your own reconnect instead, so that you know when a drop occurs and you can resubmit that query.

C# version of java's synchronized keyword?

First - most classes will never need to be thread-safe. Use YAGNI: only apply thread-safety when you know you actually are going to use it (and test it).

For the method-level stuff, there is [MethodImpl]:

[MethodImpl(MethodImplOptions.Synchronized)]
public void SomeMethod() {/* code */}

This can also be used on accessors (properties and events):

private int i;
public int SomeProperty
{
    [MethodImpl(MethodImplOptions.Synchronized)]
    get { return i; }
    [MethodImpl(MethodImplOptions.Synchronized)]
    set { i = value; }
}

Note that field-like events are synchronized by default, while auto-implemented properties are not:

public int SomeProperty {get;set;} // not synchronized
public event EventHandler SomeEvent; // synchronized

Personally, I don't like the implementation of MethodImpl as it locks this or typeof(Foo) - which is against best practice. The preferred option is to use your own locks:

private readonly object syncLock = new object();
public void SomeMethod() {
    lock(syncLock) { /* code */ }
}

Note that for field-like events, the locking implementation is dependent on the compiler; in older Microsoft compilers it is a lock(this) / lock(Type) - however, in more recent compilers it uses Interlocked updates - so thread-safe without the nasty parts.

This allows more granular usage, and allows use of Monitor.Wait/Monitor.Pulse etc to communicate between threads.

A related blog entry (later revisited).

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

The ODP.Net provider from oracle uses bind by position as default. To change the behavior to bind by name. Set property BindByName to true. Than you can dismiss the double definition of parameters.

using(OracleCommand cmd = con.CreateCommand()) {
    ...
    cmd.BindByName = true;
    ...
}

Test if a variable is a list or tuple

Has to be more complex test if you really want to handle just about anything as function argument.

type(a) != type('') and hasattr(a, "__iter__")

Although, usually it's enough to just spell out that a function expects iterable and then check only type(a) != type('').

Also it may happen that for a string you have a simple processing path or you are going to be nice and do a split etc., so you don't want to yell at strings and if someone sends you something weird, just let him have an exception.

How to do a Jquery Callback after form submit?

I could not get the number one upvoted solution to work reliably, but have found this works. Not sure if it's required or not, but I do not have an action or method attribute on the tag, which ensures the POST is handled by the $.ajax function and gives you the callback option.

<form id="form">
...
<button type="submit"></button>
</form>

<script>
$(document).ready(function() {
  $("#form_selector").submit(function() {

    $.ajax({
     type: "POST",
      url: "form_handler.php",
      data: $(this).serialize(),
      success: function() {
        // callback code here
       }
    })

  })
})
</script>

How do you discover model attributes in Rails?

To describe model I use following snippet

Model.columns.collect { |c| "#{c.name} (#{c.type})" }

Again this is if you are looking pretty print to describe you ActiveRecord without you going trough migrations or hopping that developer before you was nice enough to comment in attributes.

React: Expected an assignment or function call and instead saw an expression

You are not returning anything, at least from your snippet and comment.

const def = (props) => { <div></div> };

This is not returning anything, you are wrapping the body of the arrow function with curly braces but there is no return value.

const def = (props) => { return (<div></div>); }; OR const def = (props) => <div></div>;

These two solutions on the other hand are returning a valid React component. Keep also in mind that inside your jsx (as mentioned by @Adam) you can't have if ... else ... but only ternary operators.

List of foreign keys and the tables they reference in Oracle DB

Try this:

select * from all_constraints where r_constraint_name in (select constraint_name 
from all_constraints where table_name='YOUR_TABLE_NAME');

Simple function to sort an array of objects

Array.prototype.sort_by = function(key_func, reverse=false){
    return this.sort( (a, b) => ( key_func(b) - key_func(a) ) * (reverse ? 1 : -1) ) 
}

Then for example if we have

var arr = [ {id: 0, balls: {red: 8,  blue: 10}},
            {id: 2, balls: {red: 6 , blue: 11}},
            {id: 1, balls: {red: 4 , blue: 15}} ]

arr.sort_by(el => el.id, reverse=true)
/* would result in
[ { id: 2, balls: {red: 6 , blue: 11 }},
  { id: 1, balls: {red: 4 , blue: 15 }},
  { id: 0, balls: {red: 8 , blue: 10 }} ]
*/

or

arr.sort_by(el => el.balls.red + el.balls.blue)
/* would result in
[ { id: 2, balls: {red: 6 , blue: 11 }},    // red + blue= 17
  { id: 0, balls: {red: 8 , blue: 10 }},    // red + blue= 18
  { id: 1, balls: {red: 4 , blue: 15 }} ]   // red + blue= 19
*/

Long Press in JavaScript?

I needed something for longpress keyboard events, so I wrote this.

var longpressKeys = [13];
var longpressTimeout = 1500;
var longpressActive = false;
var longpressFunc = null;

document.addEventListener('keydown', function(e) {
    if (longpressFunc == null && longpressKeys.indexOf(e.keyCode) > -1) {
        longpressFunc = setTimeout(function() {
            console.log('longpress triggered');
            longpressActive = true;
        }, longpressTimeout);

    // any key not defined as a longpress
    } else if (longpressKeys.indexOf(e.keyCode) == -1) {
        console.log('shortpress triggered');
    }
});

document.addEventListener('keyup', function(e) {
    clearTimeout(longpressFunc);
    longpressFunc = null;

    // longpress key triggered as a shortpress
    if (!longpressActive && longpressKeys.indexOf(e.keyCode) > -1) {
        console.log('shortpress triggered');
    }
    longpressActive = false;
});

AVD Manager - Cannot Create Android Virtual Device

If you have changed the SDK Path somehow it will not be able to find the SDKs you installed even though it is listing them fine.

I solved by openig Android SDK Manager and in that dialog choosing the menu Tools -> Manage AVDs. And when you open Manage AVDs directly from the toolbar of Eclipse you should Refresh to see the AVD you created.

How to get the caller class in Java

i am using the following method to get the caller for a specific class from the stacktrace:

package test.log;

public class CallerClassTest {

    public static void main(final String[] args) {
        final Caller caller = new Caller(new Callee());
        caller.execute();
    }

    private static class Caller {

        private final Callee c;

        public Caller(final Callee c) {
            this.c = c;
        }

        void execute() {
            c.call();
        }
    }

    static class Callee {

        void call() {
            System.out.println(getCallerClassName(this.getClass()));
        }
    }

    /**
     * Searches the current threads stacktrace for the class that called the given class. Returns {@code null} if the
     * calling class could not be found.
     * 
     * @param clazz
     *            the class that has been called
     * 
     * @return the caller that called the class or {@code null}
     */
    public static String getCallerClassName(final Class<?> clazz) {
        final StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
        final String className = clazz.getName();
        boolean classFound = false;
        for (int i = 1; i < stackTrace.length; i++) {
            final StackTraceElement element = stackTrace[i];
            final String callerClassName = element.getClassName();
            // check if class name is the requested class
            if (callerClassName.equals(className)) classFound = true;
            else if (classFound) return callerClassName;
        }
        return null;
    }

}

UICollectionView - Horizontal scroll, horizontal layout?

1st approach

What about using UIPageViewController with an array of UICollectionViewControllers? You'd have to fetch proper number of items in each UICollectionViewController, but it shouldn't be hard. You'd get exactly the same look as the Springboard has.

2nd approach

I've thought about this and in my opinion you have to set:

self.collectionView.pagingEnabled = YES;

and create your own collection view layout by subclassing UICollectionViewLayout. From the custom layout object you can access self.collectionView, so you'll know what is the size of the collection view's frame, numberOfSections and numberOfItemsInSection:. With that information you can calculate cells' frames (in prepareLayout) and collectionViewContentSize. Here're some articles about creating custom layouts:

3rd approach

You can do this (or an approximation of it) without creating the custom layout. Add UIScrollView in the blank view, set paging enabled in it. In the scroll view add the a collection view. Then add to it a width constraint, check in code how many items you have and set its constant to the correct value, e.g. (self.view.frame.size.width * numOfScreens). Here's how it looks (numbers on cells show the indexPath.row): https://www.dropbox.com/s/ss4jdbvr511azxz/collection_view.mov If you're not satisfied with the way cells are ordered, then I'm afraid you'd have to go with 1. or 2.

datetime dtypes in pandas read_csv

There is a parse_dates parameter for read_csv which allows you to define the names of the columns you want treated as dates or datetimes:

date_cols = ['col1', 'col2']
pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=date_cols)

PDO error message?

From the manual:

If the database server successfully prepares the statement, PDO::prepare() returns a PDOStatement object. If the database server cannot successfully prepare the statement, PDO::prepare() returns FALSE or emits PDOException (depending on error handling).

The prepare statement likely caused an error because the db would be unable to prepare the statement. Try testing for an error immediately after you prepare your query and before you execute it.

$qry = '
    INSERT INTO non-existant-table (id, score) 
    SELECT id, 40 
    FROM another-non-existant-table
    WHERE description LIKE "%:search_string%"
    AND available = "yes"
    ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
print_r($this->pdo->errorInfo());