Programs & Examples On #Iisvdir

Assigning a variable NaN in python without numpy

A more consistent (and less opaque) way to generate inf and -inf is to again use float():

>> positive_inf = float('inf')
>> positive_inf
inf
>> negative_inf = float('-inf')
>> negative_inf
-inf

Note that the size of a float varies depending on the architecture, so it probably best to avoid using magic numbers like 9e999, even if that is likely to work.

import sys
sys.float_info
sys.float_info(max=1.7976931348623157e+308,
               max_exp=1024, max_10_exp=308,
               min=2.2250738585072014e-308, min_exp=-1021,
               min_10_exp=-307, dig=15, mant_dig=53,
               epsilon=2.220446049250313e-16, radix=2, rounds=1)

Finding the second highest number in array

private static int SecondBiggest(int[] vector)
{
    if (vector == null)
    {
        throw new ArgumentNullException("vector");
    }
    if (vector.Length < 2)
    {
        return int.MinValue;
    }

    int max1 = vector[0];
    int max2 = vector[1];
    for (int i = 2; i < vector.Length; ++i)
    {
        if (max1 > max2 && max1 != vector[i])
        {
            max2 = Math.Max(max2, vector[i]);
        }
        else if (max2 != vector[i])
        {
            max1 = Math.Max(max1, vector[i]);
        }
    }
    return Math.Min(max1, max2);
}

This treats duplicates as the same number. You can change the condition checks if you want to all the biggest and the second biggest to be duplicates.

jQuery return ajax result into outside variable

I solved it by doing like that:

var return_first = (function () {
        var tmp = $.ajax({
            'type': "POST",
            'dataType': 'html',
            'url': "ajax.php?first",
            'data': { 'request': "", 'target': arrange_url, 'method': 
                    method_target },
            'success': function (data) {
                tmp = data;
            }
        }).done(function(data){
                return data;
        });
      return tmp;
    });
  • Be careful 'async':fale javascript will be asynchronous.

How to merge two files line by line in Bash

Try following.

pr -tmJ a.txt b.txt > c.txt

How do I get my Maven Integration tests to run

By default, Maven only runs tests that have Test somewhere in the class name.

Rename to IntegrationTest and it'll probably work.

Alternatively you can change the Maven config to include that file but it's probably easier and better just to name your tests SomethingTest.

From Inclusions and Exclusions of Tests:

By default, the Surefire Plugin will automatically include all test classes with the following wildcard patterns:

  • \*\*/Test\*.java - includes all of its subdirectory and all java filenames that start with "Test".
  • \*\*/\*Test.java - includes all of its subdirectory and all java filenames that end with "Test".
  • \*\*/\*TestCase.java - includes all of its subdirectory and all java filenames that end with "TestCase".

If the test classes does not go with the naming convention, then configure Surefire Plugin and specify the tests you want to include.

How to return value from function which has Observable subscription inside?

While the previous answers may work in a fashion, I think that using BehaviorSubject is the correct way if you want to continue using observables.

Example:

    this.store.subscribe(
        (data:any) => {
            myService.myBehaviorSubject.next(data)
        }
    )

In the Service:

let myBehaviorSubject = new BehaviorSubjet(value);

In component.ts:

this.myService.myBehaviorSubject.subscribe(data => this.myData = data)

I hope this helps!

Linux find and grep command together

Or maybe even easier

grep -R put **/*bills*

The ** glob syntax means "any depth of directories". It will work in Zsh, and I think recent versions of Bash too.

Oracle select most recent date record

select *
from (select
  staff_id, site_id, pay_level, date, 
  rank() over (partition by staff_id order by date desc) r
  from owner.table
  where end_enrollment_date is null
)
where r = 1

Find document with array that contains a specific value

I feel like $all would be more appropriate in this situation. If you are looking for person that is into sushi you do :

PersonModel.find({ favoriteFood : { $all : ["sushi"] }, ...})

As you might want to filter more your search, like so :

PersonModel.find({ favoriteFood : { $all : ["sushi", "bananas"] }, ...})

$in is like OR and $all like AND. Check this : https://docs.mongodb.com/manual/reference/operator/query/all/

How do I negate a test with regular expressions in a bash script?

the safest way is to put the ! for the regex negation within the [[ ]] like this:

if [[ ! ${STR} =~ YOUR_REGEX ]]; then

otherwise it might fail on certain systems.

Styling input buttons for iPad and iPhone

Use the below css

_x000D_
_x000D_
input[type="submit"] {_x000D_
  font-size: 20px;_x000D_
  background: pink;_x000D_
  border: none;_x000D_
  padding: 10px 20px;_x000D_
}_x000D_
.flat-btn {_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
   appearance: none;_x000D_
   border-radius: 0;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
  margin: 25px 0 10px;_x000D_
  font-size: 20px;_x000D_
}
_x000D_
<h2>iOS Styled Button!</h2>_x000D_
<input type="submit" value="iOS Styled Button!" />_x000D_
_x000D_
<h2>No More Style! Button!</h2>_x000D_
<input class="flat-btn" type="submit" value="No More Style! Button!" />
_x000D_
_x000D_
_x000D_

Last Run Date on a Stored Procedure in SQL Server

The below code should do the trick (>= 2008)

SELECT o.name, 
       ps.last_execution_time 
FROM   sys.dm_exec_procedure_stats ps 
INNER JOIN 
       sys.objects o 
       ON ps.object_id = o.object_id 
WHERE  DB_NAME(ps.database_id) = '' 
ORDER  BY 
       ps.last_execution_time DESC  

Edit 1 : Please take note of Jeff Modens advice below. If you find a procedure here, you can be sure that it is accurate. If you do not then you just don't know - you cannot conclude it is not running.

How to include vars file in a vars file with ansible?

You can put your servers in the default_step group and those vars will apply to it:

# inventory file
[default_step]
prod2
web_v2

Then just move your default_step.yml file to group_vars/default_step.yml.

Get selected value in dropdown list using JavaScript

Running example of how it works:

_x000D_
_x000D_
var e = document.getElementById("ddlViewBy");_x000D_
var val1 = e.options[e.selectedIndex].value;_x000D_
var txt = e.options[e.selectedIndex].text;_x000D_
_x000D_
document.write("<br />Selected option Value: "+ val1);_x000D_
document.write("<br />Selected option Text: "+ txt);
_x000D_
<select id="ddlViewBy">_x000D_
  <option value="1">test1</option>_x000D_
  <option value="2">test2</option>_x000D_
  <option value="3"  selected="selected">test3</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Note: The values don't change as the dropdown is changed, if you require that functionality then an onClick change is to be implemented.

Copy Paste Values only( xlPasteValues )

You may use this too

Sub CopyPaste()
Sheet1.Range("A:A").Copy

Sheet2.Activate
col = 1
Do Until Sheet2.Cells(1, col) = ""
    col = col + 1
Loop

Sheet2.Cells(1, col).PasteSpecial xlPasteValues
End Sub

Unable to execute dex: method ID not in [0, 0xffff]: 65536

Update 3 (11/3/2014)
Google finally released official description.


Update 2 (10/31/2014)
Gradle plugin v0.14.0 for Android adds support for multi-dex. To enable, you just have to declare it in build.gradle:

android {
   defaultConfig {
      ...
      multiDexEnabled  true
   }
}

If your application supports Android prior to 5.0 (that is, if your minSdkVersion is 20 or below) you also have to dynamically patch the application ClassLoader, so it will be able to load classes from secondary dexes. Fortunately, there's a library that does that for you. Add it to your app's dependencies:

dependencies {
  ...
  compile 'com.android.support:multidex:1.0.0'
} 

You need to call the ClassLoader patch code as soon as possible. MultiDexApplication class's documentation suggests three ways to do that (pick one of them, one that's most convenient for you):

1 - Declare MultiDexApplication class as the application in your AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.android.multidex.myapplication">
    <application
        ...
        android:name="android.support.multidex.MultiDexApplication">
        ...
    </application>
</manifest>

2 - Have your Application class extend MultiDexApplication class:

public class MyApplication extends MultiDexApplication { .. }

3 - Call MultiDex#install from your Application#attachBaseContext method:

public class MyApplication {
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
        ....
    }
    ....
}

Update 1 (10/17/2014):
As anticipated, multidex support is shipped in revision 21 of Android Support Library. You can find the android-support-multidex.jar in /sdk/extras/android/support/multidex/library/libs folder.


Multi-dex support solves this problem. dx 1.8 already allows generating several dex files.
Android L will support multi-dex natively, and next revision of support library is going to cover older releases back to API 4.

It was stated in this Android Developers Backstage podcast episode by Anwar Ghuloum. I've posted a transcript (and general multi-dex explanation) of the relevant part.

Calling a Javascript Function from Console

An example of where the console will return ReferenceError is putting a function inside a JQuery document ready function

//this will fail
$(document).ready(function () {
          myFunction(alert('doing something!'));
          //other stuff
}

To succeed move the function outside the document ready function

//this will work
myFunction(alert('doing something!'));
$(document).ready(function () {

          //other stuff
}

Then in the console window, type the function name with the '()' to execute the function

myFunction()

Also of use is being able to print out the function body to remind yourself what the function does. Do this by leaving off the '()' from the function name

function myFunction(alert('doing something!'))

Of course if you need the function to be registered after the document is loaded then you couldn't do this. But you might be able to work around that.

Cannot use special principal dbo: Error 15405

This answer doesn't help for SQL databases where SharePoint is connected. db_securityadmin is required for the configuration databases. In order to add db_securityadmin, you will need to change the owner of the database to an administrative account. You can use that account just for dbo roles.

How to open a WPF Popup when another control is clicked, using XAML markup only?

I had some issues with the MouseDown part of this, but here is some code that might get your started.

<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Grid>
        <Control VerticalAlignment="Top">
            <Control.Template>
                <ControlTemplate>
                    <StackPanel>
                    <TextBox x:Name="MyText"></TextBox>
                    <Popup x:Name="Popup" PopupAnimation="Fade" VerticalAlignment="Top">
                        <Border Background="Red">
                            <TextBlock>Test Popup Content</TextBlock>
                        </Border>
                    </Popup>
                    </StackPanel>
                    <ControlTemplate.Triggers>
                        <EventTrigger RoutedEvent="UIElement.MouseEnter" SourceName="MyText">
                            <BeginStoryboard>
                                <Storyboard>
                                    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
                                        <DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="True"/>
                                    </BooleanAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                        <EventTrigger RoutedEvent="UIElement.MouseLeave" SourceName="MyText">
                            <BeginStoryboard>
                                <Storyboard>
                                    <BooleanAnimationUsingKeyFrames Storyboard.TargetName="Popup" Storyboard.TargetProperty="(Popup.IsOpen)">
                                        <DiscreteBooleanKeyFrame KeyTime="00:00:00" Value="False"/>
                                    </BooleanAnimationUsingKeyFrames>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Control.Template>
        </Control>
    </Grid>
</Window>

Failed to install android-sdk: "java.lang.NoClassDefFoundError: javax/xml/bind/annotation/XmlSchema"

I faced the same problem. Though I am a little bit backdated developer (Still using windows to develop :P)

To solve this issue on windows :

STEP 1: Install jdk 8 if it wasn't installed (jdk 9 or 11 doesn't work but you may have them installed for using in other dev uses).

Very simple using Chocolatey:

choco install jdk8

(If installed using Chocolatey, skip steps 2 and 3)

STEP 2: Go to the Environment variables settings and set JAVA_HOME TO jdk 8's installation directory.

JAVA_HOME

STEP 3: Go to path variable and add bin directory of jdk 8 and move it to top.

Path_varriable

STEP 4: Close any open terminal sessions and restart a new session

OPTIONAL STEP 5: Depending on your objective in the terminal run (may need to add sdkmanager to path or just navigate to the directory):

sdkmanager --update

That's all! :O Enjoy fluttering! :D

Show a leading zero if a number is less than 10

Try this

function pad (str, max) {
  return str.length < max ? pad("0" + str, max) : str;
}

alert(pad("5", 2));

Example

http://jsfiddle.net/

Or

var number = 5;
var i;
if (number < 10) {
    alert("0"+number);
}

Example

http://jsfiddle.net/

View stored procedure/function definition in MySQL

You can use table proc in database mysql:

mysql> SELECT body FROM mysql.proc
WHERE db = 'yourdb' AND name = 'procedurename' ;

Note that you must have a grant for select to mysql.proc:

mysql> GRANT SELECT ON mysql.proc TO 'youruser'@'yourhost' IDENTIFIED BY 'yourpass' ;

Get the previous month's first and last day dates in c#

This is a take on Mike W's answer:

internal static DateTime GetPreviousMonth(bool returnLastDayOfMonth)
{
    DateTime firstDayOfThisMonth = DateTime.Today.AddDays( - ( DateTime.Today.Day - 1 ) );
    DateTime lastDayOfLastMonth = firstDayOfThisMonth.AddDays (-1);
    if (returnLastDayOfMonth) return lastDayOfLastMonth;
    return firstDayOfThisMonth.AddMonths(-1);
}

You can call it like so:

dateTimePickerFrom.Value = GetPreviousMonth(false);
dateTimePickerTo.Value = GetPreviousMonth(true);

What is compiler, linker, loader?

Compiler It converts the source code into the object code.

Linker It combines the multiple object files into a single executable program file.

Loader It loads the executable file into main memory.

Rotating a point about another point (2D)

First subtract the pivot point (cx,cy), then rotate it, then add the point again.

Untested:

POINT rotate_point(float cx,float cy,float angle,POINT p)
{
  float s = sin(angle);
  float c = cos(angle);

  // translate point back to origin:
  p.x -= cx;
  p.y -= cy;

  // rotate point
  float xnew = p.x * c - p.y * s;
  float ynew = p.x * s + p.y * c;

  // translate point back:
  p.x = xnew + cx;
  p.y = ynew + cy;
  return p;
}

How to do this in Laravel, subquery where in

You can use Eloquent in different queries and make things easier to understand and mantain:

$productCategory = ProductCategory::whereIn('category_id', ['223', '15'])
                   ->select('product_id'); //don't need ->get() or ->first()

and then we put all together:

Products::whereIn('id', $productCategory)
          ->where('active', 1)
          ->select('id', 'name', 'img', 'safe_name', 'sku', 'productstatusid')
          ->get();//runs all queries at once

This will generate the same query that you wrote in your question.

Warning: #1265 Data truncated for column 'pdd' at row 1

As the message error says, you need to Increase the length of your column to fit the length of the data you are trying to insert (0000-00-00)

EDIT 1:

Following your comment, I run a test table:

mysql> create table testDate(id int(2) not null auto_increment, pdd date default null, primary key(id));
Query OK, 0 rows affected (0.20 sec)

Insertion:

mysql> insert into testDate values(1,'0000-00-00');
Query OK, 1 row affected (0.06 sec)

EDIT 2:

So, aparently you want to insert a NULL value to pdd field as your comment states ? You can do that in 2 ways like this:

Method 1:

mysql> insert into testDate values(2,'');
Query OK, 1 row affected, 1 warning (0.06 sec)

Method 2:

mysql> insert into testDate values(3,NULL);
Query OK, 1 row affected (0.07 sec)

EDIT 3:

You failed to change the default value of pdd field. Here is the syntax how to do it (in my case, I set it to NULL in the start, now I will change it to NOT NULL)

mysql> alter table testDate modify pdd date not null;
Query OK, 3 rows affected, 1 warning (0.60 sec)
Records: 3  Duplicates: 0  Warnings: 1

Bootstrap datepicker disabling past dates without current date

The solution is much simpler:

$('#date').datepicker({ 
    startDate: "now()" 
});

Try Online Demo and fill input Start date: now()

Matplotlib scatter plot with different text at each data point

I'm not aware of any plotting method which takes arrays or lists but you could use annotate() while iterating over the values in n.

y = [2.56422, 3.77284, 3.52623, 3.51468, 3.02199]
z = [0.15, 0.3, 0.45, 0.6, 0.75]
n = [58, 651, 393, 203, 123]

fig, ax = plt.subplots()
ax.scatter(z, y)

for i, txt in enumerate(n):
    ax.annotate(txt, (z[i], y[i]))

There are a lot of formatting options for annotate(), see the matplotlib website:

enter image description here

Angular 2 beta.17: Property 'map' does not exist on type 'Observable<Response>'

You need to import the map operator:

import 'rxjs/add/operator/map'

One liner for If string is not null or empty else

This may help:

public string NonBlankValueOf(string strTestString)
{
    return String.IsNullOrEmpty(strTestString)? "0": strTestString;
}

LIKE vs CONTAINS on SQL Server

The second (assuming you means CONTAINS, and actually put it in a valid query) should be faster, because it can use some form of index (in this case, a full text index). Of course, this form of query is only available if the column is in a full text index. If it isn't, then only the first form is available.

The first query, using LIKE, will be unable to use an index, since it starts with a wildcard, so will always require a full table scan.


The CONTAINS query should be:

SELECT * FROM table WHERE CONTAINS(Column, 'test');

How to rename with prefix/suffix?

Bulk rename files bash script

#!/bin/bash
# USAGE: cd FILESDIRECTORY; RENAMERFILEPATH/MultipleFileRenamer.sh FILENAMEPREFIX INITNUMBER
# USAGE EXAMPLE: cd PHOTOS; /home/Desktop/MultipleFileRenamer.sh 2016_
# VERSION: 2016.03.05.
# COPYRIGHT: Harkály Gergo | mangoRDI (https://wwww.mangordi.com/) 

# check isset INITNUMBER argument, if not, set 1 | INITNUMBER is the first number after renaming
if [ -z "$2" ]
    then i=1;
else
    i=$2;
fi

# counts the files to set leading zeros before number | max 1000 files
count=$(ls -l * | wc -l)
if [ $count -lt 10 ]
    then zeros=1;
else
    if [ $count -lt 100 ]
        then zeros=2;
    else
        zeros=3
    fi
fi

# rename script
for file in *
do
    mv $file $1_$(printf %0"$zeros"d.%s ${i%.*} ${file##*.})
    let i="$i+1"
done

Remove first Item of the array (like popping from stack)

There is a function called shift(). It will remove the first element of your array.

There is some good documentation and examples.

Single quotes vs. double quotes in C or C++

Use single quote with single char as:

char ch = 'a';

here 'a' is a char constant and is equal to the ASCII value of char a.

Use double quote with strings as:

char str[] = "foo";

here "foo" is a string literal.

Its okay to use "a" but its not okay to use 'foo'

Setting network adapter metric priority in Windows 7

Windows has two different settings in which priority is established. There is the metric value which you have already set in the adapter settings, and then there is the connection priority in the network connections settings.

To change the priority of the connections:

  • Open your Adapter Settings (Control Panel\Network and Internet\Network Connections)
  • Click Alt to pull up the menu bar
  • Select Advanced -> Advanced Settings
  • Change the order of the connections so that the connection you want to have priority is top on the list

Run JavaScript in Visual Studio Code

I used Node Exec, no config needed, builds the file that you are currently ending or what ever has been selected and outputs inside of VSCode.

https://marketplace.visualstudio.com/items?itemName=miramac.vscode-exec-node

With a bit of config you can add Babel to do some on the fly transpiling too.

What is setBounds and how do I use it?

You can use setBounds(x, y, width, height) to specify the position and size of a GUI component if you set the layout to null. Then (x, y) is the coordinate of the upper-left corner of that component.

How to get public directory?

Use public_path()

For reference:

// Path to the project's root folder    
echo base_path();

// Path to the 'app' folder    
echo app_path();        

// Path to the 'public' folder    
echo public_path();

// Path to the 'storage' folder    
echo storage_path();

// Path to the 'storage/app' folder    
echo storage_path('app');

Tesseract running error

C# developer working on Windows here. What works for me is simply download the file eng.traineddata from the following URL:

https://github.com/tesseract-ocr/tessdata/blob/master/eng.traineddata

and copy it to the following directory in my Console Application project:

[Project Directory]\bin\Debug\tessdata

I did manually create the tessdata folder above.

What is aria-label and how should I use it?

As a side answer it's worth to note that:

  • ARIA is commonly used to improve the accessibility for screen readers. (not only but mostly atm.)
  • Using ARIA does not necessarily make things better! Easily ARIA can lead to significantly worse accessibility if not implemented and tested properly. Don't use ARIA just to have some "cool things in the code" which you don't fully understand. Sadly too often ARIA implementations introduce more issues than solutions in terms of accessibility. This is rather common since sighted users and developers are less likely to put extra effort in extensive testing with screen readers while on the other hand ARIA specs and validators are currently far from perfect and even confusing in some cases. On top of that each browser and screen reader implement the ARIA support non-uniformly causing the major inconsistencies in the behavior. Often it's better idea to avoid ARIA completely when it's not clear exactly what it does, how it behaves and it won't be tested intensively with all screen readers and browsers (or at least the most common combinations). Disclaimer: My intention is not to disgrace ARIA but rather its bad ARIA implementations. In fact it's not so uncommon that HTML5 don't offer any other alternatives where implementing ARIA would bring significant benefits for the accessibility e.g. aria-hidden or aria-expanded. But only if implemented and tested properly!

Predicate Delegates in C#

Simply -> they provide True/False values based on condition mostly used for querying. mostly used with delegates

consider example of list

List<Program> blabla= new List<Program>();
        blabla.Add(new Program("shubham", 1));
        blabla.Add(new Program("google", 3));
        blabla.Add(new Program("world",5));
        blabla.Add(new Program("hello", 5));
        blabla.Add(new Program("bye", 2));

contains names and ages. Now say we want to find names on condition So I Will use,

    Predicate<Program> test = delegate (Program p) { return p.age > 3; };
        List<Program> matches = blabla.FindAll(test);
        Action<Program> print = Console.WriteLine;
        matches.ForEach(print);

tried to Keep it Simple!

Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported for @RequestBody MultiValueMap

The problem is that when we use application/x-www-form-urlencoded, Spring doesn't understand it as a RequestBody. So, if we want to use this we must remove the @RequestBody annotation.

Then try the following:

@RequestMapping(value = "/{email}/authenticate", method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE, 
        produces = {MediaType.APPLICATION_ATOM_XML_VALUE, MediaType.APPLICATION_JSON_VALUE})
public @ResponseBody  Representation authenticate(@PathVariable("email") String anEmailAddress, MultiValueMap paramMap) throws Exception {
   if(paramMap == null && paramMap.get("password") == null) {
        throw new IllegalArgumentException("Password not provided");
    }
    return null;
}

Note that removed the annotation @RequestBody

answer: Http Post request with content type application/x-www-form-urlencoded not working in Spring

How to show loading spinner in jQuery?

Use the loading plugin: http://plugins.jquery.com/project/loading

$.loading.onAjax({img:'loading.gif'});

How does DISTINCT work when using JPA and Hibernate

I agree with kazanaki's answer, and it helped me. I wanted to select the whole entity, so I used

 select DISTINCT(c) from Customer c

In my case I have many-to-many relationship, and I want to load entities with collections in one query.

I used LEFT JOIN FETCH and at the end I had to make the result distinct.

What is the difference between functional and non-functional requirements?

Functional requirements

  1. Functional requirements specifies a function that a system or system component must be able to perform. It can be documented in various ways. The most common ones are written descriptions in documents, and use cases.

  2. Use cases can be textual enumeration lists as well as diagrams, describing user actions. Each use case illustrates behavioural scenarios through one or more functional requirements. Often, though, an analyst will begin by eliciting a set of use cases, from which the analyst can derive the functional requirements that must be implemented to allow a user to perform each use case.

  3. Functional requirements is what a system is supposed to accomplish. It may be

    • Calculations
    • Technical details
    • Data manipulation
    • Data processing
    • Other specific functionality
  4. A typical functional requirement will contain a unique name and number, a brief summary, and a rationale. This information is used to help the reader understand why the requirement is needed, and to track the requirement through the development of the system.

Non-functional requirements

LBushkin have already explained more about Non-functional requirements. I will add more.

  1. Non-functional requirements are any other requirement than functional requirements. This are the requirements that specifies criteria that can be used to judge the operation of a system, rather than specific behaviours.

  2. Non-functional requirements are in the form of "system shall be ", an overall property of the system as a whole or of a particular aspect and not a specific function. The system's overall properties commonly mark the difference between whether the development project has succeeded or failed.

  3. Non-functional requirements - can be divided into two main categories:

    • Execution qualities, such as security and usability, which are observable at run time.
    • Evolution qualities, such as testability, maintainability, extensibility and scalability, which are embodied in the static structure of the software system.
  4. Non-functional requirements place restrictions on the product being developed, the development process, and specify external constraints that the product must meet.
  5. The IEEE-Std 830 - 1993 lists 13 non-functional requirements to be included in a Software Requirements Document.
  1. Performance requirements
  2. Interface requirements
  3. Operational requirements
  4. Resource requirements
  5. Verification requirements
  6. Acceptance requirements
  7. Documentation requirements
  8. Security requirements
  9. Portability requirements
  10. Quality requirements
  11. Reliability requirements
  12. Maintainability requirements
  13. Safety requirements

Whether or not a requirement is expressed as a functional or a non-functional requirement may depend:

  • on the level of detail to be included in the requirements document
  • the degree of trust which exists between a system customer and a system developer.

Ex. A system may be required to present the user with a display of the number of records in a database. This is a functional requirement. How up-to-date [update] this number needs to be, is a non-functional requirement. If the number needs to be updated in real time, the system architects must ensure that the system is capable of updating the [displayed] record count within an acceptably short interval of the number of records changing.

References:

  1. Functional requirement
  2. Non-functional requirement
  3. Quantification and Traceability of Requirements

How to handle the click event in Listview in android?

Error is coming in your code from this statement as you said

Intent intent = new Intent(context, SendMessage.class);

This is due to you are providing context of OnItemClickListener anonymous class into the Intent constructor but according to constructor of Intent

android.content.Intent.Intent(Context packageContext, Class<?> cls)

You have to provide context of you activity in which you are using intent that is the MainActivity class context. so your statement which is giving error will be converted to

Intent intent = new Intent(MainActivity.this, SendMessage.class);

Also for sending your message from this MainActivity to SendMessage class please see below code

lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position,
                    long id) {
                ListEntry entry= (ListEntry) parent.getAdapter().getItem(position);
                Intent intent = new Intent(MainActivity.this, SendMessage.class);
                intent.putExtra(EXTRA_MESSAGE, entry.getMessage());
                startActivity(intent);
            }
        });

Please let me know if this helps you

EDIT:- If you are finding some issue to get the value of list do one thing declear your array list

ArrayList<ListEntry> members = new ArrayList<ListEntry>();

globally i.e. before oncreate and change your listener as below

 lv.setOnItemClickListener(new OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {
                    Intent intent = new Intent(MainActivity.this, SendMessage.class);
                    intent.putExtra(EXTRA_MESSAGE, members.get(position));
                    startActivity(intent);
                }
            });

So your whole code will look as

public class MainActivity extends Activity {
    public final static String EXTRA_MESSAGE = "com.example.ListViewTest.MESSAGE";
ArrayList<ListEntry> members = new ArrayList<ListEntry>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        members.add(new ListEntry("BBB","AAA",R.drawable.tab1_hdpi));
        members.add(new ListEntry("ccc","ddd",R.drawable.tab2_hdpi));
        members.add(new ListEntry("assa","cxv",R.drawable.tab3_hdpi));
        members.add(new ListEntry("BcxsadvBB","AcxdxvAA"));
        members.add(new ListEntry("BcxvadsBB","AcxzvAA"));
        members.add(new ListEntry("BcxvBB","AcxvAA"));
        members.add(new ListEntry("BvBB","AcxsvAA"));
        members.add(new ListEntry("BcxvBB","AcxsvzAA"));
        members.add(new ListEntry("Bcxadv","AcsxvAA"));
        members.add(new ListEntry("BcxcxB","AcxsvAA"));
        ListView lv = (ListView)findViewById(R.id.listView1);
        Log.i("testTag","before start adapter");
        StringArrayAdapter ad = new StringArrayAdapter (members,this);
        Log.i("testTag","after start adapter");
        Log.i("testTag","set adapter");
        lv.setAdapter(ad);
        lv.setOnItemClickListener(new OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {
                        Intent intent = new Intent(MainActivity.this, SendMessage.class);
                        intent.putExtra(EXTRA_MESSAGE, members.get(position).getMessage());
                        startActivity(intent);
                    }
                });
    }

Where getMessage() will be a getter method specified in your ListEntry class which you are using to get message which was previously set.

Pandas: Looking up the list of sheets in an excel file

If you:

  • care about performance
  • don't need the data in the file at execution time.
  • want to go with conventional libraries vs rolling your own solution

Below was benchmarked on a ~10Mb xlsx, xlsb file.

xlsx, xls

from openpyxl import load_workbook

def get_sheetnames_xlsx(filepath):
    wb = load_workbook(filepath, read_only=True, keep_links=False)
    return wb.sheetnames

Benchmarks: ~ 14x speed improvement

# get_sheetnames_xlsx vs pd.read_excel
225 ms ± 6.21 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
3.25 s ± 140 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

xlsb

from pyxlsb import open_workbook

def get_sheetnames_xlsb(filepath):
  with open_workbook(filepath) as wb:
     return wb.sheets

Benchmarks: ~ 56x speed improvement

# get_sheetnames_xlsb vs pd.read_excel
96.4 ms ± 1.61 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
5.36 s ± 162 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Notes:

Entity Framework - Linq query with order by and group by

Your requirements are all over the place, but this is the solution to my understanding of them:

To group by Reference property:

var refGroupQuery = (from m in context.Measurements
            group m by m.Reference into refGroup
            select refGroup);

Now you say you want to limit results by "most recent numOfEntries" - I take this to mean you want to limit the returned Measurements... in that case:

var limitedQuery = from g in refGroupQuery
                   select new
                   {
                       Reference = g.Key,
                       RecentMeasurements = g.OrderByDescending( p => p.CreationTime ).Take( numOfEntries )
                   }

To order groups by first Measurement creation time (note you should order the measurements; if you want the earliest CreationTime value, substitue "g.SomeProperty" with "g.CreationTime"):

var refGroupsOrderedByFirstCreationTimeQuery = limitedQuery.OrderBy( lq => lq.RecentMeasurements.OrderBy( g => g.SomeProperty ).First().CreationTime );

To order groups by average CreationTime, use the Ticks property of the DateTime struct:

var refGroupsOrderedByAvgCreationTimeQuery = limitedQuery.OrderBy( lq => lq.RecentMeasurements.Average( g => g.CreationTime.Ticks ) );

What key shortcuts are to comment and uncomment code?

Keyboard accelerators are configurable. You can find out which keyboard accelerators are bound to a command in Tools -> Options on the Environment -> Keyboard page.

These commands are named Edit.CommentSelection and Edit.UncommentSelection.

(With my settings, these are bound to Ctrl+K, Ctrl+C and Ctrl+K, Ctrl+U. I would guess that these are the defaults, at least in the C++ defaults, but I don't know for sure. The best way to find out is to check your settings.)

C# Base64 String to JPEG Image

First, convert the base 64 string to an Image, then use the Image.Save method.

To convert from base 64 string to Image:

 public Image Base64ToImage(string base64String)
 {
    // Convert base 64 string to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    // Convert byte[] to Image
    using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
    {
        Image image = Image.FromStream(ms, true);
        return image;
    }
 }

To convert from Image to base 64 string:

public string ImageToBase64(Image image,System.Drawing.Imaging.ImageFormat format)
{
  using (MemoryStream ms = new MemoryStream())
  {
    // Convert Image to byte[]
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();

    // Convert byte[] to base 64 string
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
  }
}

Finally, you can easily to call Image.Save(filePath); to save the image.

SET NAMES utf8 in MySQL?

This query should be written before the query which create or update data in the database, this query looks like :

mysql_query("set names 'utf8'");

Note that you should write the encode which you are using in the header for example if you are using utf-8 you add it like this in the header or it will couse a problem with Internet Explorer

so your page looks like this

<html>
    <head>
        <title>page title</title>
        <meta charset="UTF-8" />   
    </head>
    <body>
    <?php
            mysql_query("set names 'utf8'");   
            $sql = "INSERT * FROM ..... ";  
            mysql_query($sql);
    ?>    

    </body>
</html>

How to merge a specific commit in Git

I used to cherry pick, but found I had some mysterious issues from time to time. I came across a blog by Raymond Chen, a 25 year veteran at Microsoft, that describes some scenarios where cherry picking can cause issues in certain cases.

One of the rules of thumb is, if you cherry pick from one branch into another, then later merge between those branches, you're likely sooner or later going to experience issues.

Here's a reference to Raymond Chen's blogs on this topic: https://devblogs.microsoft.com/oldnewthing/20180312-00/?p=98215

The only issue I had with Raymond's blog is he did not provide a full working example. So I will attempt to provide one here.

The question above asks how to merge only the commit pointed to by the HEAD in the a-good-feature branch over to master.

Here is how that would be done:

  1. Find the common ancestor between the master and a-good-feature branches.
  2. Create a new branch from that ancestor, we'll call this new branch patch.
  3. Cherry pick one or more commits into this new patch branch.
  4. Merge the patch branch into both the master and a-good-feature branches.
  5. The master branch will now contain the commits, and both master and a-good-feature branches will also have a new common ancestor, which will resolve any future issues if further merging is performed later on.

Here is an example of those commands:

git checkout master...a-good-feature  [checkout the common ancestor]
git checkout -b patch
git cherry-pick a-good-feature  [this is not only the branch name, but also the commit we want]
git checkout master
git merge patch
git checkout a-good-feature
git merge -s ours patch

It might be worth noting that the last line that merged into the a-good-feature branch used the "-s ours" merge strategy. The reason for this is because we simply need to create a commit in the a-good-feature branch that points to a new common ancestor, and since the code is already in that branch, we want to make sure there isn't any chance of a merge conflict. This becomes more important if the commit(s) you are merging are not the most recent.

The scenarios and details surrounding partial merges can get pretty deep, so I recommend reading through all 10 parts of Raymond Chen's blog to gain a full understanding of what can go wrong, how to avoid it, and why this works.

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

Creating Unicode character from its number

This one worked fine for me.

  String cc2 = "2202";
  String text2 = String.valueOf(Character.toChars(Integer.parseInt(cc2, 16)));

Now text2 will have ?.

How to add `style=display:"block"` to an element using jQuery?

Depending on the purpose of setting the display property, you might want to take a look at

$("#yourElementID").show()

and

$("#yourElementID").hide()

How to create EditText with cross(x) button at end of it?

For drawable resource you can use standard android images :

http://androiddrawables.com/Menu.html

For example :

android:background="@android:drawable/ic_menu_close_clear_cancel"

Can Json.NET serialize / deserialize to / from a stream?

UPDATE: This no longer works in the current version, see below for correct answer (no need to vote down, this is correct on older versions).

Use the JsonTextReader class with a StreamReader or use the JsonSerializer overload that takes a StreamReader directly:

var serializer = new JsonSerializer();
serializer.Deserialize(streamReader);

Doctrine 2: Update query with query builder

With a small change, it worked fine for me

$qb=$this->dm->createQueryBuilder('AppBundle:CSSDInstrument')
               ->update()
               ->field('status')->set($status)
               ->field('id')->equals($instrumentId)
               ->getQuery()
               ->execute();

Convert integer value to matching Java Enum

I know this question is a few years old, but as Java 8 has, in the meantime, brought us Optional, I thought I'd offer up a solution using it (and Stream and Collectors):

public enum PcapLinkType {
  DLT_NULL(0),
  DLT_EN3MB(2),
  DLT_AX25(3),
  /*snip, 200 more enums, not always consecutive.*/
  // DLT_UNKNOWN(-1); // <--- NO LONGER NEEDED

  private final int value;
  private PcapLinkType(int value) { this.value = value; }

  private static final Map<Integer, PcapLinkType> map;
  static {
    map = Arrays.stream(values())
        .collect(Collectors.toMap(e -> e.value, e -> e));
  }

  public static Optional<PcapLinkType> fromInt(int value) {
    return Optional.ofNullable(map.get(value));
  }
}

Optional is like null: it represents a case when there is no (valid) value. But it is a more type-safe alternative to null or a default value such as DLT_UNKNOWN because you could forget to check for the null or DLT_UNKNOWN cases. They are both valid PcapLinkType values! In contrast, you cannot assign an Optional<PcapLinkType> value to a variable of type PcapLinkType. Optional makes you check for a valid value first.

Of course, if you want to retain DLT_UNKNOWN for backward compatibility or whatever other reason, you can still use Optional even in that case, using orElse() to specify it as the default value:

public enum PcapLinkType {
  DLT_NULL(0),
  DLT_EN3MB(2),
  DLT_AX25(3),
  /*snip, 200 more enums, not always consecutive.*/
  DLT_UNKNOWN(-1);

  private final int value;
  private PcapLinkType(int value) { this.value = value; }

  private static final Map<Integer, PcapLinkType> map;
  static {
    map = Arrays.stream(values())
        .collect(Collectors.toMap(e -> e.value, e -> e));
  }

  public static PcapLinkType fromInt(int value) {
    return Optional.ofNullable(map.get(value)).orElse(DLT_UNKNOWN);
  }
}

Change old commit message on Git

As Gregg Lind suggested, you can use reword to be prompted to only change the commit message (and leave the commit intact otherwise):

git rebase -i HEAD~n

Here, n is the list of last n commits.

For example, if you use git rebase -i HEAD~4, you may see something like this:

pick e459d80 Do xyz
pick 0459045 Do something
pick 90fdeab Do something else
pick facecaf Do abc

Now replace pick with reword for the commits you want to edit the messages of:

pick e459d80 Do xyz
reword 0459045 Do something
reword 90fdeab Do something else
pick facecaf Do abc

Exit the editor after saving the file, and next you will be prompted to edit the messages for the commits you had marked reword, in one file per message. Note that it would've been much simpler to just edit the commit messages when you replaced pick with reword, but doing that has no effect.

Learn more on GitHub's page for Changing a commit message.

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

Quite a few answers here recommend adding the slf4j-simple dependency to your maven pom file. You might want to check for the most current version.

At https://mvnrepository.com/artifact/org.slf4j/slf4j-simple you'll find the latest version of the SLF4J Simple Binding. Pick the one that suites you best (still 1.7.30 from 2019-12 is the stable version as of 2020-10) and include it to your pom.xml.

For your convenience some dependencies are shown here - but they might not be up-to-date when you read this!

Alpha Version of 2019-10

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-simple</artifactId>
   <version>2.0.0-alpha1</version>
 </dependency>

Beta Version of Feb 2019

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.8.0-beta4</version>
</dependency>

Stable Version 2019-12

<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-simple -->
<dependency>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-simple</artifactId>
   <version>1.7.30</version>
</dependency>

I removed the scope test part thanks to the comment below.

Initializing a member array in constructor initializer

You want to init an array of ints in your constructor? Point it to a static array.

class C 
{
public:
    int *cArray;

};

C::C {
    static int c_init[]{1,2,3};
    cArray = c_init;
}

How do I set multipart in axios with react?

ok. I tried the above two ways but it didnt work for me. After trial and error i came to know that actually the file was not getting saved in 'this.state.file' variable.

fileUpload = (e) => {
    let data = e.target.files
    if(e.target.files[0]!=null){
        this.props.UserAction.fileUpload(data[0], this.fallBackMethod)
    }
}

here fileUpload is a different js file which accepts two params like this

export default (file , callback) => {
const formData = new FormData();
formData.append('fileUpload', file);

return dispatch => {
    axios.put(BaseUrl.RestUrl + "ur/url", formData)
        .then(response => {
            callback(response.data);
        }).catch(error => {
         console.log("*****  "+error)
    });
}

}

don't forget to bind method in the constructor. Let me know if you need more help in this.

Set multiple system properties Java command line

There's nothing on the Documentation that mentions about anything like that.

Here's a quote:

-Dproperty=value Set a system property value. If value is a string that contains spaces, you must enclose the string in double quotes:

java -Dfoo="some string" SomeClass

How to migrate GIT repository from one server to a new one

This is a variation on this answer, currently suggested by gitlab to "migrate" a git repository from one server to another.

  1. Let us assume that your old project is called existing_repo, stored in a existing_repo folder.

  2. Create a repo on your new server. We will assume that the url of that new project is git@newserver:newproject.git

  3. Open a command-line interface, and enter the following:

    cd existing_repo
    git remote rename origin old-origin
    git remote add origin git@newserver:newproject.git
    git push -u origin --all
    git push -u origin --tags
    

The benefits of this approach is that you do not delete the branch that corresponds to your old server.

How can I get a specific number child using CSS?

For modern browsers, use td:nth-child(2) for the second td, and td:nth-child(3) for the third. Remember that these retrieve the second and third td for every row.

If you need compatibility with IE older than version 9, use sibling combinators or JavaScript as suggested by Tim. Also see my answer to this related question for an explanation and illustration of his method.

How do I configure PyCharm to run py.test tests?

It's poorly documented to be sure. Once you get add a new configuration from defaults, you will be in the realm of running the "/Applications/PyCharm CE.app/Contents/helpers/pycharm/pytestrunner.py" script. It's not documented and has its own ideas of command line arguments.

You can:

  1. Try to play around, reverse the script, and see if you can somehow get py.test to accept arguments. It might work; it didn't in the first half hour for me.
  2. Just run "py.test *.py" from a console.

Oddly, you will find it hard to find any discussion as JetBrains does a good job of bombing Google algorithms with its own pages.

How do I use T-SQL's Case/When?

If logical test is against a single column then you could use something like

USE AdventureWorks2012;  
GO  
SELECT   ProductNumber, Category =  
      CASE ProductLine  
         WHEN 'R' THEN 'Road'  
         WHEN 'M' THEN 'Mountain'  
         WHEN 'T' THEN 'Touring'  
         WHEN 'S' THEN 'Other sale items'  
         ELSE 'Not for sale'  
      END,  
   Name  
FROM Production.Product  
ORDER BY ProductNumber;  
GO  

More information - https://docs.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql?view=sql-server-2017

How get sound input from microphone in python, and process it on the fly?

...and when I got one how to process it (do I need to use Fourier Transform like it was instructed in the above post)?

If you want a "tap" then I think you are interested in amplitude more than frequency. So Fourier transforms probably aren't useful for your particular goal. You probably want to make a running measurement of the short-term (say 10 ms) amplitude of the input, and detect when it suddenly increases by a certain delta. You would need to tune the parameters of:

  • what is the "short-term" amplitude measurement
  • what is the delta increase you look for
  • how quickly the delta change must occur

Although I said you're not interested in frequency, you might want to do some filtering first, to filter out especially low and high frequency components. That might help you avoid some "false positives". You could do that with an FIR or IIR digital filter; Fourier isn't necessary.

ASP.NET 2.0 - How to use app_offline.htm

Make sure your app_offline.htm file is at least 512 bytes long. A zero-byte app_offline.htm will have no effect.

UPDATE: Newer versions of ASP.NET/IIS may behave better than when I first wrote this.

UPDATE 2: If you are using ASP.NET MVC, add the following to web.config:

<?xml version="1.0"?>
<configuration>
    <system.webServer>
        <modules runAllManagedModulesForAllRequests="true" />
    </system.webServer>
</configuration>

Jenkins Slave port number for firewall

I have a similar scenario, and had no problem connecting after setting the JNLP port as you describe, and adding a single firewall rule allowing a connection on the server using that port. Granted it is a randomly selected client port going to a known server port (a host:ANY -> server:1 rule is needed).

From my reading of the source code, I don't see a way to set the local port to use when making the request from the slave. It's unfortunate, it would be a nice feature to have.

Alternatives:

Use a simple proxy on your client that listens on port N and then does forward all data to the actual Jenkins server on the remote host using a constant local port. Connect your slave to this local proxy instead of the real Jenkins server.

Create a custom Jenkins slave build that allows an option to specify the local port to use.

Remember also if you are using HTTPS via a self-signed certificate, you must alter the configuration jenkins-slave.xml file on the slave to specify the -noCertificateCheck option on the command line.

Android; Check if file exists without creating a new one

When you say "in you package folder," do you mean your local app files? If so you can get a list of them using the Context.fileList() method. Just iterate through and look for your file. That's assuming you saved the original file with Context.openFileOutput().

Sample code (in an Activity):

public void onCreate(...) {
    super.onCreate(...);
    String[] files = fileList();
    for (String file : files) {
        if (file.equals(myFileName)) {
            //file exits
        }
    }
}

Is there a job scheduler library for node.js?

You can use timexe

It's simple to use, light weight, has no dependencies, has an improved syntax over cron, with a resolution in milliseconds and works in the browser.

Install:

npm install timexe

Use:

var timexe = require('timexe');
var res = timexe("* * * 15 30", function(){ console.log("It's now 3:30 pm"); });

(I'm the author)

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

Looks like a resources related error. I would start there.

I got this ("Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details") first time related to pictures. Resize solved it. Or another time just repaired the links to resources.

database vs. flat files

  1. Databases can handle querying tasks, so you don't have to walk over files manually. Databases can handle very complicated queries.
  2. Databases can handle indexing tasks, so if tasks like get record with id = x can be VERY fast
  3. Databases can handle multiprocess/multithreaded access.
  4. Databases can handle access from network
  5. Databases can watch for data integrity
  6. Databases can update data easily (see 1) )
  7. Databases are reliable
  8. Databases can handle transactions and concurrent access
  9. Databases + ORMs let you manipulate data in very programmer friendly way.

Python speed testing - Time Difference - milliseconds

You may want to look into the profile modules. You'll get a better read out of where your slowdowns are, and much of your work will be full-on automated.

How to implement a tree data-structure in Java?

There is actually a pretty good tree structure implemented in the JDK.

Have a look at javax.swing.tree, TreeModel, and TreeNode. They are designed to be used with the JTreePanel but they are, in fact, a pretty good tree implementation and there is nothing stopping you from using it with out a swing interface.

Note that as of Java 9 you may wish not to use these classes as they will not be present in the 'Compact profiles'.

Where to place $PATH variable assertions in zsh?

tl;dr version: use ~/.zshrc

And read the man page to understand the differences between:

~/.zshrc, ~/.zshenv and ~/.zprofile.


Regarding my comment

In my comment attached to the answer kev gave, I said:

This seems to be incorrect - /etc/profile isn't listed in any zsh documentation I can find.

This turns out to be partially incorrect: /etc/profile may be sourced by zsh. However, this only occurs if zsh is "invoked as sh or ksh"; in these compatibility modes:

The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by $HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. [man zshall, "Compatibility"].

The ArchWiki ZSH link says:

At login, Zsh sources the following files in this order:
/etc/profile
This file is sourced by all Bourne-compatible shells upon login

This implys that /etc/profile is always read by zsh at login - I haven't got any experience with the Arch Linux project; the wiki may be correct for that distribution, but it is not generally correct. The information is incorrect compared to the zsh manual pages, and doesn't seem to apply to zsh on OS X (paths in $PATH set in /etc/profile do not make it to my zsh sessions).



To address the question:

where exactly should I be placing my rvm, python, node etc additions to my $PATH?

Generally, I would export my $PATH from ~/.zshrc, but it's worth having a read of the zshall man page, specifically the "STARTUP/SHUTDOWN FILES" section - ~/.zshrc is read for interactive shells, which may or may not suit your needs - if you want the $PATH for every zsh shell invoked by you (both interactive and not, both login and not, etc), then ~/.zshenv is a better option.

Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?

There's a bunch of files read on startup (check the linked man pages), and there's a reason for that - each file has it's particular place (settings for every user, settings for user-specific, settings for login shells, settings for every shell, etc).
Don't worry about ~/.zshenv not existing - if you need it, make it, and it will be read.

.bashrc and .bash_profile are not read by zsh, unless you explicitly source them from ~/.zshrc or similar; the syntax between bash and zsh is not always compatible. Both .bashrc and .bash_profile are designed for bash settings, not zsh settings.

Properly Handling Errors in VBA (Excel)

Block 2 doesn't work because it doesn't reset the Error Handler potentially causing an endless loop. For Error Handling to work properly in VBA, you need a Resume statement to clear the Error Handler. The Resume also reactivates the previous Error Handler. Block 2 fails because a new error would go back to the previous Error Handler causing an infinite loop.

Block 3 fails because there is no Resume statement so any attempt at error handling after that will fail.

Every error handler must be ended by exiting the procedure or a Resume statement. Routing normal execution around an error handler is confusing. This is why error handlers are usually at the bottom.

But here is another way to handle an error in VBA. It handles the error inline like Try/Catch in VB.net There are a few pitfalls, but properly managed it works quite nicely.

Sub InLineErrorHandling()

    'code without error handling

BeginTry1:

    'activate inline error handler
    On Error GoTo ErrHandler1

        'code block that may result in an error
        Dim a As String: a = "Abc"
        Dim c As Integer: c = a 'type mismatch

ErrHandler1:

    'handle the error
    If Err.Number <> 0 Then

        'the error handler has deactivated the previous error handler

        MsgBox (Err.Description)

        'Resume (or exit procedure) is the only way to get out of an error handling block
        'otherwise the following On Error statements will have no effect
        'CAUTION: it also reactivates the previous error handler
        Resume EndTry1
    End If

EndTry1:
    'CAUTION: since the Resume statement reactivates the previous error handler
    'you must ALWAYS use an On Error GoTo statement here
    'because another error here would cause an endless loop
    'use On Error GoTo 0 or On Error GoTo <Label>
    On Error GoTo 0

    'more code with or without error handling

End Sub

Sources:

The key to making this work is to use a Resume statement immediately followed by another On Error statement. The Resume is within the error handler and diverts code to the EndTry1 label. You must immediately set another On Error statement to avoid problems as the previous error handler will "resume". That is, it will be active and ready to handle another error. That could cause the error to repeat and enter an infinite loop.

To avoid using the previous error handler again you need to set On Error to a new error handler or simply use On Error Goto 0 to cancel all error handling.

Find html label associated with a given input

First, scan the page for labels, and assign a reference to the label from the actual form element:

var labels = document.getElementsByTagName('LABEL');
for (var i = 0; i < labels.length; i++) {
    if (labels[i].htmlFor != '') {
         var elem = document.getElementById(labels[i].htmlFor);
         if (elem)
            elem.label = labels[i];         
    }
}

Then, you can simply go:

document.getElementById('MyFormElem').label.innerHTML = 'Look ma this works!';

No need for a lookup array :)

MySQL: how to get the difference between two timestamps in seconds

UNIX_TIMESTAMP(ts1) - UNIX_TIMESTAMP(ts2)

If you want an unsigned difference, add an ABS() around the expression.

Alternatively, you can use TIMEDIFF(ts1, ts2) and then convert the time result to seconds with TIME_TO_SEC().

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

AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float percent = 0.7f;
int seventyVolume = (int) (maxVolume*percent);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, seventyVolume, 0);

Wordpress keeps redirecting to install-php after migration

Well finally I have solved the problem. And surprise, surprise It was the freaking UPPERCASE letter in my table prefix. I had it this way in my wp-config file wp_C5n but for some reason most of the tables got a prefix wp_c5n. But not all. So what id did was I changed my table prefix in wp_config file to all lowercase and then went through all the tables by hand via phpMyadmin to see If there's any uppercase tables left. There where about 3. They were inside usermeta table and inside options table. Now finally everything is working. Did a quick search through wordpress codex but did not find anything mentioning not to use uppercase characters.

How can I create numbered map markers in Google Maps V3?

This has now been added to the Mapping documentation and requires no third party code.

You can combine these two samples:

https://developers.google.com/maps/documentation/javascript/examples/marker-labels

https://developers.google.com/maps/documentation/javascript/examples/icon-simple

To get code like this:

var labelIndex = 0;
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789';

function initialize() {
  var bangalore = { lat: 12.97, lng: 77.59 };
  var map = new google.maps.Map(document.getElementById('map-canvas'), {
    zoom: 12,
    center: bangalore
  });

  // This event listener calls addMarker() when the map is clicked.
  google.maps.event.addListener(map, 'click', function(event) {
    addMarker(event.latLng, map);
  });

  // Add a marker at the center of the map.
  addMarker(bangalore, map);
}

// Adds a marker to the map.
function addMarker(location, map) {
  // Add the marker at the clicked location, and add the next-available label
  // from the array of alphabetical characters.
  var marker = new google.maps.Marker({
    position: location,
    label: labels[labelIndex],
    map: map,
    icon: 'image.png'
  });
}

google.maps.event.addDomListener(window, 'load', initialize);

Note that if you have more than 35 markers, this method will not work as the label only shows the first character (using A-Z and 0-9 makes 35). Please vote for this Google Maps Issue to request that this restriction be lifted.

How to fix date format in ASP .NET BoundField (DataFormatString)?

The following links will help you:

In Client side design page you can try this: {0:G}

OR

You can convert that datetime format inside the query itself from the database:

Comments in Markdown

kramdown—the Ruby-based markdown engine that is the default for Jekyll and thus GitHub Pages—has built-in comment support through its extension syntax:

{::comment}
This text is completely ignored by kramdown - a comment in the text.
{:/comment}

Do you see {::comment}this text{:/comment}?
{::comment}some other comment{:/}

This has the benefit of allowing in-line comments, but the downside of not being portable to other Markdown engines.

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

This is likely when you have a PRIMARY KEY field and you are inserting a value that is duplicating or you have the INSERT_IDENTITY flag set to on

how to load url into div tag

Not using iframes puts you in a world of handling #document security issues with cross domain and links firing unexpected ways that was not intended for originally, do you really need bad Advertisements?

You can use jquery .load function to send the page to whatever html element you want to target, assuming your not getting this from another domain.

You can use javascript .innerHTML value to set and to rewrite the element with whatever you want, but if you add another file you might be writing against 2 documents in 1... like a in another

iframes are old, another way we can add "src" into the html alone without any use for javascript. But it's old, prehistoric, and just plain OLD! Frameset makes it worse because I can put #document in those to handle multiple html files. An Old way people created navigation menu's Long and before people had FLIP phones.

1.) Yes you will have to work in Javascript if you do NOT want to use an Iframe.

2.) There is a good hack in which you can set the domain to equal each other without having to set server stuff around. Means you will have to have edit capabilities of the documents.

3.) javascript window.document is limited to the iframe itself and can NOT go above the iframe if you want to grab something through the DOM itself. Because it treats it like a separate tab, it also defines it in another document object model.

SQL Server: Multiple table joins with a WHERE clause

SELECT Computer.Computer_Name, Application1.Name, Max(Soft.[Version]) as Version1
FROM Application1
inner JOIN Software
    ON Application1.ID = Software.Application_Id
cross join Computer
Left JOIN Software_Computer
    ON Software_Computer.Computer_Id = Computer.ID and Software_Computer.Software_Id = Software.Id
Left JOIN Software as Soft
    ON Soft.Id = Software_Computer.Software_Id
WHERE Computer.ID = 1 
GROUP BY Computer.Computer_Name, Application1.Name 

XPath to fetch SQL XML value

I always go back to this article SQL Server 2005 XQuery and XML-DML - Part 1 to know how to use the XML features in SQL Server 2005.

For basic XPath know-how, I'd recommend the W3Schools tutorial.

Addition for BigDecimal

Using Java8 lambdas

List<BigDecimal> items = Arrays.asList(a, b, c, .....);

items.stream().filter(Objects::nonNull).reduce(BigDecimal.ZERO, BigDecimal::add);

This covers cases where the some or all of the objects in the list is null.

SPA best practices for authentication and session management

You can increase security in authentication process by using JWT (JSON Web Tokens) and SSL/HTTPS.

The Basic Auth / Session ID can be stolen via:

  • MITM attack (Man-In-The-Middle) - without SSL/HTTPS
  • An intruder gaining access to a user's computer
  • XSS

By using JWT you're encrypting the user's authentication details and storing in the client, and sending it along with every request to the API, where the server/API validates the token. It can't be decrypted/read without the private key (which the server/API stores secretly) Read update.

The new (more secure) flow would be:

Login

  • User logs in and sends login credentials to API (over SSL/HTTPS)
  • API receives login credentials
  • If valid:
    • Register a new session in the database Read update
    • Encrypt User ID, Session ID, IP address, timestamp, etc. in a JWT with a private key.
  • API sends the JWT token back to the client (over SSL/HTTPS)
  • Client receives the JWT token and stores in localStorage/cookie

Every request to API

  • User sends a HTTP request to API (over SSL/HTTPS) with the stored JWT token in the HTTP header
  • API reads HTTP header and decrypts JWT token with its private key
  • API validates the JWT token, matches the IP address from the HTTP request with the one in the JWT token and checks if session has expired
  • If valid:
    • Return response with requested content
  • If invalid:
    • Throw exception (403 / 401)
    • Flag intrusion in the system
    • Send a warning email to the user.

Updated 30.07.15:

JWT payload/claims can actually be read without the private key (secret) and it's not secure to store it in localStorage. I'm sorry about these false statements. However they seem to be working on a JWE standard (JSON Web Encryption).

I implemented this by storing claims (userID, exp) in a JWT, signed it with a private key (secret) the API/backend only knows about and stored it as a secure HttpOnly cookie on the client. That way it cannot be read via XSS and cannot be manipulated, otherwise the JWT fails signature verification. Also by using a secure HttpOnly cookie, you're making sure that the cookie is sent only via HTTP requests (not accessible to script) and only sent via secure connection (HTTPS).

Updated 17.07.16:

JWTs are by nature stateless. That means they invalidate/expire themselves. By adding the SessionID in the token's claims you're making it stateful, because its validity doesn't now only depend on signature verification and expiry date, it also depends on the session state on the server. However the upside is you can invalidate tokens/sessions easily, which you couldn't before with stateless JWTs.

How to change spinner text size and text color?

Just wanted to make a small change on the correct answer at the top. Make a custom XML file for your spinner item inside the layout directory.

spinner_style.xml:

Give your customized color and size to text in this file.

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

     <TextView  
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_width="match_parent" 
            android:layout_height="wrap_content"
            style="?android:attr/spinnerItemStyle"
            android:singleLine="true"
            android:ellipsize="marquee"
            android:textAlignment="inherit"
            android:textSize="15sp"
            android:textColor="#FF0000"         
            android:padding="5dp"
            />

Now use this file to show your spinner items inside your java file:

ArrayAdapter<String> adapter = new ArrayAdapter<>(this,R.layout.spinner_style,list);
adapter.setDropDownViewResource(R.layout.spinner_style);

Is there a better way to do optional function parameters in JavaScript?

If you're using the Underscore library (you should, it's an awesome library):

_.defaults(optionalArg, 'defaultValue');

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

Find the most common element in a list

A simpler one-liner:

def most_common(lst):
    return max(set(lst), key=lst.count)

How to declare a structure in a header that is to be used by multiple files in c?

a.h:

#ifndef A_H
#define A_H

struct a { 
    int i;
    struct b {
        int j;
    }
};

#endif

there you go, now you just need to include a.h to the files where you want to use this structure.

Is it ok to run docker from inside docker?

Yes, we can run docker in docker, we'll need to attach the unix sockeet "/var/run/docker.sock" on which the docker daemon listens by default as volume to the parent docker using "-v /var/run/docker.sock:/var/run/docker.sock". Sometimes, permissions issues may arise for docker daemon socket for which you can write "sudo chmod 757 /var/run/docker.sock".

And also it would require to run the docker in privileged mode, so the commands would be:

sudo chmod 757 /var/run/docker.sock

docker run --privileged=true -v /var/run/docker.sock:/var/run/docker.sock -it ...

Why am I getting this error: No mapping specified for the following EntitySet/AssociationSet - Entity1?

A quicker way for me was to delete the tables and re-add them. It Auto-mapped them. :)

calling java methods in javascript code

Java is a server side language, whereas javascript is a client side language. Both cannot communicate. If you have setup some server side script using Java you could use AJAX on the client in order to send an asynchronous request to it and thus invoke any possible Java functions. For example if you use jQuery as js framework you may take a look at the $.ajax() method. Or if you wanted to do it using plain javascript, here's a tutorial.

Extreme wait-time when taking a SQL Server database offline

In SSMS: right-click on SQL server icon, Activity Monitor. Open Processes. Find the processed connected. Right-click on the process, Kill.

Difference between Statement and PreparedStatement

Statement is static and prepared statement is dynamic.

Statement is suitable for DDL and prepared statment for DML.

Statement is slower while prepared statement is faster.

more differences (archived)

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

Try to delete the maven folder at ~/.m2/repository/org/apache/maven and build your project again to force the maven libraries be downloaded. This worked for me the last time I faced this java.lang.NoClassDefFoundError: org/apache/maven/shared/filtering/MavenFilteringException.

Getting 404 Not Found error while trying to use ErrorDocument

The ErrorDocument directive, when supplied a local URL path, expects the path to be fully qualified from the DocumentRoot. In your case, this means that the actual path to the ErrorDocument is

ErrorDocument 404 /hellothere/error/404page.html

How to terminate a process in vbscript

Dim shll : Set shll = CreateObject("WScript.Shell")
Set Rt = shll.Exec("Notepad") : wscript.sleep 4000 : Rt.Terminate

Run the process with .Exec.

Then wait for 4 seconds.

After that kill this process.

Regex to match a 2-digit number (to validate Credit/Debit Card Issue number)

You need to use anchors to match the beginning of the string ^ and the end of the string $

^[0-9]{2}$

Java decimal formatting using String.format?

Here is a small code snippet that does the job:

double a = 34.51234;

NumberFormat df = DecimalFormat.getInstance();
df.setMinimumFractionDigits(2);
df.setMaximumFractionDigits(4);
df.setRoundingMode(RoundingMode.DOWN);

System.out.println(df.format(a));

How to cast ArrayList<> from List<>

The second approach is clearly wrong if you want to cast. It instantiate a new ArrayList.

However the first approach should work just fine, if and only if getAllTasks return an ArrayList.

It is really needed for you to have an ArrayList ? isn't the List interface enough ? What you are doing can leads to Runtime Exception if the type isn't correct.

If getAllTasks() return an ArrayList you should change the return type in the class definition and then you won't need a cast and if it's returning something else, you can't cast to ArrayList.

Using {% url ??? %} in django templates

Judging from your example, shouldn't it be {% url myproject.login.views.login_view %} and end of story? (replace myproject with your actual project name)

ORACLE and TRIGGERS (inserted, updated, deleted)

I've changed my code like this and it works:

CREATE or REPLACE TRIGGER test001
  AFTER INSERT OR UPDATE OR DELETE ON tabletest001
  REFERENCING OLD AS old_buffer NEW AS new_buffer 
  FOR EACH ROW WHEN (new_buffer.field1 = 'HBP00' OR old_buffer.field1 = 'HBP00') 

DECLARE
      Operation       NUMBER;
      CustomerCode    CHAR(10 BYTE);
BEGIN

IF DELETING THEN 
  Operation := 3;
  CustomerCode := :old_buffer.field1;
END IF;

IF INSERTING THEN 
  Operation := 1;
  CustomerCode := :new_buffer.field1;
END IF;

IF UPDATING THEN 
  Operation := 2;
  CustomerCode := :new_buffer.field1;
END IF;    

// DO SOMETHING ...

EXCEPTION
    WHEN OTHERS THEN ErrorCode := SQLCODE;

END;

Fatal error: Call to undefined function: ldap_connect()

If you are a Windows user, this is a common error when you use XAMPP since LDAP is not enabled by default.

You can follow this steps to make sure LDAP works in your XAMPP:

  • [Your Drive]:\xampp\php\php.ini: In this file uncomment the following line:

     extension=php_ldap.dll
    
  • Move the file: libsasl.dll, from [Your Drive]:\xampp\php to [Your Drive]:\xampp\apache\bin (Note: moving the file is needed only for XAMPP prior to version: 5.6.28)

  • Restart Apache.

  • You can now use functions of the LDAP Module!

If you use Linux:

For php5:

sudo apt-get install php5-ldap

For php7:

sudo apt-get install php7.0-ldap

If you are using the latest version of PHP you can do

sudo apt-get install php-ldap

running the above command should do the trick.

if for any reason it doesn't work check your php.ini configuration to enable ldap, remove the semicolon before extension=ldap to uncomment, save and restart Apache

jQuery Selector: Id Ends With?

$('element[id$=txtTitle]')

It's not strictly necessary to quote the text fragment you are matching against

Int to Decimal Conversion - Insert decimal point at specified location

Simple math.

double result = ((double)number) / 100.0;

Although you may want to use decimal rather than double: decimal vs double! - Which one should I use and when?

How to programmatically close a JFrame

I have tried this, write your own code for formWindowClosing() event.

 private void formWindowClosing(java.awt.event.WindowEvent evt) {                                   
    int selectedOption = JOptionPane.showConfirmDialog(null,
            "Do you want to exit?",
            "FrameToClose",
            JOptionPane.YES_NO_OPTION);
    if (selectedOption == JOptionPane.YES_OPTION) {
        setVisible(false);
        dispose();
    } else {
        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
    }
}    

This asks user whether he want to exit the Frame or Application.

How can I create a marquee effect?

The following should do what you want.

@keyframes marquee {
    from  { text-indent:  100% }
    to    { text-indent: -100% }
}

Get element by id - Angular2

Complate Angular Way ( Set/Get value by Id ):

// In Html tag

 <button (click) ="setValue()">Set Value</button>
 <input type="text"  #userNameId />

// In component .ts File

    export class testUserClass {
       @ViewChild('userNameId') userNameId: ElementRef;

      ngAfterViewInit(){
         console.log(this.userNameId.nativeElement.value );
       }

      setValue(){
        this.userNameId.nativeElement.value = "Sample user Name";
      }



   }

How do I declare class-level properties in Objective-C?

Here's a thread safe way of doing it:

// Foo.h
@interface Foo {
}

+(NSDictionary*) dictionary;

// Foo.m
+(NSDictionary*) dictionary
{
  static NSDictionary* fooDict = nil;

  static dispatch_once_t oncePredicate;

  dispatch_once(&oncePredicate, ^{
        // create dict
    });

  return fooDict;
}

These edits ensure that fooDict is only created once.

From Apple documentation: "dispatch_once - Executes a block object once and only once for the lifetime of an application."

Custom li list-style with font-awesome icon

I'd like to provide an alternate, easier solution that is specific to FontAwesome. If you're using a different iconic font, JOPLOmacedo's answer is still perfectly fine for use.

FontAwesome now handles list styles internally with CSS classes.

Here's the official example:

<ul class="fa-ul">
  <li><span class="fa-li"><i class="fas fa-check-square"></i></span>List icons can</li>
  <li><span class="fa-li"><i class="fas fa-check-square"></i></span>be used to</li>
  <li><span class="fa-li"><i class="fas fa-spinner fa-pulse"></i></span>replace bullets</li>
  <li><span class="fa-li"><i class="far fa-square"></i></span>in lists</li>
</ul>

Parsing JSON in Spring MVC using Jackson JSON

The whole point of using a mapping technology like Jackson is that you can use Objects (you don't have to parse the JSON yourself).

Define a Java class that resembles the JSON you will be expecting.

e.g. this JSON:

{
"foo" : ["abc","one","two","three"],
"bar" : "true",
"baz" : "1"
}

could be mapped to this class:

public class Fizzle{
    private List<String> foo;
    private boolean bar;
    private int baz;
    // getters and setters omitted
}

Now if you have a Controller method like this:

@RequestMapping("somepath")
@ResponseBody
public Fozzle doSomeThing(@RequestBody Fizzle input){
    return new Fozzle(input);
}

and you pass in the JSON from above, Jackson will automatically create a Fizzle object for you, and it will serialize a JSON view of the returned Object out to the response with mime type application/json.

For a full working example see this previous answer of mine.

How can I display a tooltip on an HTML "option" tag?

Why use a dropdown at all? The only way the user will see your explanatory text is by blindly hovering over one of the options.

I think it would be preferable to use a radio button group, and next to each item, put a tooltip icon indicating additional information, as well as displaying it after selection (like you currently have it).

I realize this doesn't exactly solve your problem, but I don't see the point in struggling with an html element that's notorious for its inflexibility when you could just use one that's better suited in the first place.

GCM with PHP (Google Cloud Messaging)

Here's a library I forked from CodeMonkeysRU.

The reason I forked was because Google requires exponential backoff. I use a redis server to queue messages and resend after a set time.

I've also updated it to support iOS.

https://github.com/stevetauber/php-gcm-queue

Insert Data Into Temp Table with Query

Fastest way to do this is using "SELECT INTO" command e.g.

SELECT * INTO #TempTableName
FROM....

This will create a new table, you don't have to create it in advance.

How to handle login pop up window using Selenium WebDriver?

The easiest way to handle the Authentication Pop up is to enter the Credentials in Url Itself. For Example, I have Credentials like Username: admin and Password: admin:

WebDriver driver = new ChromeDriver();
driver.get("https://admin:admin@your website url");

How to get file path in iPhone app

If your tiles are not in your bundle, either copied from the bundle or downloaded from the internet you can get the directory like this

NSString *documentdir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *tileDirectory = [documentdir stringByAppendingPathComponent:@"xxxx/Tiles"];
NSLog(@"Tile Directory: %@", tileDirectory);

Concat a string to SELECT * MySql

You simply can't do that in SQL. You have to explicitly list the fields and concat each one:

SELECT CONCAT(field1, '/'), CONCAT(field2, '/'), ... FROM `socials` WHERE 1

If you are using an app, you can use SQL to read the column names, and then use your app to construct a query like above. See this stackoverflow question to find the column names: Get table column names in mysql?

Date to milliseconds and back to date in Swift

let dateTimeStamp = NSDate(timeIntervalSince1970:Double(currentTimeInMiliseconds())/1000)  //UTC time  //YOUR currentTimeInMiliseconds METHOD
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone.localTimeZone() 
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle


let strDateSelect = dateFormatter.stringFromDate(dateTimeStamp)
print("Local Time", strDateSelect) //Local time


let dateFormatter2 = NSDateFormatter()
dateFormatter2.timeZone = NSTimeZone(name: "UTC") as NSTimeZone!
dateFormatter2.dateFormat = "yyyy-MM-dd"

let date3 = dateFormatter.dateFromString(strDateSelect)
print("DATE",date3)

How to apply a function to two columns of Pandas dataframe

My example to your questions:

def get_sublist(row, col1, col2):
    return mylist[row[col1]:row[col2]+1]
df.apply(get_sublist, axis=1, col1='col_1', col2='col_2')

Using external images for CSS custom cursors

Originally from a Codepen pen by Chris Coyier of Codepen/CSS-Tricks

_x000D_
_x000D_
.auto            { cursor: auto; }
.default         { cursor: default; }
.none            { cursor: none; }
.context-menu    { cursor: context-menu; }
.help            { cursor: help; }
.pointer         { cursor: pointer; }
.progress        { cursor: progress; }
.wait            { cursor: wait; }
.cell            { cursor: cell; }
.crosshair       { cursor: crosshair; }
.text            { cursor: text; }
.vertical-text   { cursor: vertical-text; }
.alias           { cursor: alias; }
.copy            { cursor: copy; }
.move            { cursor: move; }
.no-drop         { cursor: no-drop; }
.not-allowed     { cursor: not-allowed; }
.all-scroll      { cursor: all-scroll; }
.col-resize      { cursor: col-resize; }
.row-resize      { cursor: row-resize; }
.n-resize        { cursor: n-resize; }
.e-resize        { cursor: e-resize; }
.s-resize        { cursor: s-resize; }
.w-resize        { cursor: w-resize; }
.ns-resize       { cursor: ns-resize; }
.ew-resize       { cursor: ew-resize; }
.ne-resize       { cursor: ne-resize; }
.nw-resize       { cursor: nw-resize; }
.se-resize       { cursor: se-resize; }
.sw-resize       { cursor: sw-resize; }
.nesw-resize     { cursor: nesw-resize; }
.nwse-resize     { cursor: nwse-resize; }

body {
  text-align: center;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";

}
.cursors {
  display: flex;
  flex-wrap: wrap;
}
.cursors > div {
  flex: 150px;
  padding: 10px 2px;
  white-space: nowrap;
  border: 1px solid #eee;
  border-radius: 5px;
  margin: 0 5px 5px 0;
}
.cursors > div:hover {
  background: #eee;
}

HTML CSSResult
EDIT ON
.svg {
  cursor: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/9632/heart.svg), auto;
}

.svg-base64 {
  cursor: url(data:text/html;base64,PHN2ZyB2ZXJzaW9uPSIxLjEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4Ig0KCSB2aWV3Qm94PSItMjQxIDI0MyAxNiAxNiIgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+DQo8c3R5bGUgdHlwZT0idGV4dC9jc3MiPg0KCS5zdDB7ZmlsbDojRkYwMDAwO30NCjwvc3R5bGU+DQo8cGF0aCBjbGFzcz0ic3QwIiBkPSJNLTIyOS4yLDI0NGMtMS43LDAtMy4xLDEuNC0zLjgsMi44Yy0wLjctMS40LTIuMS0yLjgtMy44LTIuOGMtMi4zLDAtNC4yLDEuOS00LjIsNC4yYzAsNC43LDQuOCw2LDgsMTAuNg0KCWMzLjEtNC42LDgtNi4xLDgtMTAuNkMtMjI1LDI0NS45LTIyNi45LDI0NC0yMjkuMiwyNDRMLTIyOS4yLDI0NHoiLz4NCjwvc3ZnPg0K), auto;
}

.png-base64 {
  cursor: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGQAAABkCAYAAABw4pVUAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAyhpVFh0WE1MOmNvbS5hZG9iZS54bXAAAAAAADw/eHBhY2tldCBiZWdpbj0i77u/IiBpZD0iVzVNME1wQ2VoaUh6cmVTek5UY3prYzlkIj8+IDx4OnhtcG1ldGEgeG1sbnM6eD0iYWRvYmU6bnM6bWV0YS8iIHg6eG1wdGs9IkFkb2JlIFhNUCBDb3JlIDUuNi1jMDY3IDc5LjE1Nzc0NywgMjAxNS8wMy8zMC0yMzo0MDo0MiAgICAgICAgIj4gPHJkZjpSREYgeG1sbnM6cmRmPSJodHRwOi8vd3d3LnczLm9yZy8xOTk5LzAyLzIyLXJkZi1zeW50YXgtbnMjIj4gPHJkZjpEZXNjcmlwdGlvbiByZGY6YWJvdXQ9IiIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bWxuczp4bXBNTT0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL21tLyIgeG1sbnM6c3RSZWY9Imh0dHA6Ly9ucy5hZG9iZS5jb20veGFwLzEuMC9zVHlwZS9SZXNvdXJjZVJlZiMiIHhtcDpDcmVhdG9yVG9vbD0iQWRvYmUgUGhvdG9zaG9wIENDIDIwMTUgKE1hY2ludG9zaCkiIHhtcE1NOkluc3RhbmNlSUQ9InhtcC5paWQ6M0EwMEYyRjlDMjZFMTFFNUI4QkRFMkRBRDg3QkNFRUQiIHhtcE1NOkRvY3VtZW50SUQ9InhtcC5kaWQ6M0EwMEYyRkFDMjZFMTFFNUI4QkRFMkRBRDg3QkNFRUQiPiA8eG1wTU06RGVyaXZlZEZyb20gc3RSZWY6aW5zdGFuY2VJRD0ieG1wLmlpZDozQTAwRjJGN0MyNkUxMUU1QjhCREUyREFEODdCQ0VFRCIgc3RSZWY6ZG9jdW1lbnRJRD0ieG1wLmRpZDozQTAwRjJGOEMyNkUxMUU1QjhCREUyREFEODdCQ0VFRCIvPiA8L3JkZjpEZXNjcmlwdGlvbj4gPC9yZGY6UkRGPiA8L3g6eG1wbWV0YT4gPD94cGFja2V0IGVuZD0iciI/Pi/X/ugAAAY6SURBVHja7J1bbBVFHMZ3pVajTQoxCCgaNECqJiJV41NFCdF6CRKrvrRcXkyMD6gQE16MMSbESx9INCYkeHkywRhNiJFUoK3EqDVoRVQIiBpoQDFKC4jYtK7fZP+L0+2e6V7ncvx/ydc953S7Z+b7dWbP7O6Z9YMg8Fj26AKOgIGwGAgDYTEQBsKqQA3yE9/3C28wCLd5C3wnfCPcAl8NN8GNtNrv8M/wN/BuuAfvfNxkECj3HCzuhm+ncs+DL6Nfj8Jn4CPwASp3H7wH5R4r/N7y0EM8iVygMj7cBm+BhwOx2Wweh3fCDwYaW614L3rPnVSGrOUepjqLuvtFgJxnUAQIgVgBD+aoTC0fhDuKVDBluTvovcoq9yBl4RsBgrUXwZ+VWKG4xX/ttRXAuIa2XVW5RSaLtAHBWtPgZ+GxCisV+QzcVSKMLtpm1eUeo4ymVQoEa8yEd2moUNyb0lZO8U+0yUC5RVYzKwGC386F9xuoVOT3g/8+pWWB0Uh/a6rcIrO5pQIhGEMGKxV5WxYoBGObBeUeUkHJBASvzoC/s6BSkd9J031RN7XVonKLDGcUAkIfD3ssqlTkF1MAecHCcvckfSzOAmSDhZWK/IgCxkMWl3tDLiB41gKPWlyxkSA8vBEv97ycRwt0WWTakgfIDosrFblP7gKoi93lQLl3ZAKCR+0OVCryGqncaxwqd3sSEF8GER3txSv9WCxx5Ij1r/ACenwInuVIuT9G2nfEj/Y2JPTBrQ7B8AjAeumxK1oisgaUr2qeDyGtdPC8zpOOno8SWU8AMqHLoj7rGDybz91p0S/wFXKfFT8ZdAPD0KrZlHnNc+pLOSPtWqoCspjz0a7FKiALOR/tWqgCMp/z0a75KiBNnI92Nak+9vJ3E0woCPxaLYRlWAzEvP5RARnhfLRrRAXkBOejXScYiF0aUgE5zPlo10EVkP2cj3Z9qwKyl/PRri9VA8Nm/DzpVfhVANYE/QlPx8BwLLGF+OFHMG4l+tQb/wZW0sDwA85Jm96LvzDpqhM8uxkP93BWlUt8b3EOWsgfMoNJLcQPdzIHOK/K9a6AEX+x1rGsLZxX5Xot6cVaF8pNpxHkpZxbJfoESbdFT5RdFnVbw1hs5twq0/O1fpHYQqiViKsAD3MrKV0f+eEEBV7qFkKtRFwz2835lSox5livWmGqE1QveeEUGKxy1O3Hjl2l7rKkruseLD7kLAtLHLgVF1efm5Rxmi5L6rq2Y/EG51l4ENiZBCNrlxXpKfhHzjW3ngaMwTQrTtllSV3XTVh8Dl/E+WbS20i1U7VCpi5L6rq+xuIxzjeTxDHBR7P8QabLgADlLSxe5pxT6Si8HJmdzZRx2i5L6rrELApb4Q7OvKbEjHltfspT4rm6LKmVjHthn9jPuSfqNHyfn/P6hFxXLuLN/sZiBfwF5z9Bf4lckM9A3g3kvpSUTve2e3wyS4ZxP3LpLbKRQtf2+uEFEcu4pXin4HuLwji/QylhVtJmeMChWRTKnnPlttIYlAGEoFwC9/7PYPwG31pqoygLCEG52PB0ejp9ND6rj3VAonEK/Hqdw/h+qnkUrQFCUMR34zbWKYyBNDONWgVEAvNEzim8bfV2sa8sPSddQAiKmG7vXB3AeDNInqzHLSAERUxWf9JhGBsrnYteNxCCcj18xDEQortdW/Wo0ggQgnIlvNcRGKOqmU/rAog0qu9zYPS9TNdxF6NACEqjZbNOx0ffrToPhBkHQlDE3W1etQyGmKN9ge4jk1YAkcA8ZwmMH+CrjGRgExCCstYwjH3w5cbqbxsQgtJlaFQ/QF+/8BjIZCidmqEIGM3G620rEILygKabAFgBw3ogBGV5xVCsgeEEkIqh7DO9z3ASCEF5uOR9ivhoa91E0c4AISirS4JxXNxU0so6ugSEoKwrCONUYPEk0c4BISjdBe66eZfVdXMUiE+3zMsK5HHPcjkJhKCIy4w+zQDjFc8BOQuEoMxKeeZxN3whA9EDpRU+q4BxLHDoPijOAyEoqxTnwducqks9ACEomxOAPONcPeoIiNjJD0ow+ovcd52BlAPlOtqfnLZ1JJ4FSIPnuPzwBvLr8HAcj39yvj6utox6Fd+ugoGwGAgDYeXVvwIMAGCAb3XkplDRAAAAAElFTkSuQmCC"), auto;
}

.png {
  cursor: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/9632/heart.png"), auto;
}

.gif {
  cursor: url("https://s3-us-west-2.amazonaws.com/s.cdpn.io/9632/tina.gif"), auto;
}

.cursors {
  display: flex;
  justify-content: flex-start;
  align-items: stretch;
  height: 100vh;
}

.cursors > div {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-grow: 1;
  box-sizing: border-box;
  padding: 10px 2px;
  text-align: center;
}
_x000D_
<h1>The Cursors of CSS</h1>

<div class="cursors">
    <div class="auto">auto</div>
    <div class="default">default</div>
    <div class="none">none</div>
    <div class="context-menu">context-menu</div>
    <div class="help">help</div>
    <div class="pointer">pointer</div>
    <div class="progress">progress</div>
    <div class="wait">wait</div>
    <div class="cell">cell</div>
    <div class="crosshair">crosshair</div>
    <div class="text">text</div>
    <div class="vertical-text">vertical-text</div>
    <div class="alias">alias</div>
    <div class="copy">copy</div>
    <div class="move">move</div>
    <div class="no-drop">no-drop</div>
    <div class="not-allowed">not-allowed</div>
    <div class="all-scroll">all-scroll</div>
    <div class="col-resize">col-resize</div>
    <div class="row-resize">row-resize</div>
    <div class="n-resize">n-resize</div>
    <div class="s-resize">s-resize</div>
    <div class="e-resize">e-resize</div>
    <div class="w-resize">w-resize</div>
    <div class="ns-resize">ns-resize</div>
    <div class="ew-resize">ew-resize</div>
    <div class="ne-resize">ne-resize</div>
    <div class="nw-resize">nw-resize</div>
    <div class="se-resize">se-resize</div>
    <div class="sw-resize">sw-resize</div>
    <div class="nesw-resize">nesw-resize</div>
    <div class="nwse-resize">nwse-resize</div>
</div>
<br><br><br><br><br><br><br><br><br>
<h1>Custom Image</h1>
<div class="cursors">
  <div class="svg"><p>SVG</p></div>
  <div class="svg-base64">Base 64 SVG</div>
  <div class="png-base64">Base 64 PNG</div>
  <div class="png">PNG</div>
  <div class="gif">GIF</div>
</div>
_x000D_
_x000D_
_x000D_

Java JTable setting Column Width

With JTable.AUTO_RESIZE_OFF, the table will not change the size of any of the columns for you, so it will take your preferred setting. If it is your goal to have the columns default to your preferred size, except to have the last column fill the rest of the pane, You have the option of using the JTable.AUTO_RESIZE_LAST_COLUMN autoResizeMode, but it might be most effective when used with TableColumn.setMaxWidth() instead of TableColumn.setPreferredWidth() for all but the last column.

Once you are satisfied that AUTO_RESIZE_LAST_COLUMN does in fact work, you can experiment with a combination of TableColumn.setMaxWidth() and TableColumn.setMinWidth()

Word-wrap in an HTML table

As mentioned, putting the text within div almost works. You just have to specify the width of the div, which is fortunate for layouts which are static.

This works on FF 3.6, IE 8, Chrome.

<td>
  <div style="width: 442px; word-wrap: break-word">
    <!-- Long Content Here-->
  </div>
</td>

Twitter Bootstrap 3 Sticky Footer

This has been solved by flexbox, once and forever:

https://philipwalton.github.io/solved-by-flexbox/demos/sticky-footer/

The HTML

<body class="Site">
  <header>…</header>
  <main class="Site-content">…</main>
  <footer>…</footer>
</body>

The CSS

.Site {
  display: flex;
  min-height: 100vh;
  flex-direction: column;
}

.Site-content {
  flex: 1;
}

android:layout_height 50% of the screen size

You can use android:weightSum="2" on the parent layout combined with android:layout_height="1" on the child layout.

           <LinearLayout
                android:layout_height="match_parent"
                android:layout_width="wrap_content"
                android:weightSum="2"
                >

                <ImageView
                    android:layout_height="1"
                    android:layout_width="wrap_content" />

            </LinearLayout>

How to download image using requests

Here is a more user-friendly answer that still uses streaming.

Just define these functions and call getImage(). It will use the same file name as the url and write to the current directory by default, but both can be changed.

import requests
from StringIO import StringIO
from PIL import Image

def createFilename(url, name, folder):
    dotSplit = url.split('.')
    if name == None:
        # use the same as the url
        slashSplit = dotSplit[-2].split('/')
        name = slashSplit[-1]
    ext = dotSplit[-1]
    file = '{}{}.{}'.format(folder, name, ext)
    return file

def getImage(url, name=None, folder='./'):
    file = createFilename(url, name, folder)
    with open(file, 'wb') as f:
        r = requests.get(url, stream=True)
        for block in r.iter_content(1024):
            if not block:
                break
            f.write(block)

def getImageFast(url, name=None, folder='./'):
    file = createFilename(url, name, folder)
    r = requests.get(url)
    i = Image.open(StringIO(r.content))
    i.save(file)

if __name__ == '__main__':
    # Uses Less Memory
    getImage('http://www.example.com/image.jpg')
    # Faster
    getImageFast('http://www.example.com/image.jpg')

The request guts of getImage() are based on the answer here and the guts of getImageFast() are based on the answer above.

PHP Fatal error: Cannot access empty property

Interesting:

  1. You declared an array var $my_value = array();
  2. Pushed value into it $a->my_value[] = 'b';
  3. Assigned a string to variable. (so it is no more array) $a->set_value ('c');
  4. Tried to push a value into array, that does not exist anymore. (it's string) $a->my_class('d');

And your foreach wont work anymore.

" netsh wlan start hostednetwork " command not working no matter what I try

If you have a wifi button or switch on your laptop make sure it is turned on! Then use the netsh commands that other people have stated

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

This is my Makefile for different debug/release output directories. This Makefile was tested successfully on Ubuntu linux. It should work seamlessly on Windows provided that Mingw-w64 is installed correctly.

ifeq ($(OS),Windows_NT)
    ObjExt=obj
    mkdir_CMD=mkdir
    rm_CMD=rmdir /S /Q
else
    ObjExt=o
    mkdir_CMD=mkdir -p
    rm_CMD=rm -rf
endif

CC     =gcc
CFLAGS =-Wall -ansi
LD     =gcc

OutRootDir=.
DebugDir  =Debug
ReleaseDir=Release


INSTDIR =./bin
INCLUDE =.

SrcFiles=$(wildcard *.c)
EXEC_main=myapp

OBJ_C_Debug   =$(patsubst %.c,  $(OutRootDir)/$(DebugDir)/%.$(ObjExt),$(SrcFiles))
OBJ_C_Release =$(patsubst %.c,  $(OutRootDir)/$(ReleaseDir)/%.$(ObjExt),$(SrcFiles))

.PHONY: Release Debug cleanDebug cleanRelease clean

# Target specific variables
release: CFLAGS += -O -DNDEBUG
debug:   CFLAGS += -g

################################################
#Callable Targets
release: $(OutRootDir)/$(ReleaseDir)/$(EXEC_main)
debug:   $(OutRootDir)/$(DebugDir)/$(EXEC_main)

cleanDebug:
    -$(rm_CMD) "$(OutRootDir)/$(DebugDir)"
    @echo cleanDebug done

cleanRelease:
    -$(rm_CMD) "$(OutRootDir)/$(ReleaseDir)"
    @echo cleanRelease done

clean: cleanDebug cleanRelease
################################################

# Pattern Rules
# Multiple targets cannot be used with pattern rules [https://www.gnu.org/software/make/manual/html_node/Multiple-Targets.html]
$(OutRootDir)/$(ReleaseDir)/%.$(ObjExt): %.c | $(OutRootDir)/$(ReleaseDir)
    $(CC) -I$(INCLUDE) $(CFLAGS) -c $< -o"$@"

$(OutRootDir)/$(DebugDir)/%.$(ObjExt):   %.c | $(OutRootDir)/$(DebugDir)
    $(CC) -I$(INCLUDE) $(CFLAGS) -c $< -o"$@"

# Create output directory
$(OutRootDir)/$(ReleaseDir) $(OutRootDir)/$(DebugDir) $(INSTDIR):
    -$(mkdir_CMD) $@

# Create the executable
# Multiple targets [https://www.gnu.org/software/make/manual/html_node/Multiple-Targets.html]
$(OutRootDir)/$(ReleaseDir)/$(EXEC_main): $(OBJ_C_Release)
$(OutRootDir)/$(DebugDir)/$(EXEC_main):   $(OBJ_C_Debug)
$(OutRootDir)/$(ReleaseDir)/$(EXEC_main) $(OutRootDir)/$(DebugDir)/$(EXEC_main):
    $(LD) $^ -o$@

What version of Java is running in Eclipse?

try this :

public class vm
{
  public static void main(String[] args)
  {
      System.getProperty("sun.arch.data.model") 
  }
}

compile and run. it will return either 32 or 64 as per your java version . . .

How do I give ASP.NET permission to write to a folder in Windows 7?

My immediate solution (since I couldn't find the ASP.NET worker process) was to give write (that is, Modify) permission to IIS_IUSRS. This worked. I seem to recall that in WinXP I had to specifically given the ASP.NET worker process write permission to accomplish this. Maybe my memory is faulty, but anyway...

@DraganRadivojevic wrote that he thought this was dangerous from a security viewpoint. I do not disagree, but since this was my workstation and not a network server, it seemed relatively safe. In any case, his answer is better and is what I finally settled on after chasing down a fail-path due to not specifying the correct domain for the AppPool user.

Most efficient way to check if a file is empty in Java on Windows

This is an improvement of Saik0's answer based on Anwar Shaikh's comment that too big files (above available memory) will throw an exception:

Using Apache Commons FileUtils

private void printEmptyFileName(final File file) throws IOException {
    /*Arbitrary big-ish number that definitely is not an empty file*/
    int limit = 4096;
    if(file.length < limit && FileUtils.readFileToString(file).trim().isEmpty()) {
        System.out.println("File is empty: " + file.getName());
    }        
}

The import org.junit cannot be resolved

In starting code line copy past 'Junit' or 'TestNG' elements will show with Error till you import library with the Project File.

To import Libraries in to project:

Right Click on the Project --> Properties --> Java Build Path --> Libraries -> Add Library -> 'Junit' or 'TestNG'

Add Junit Libraries

Using jQuery to build table rows from AJAX response(json)

Use .append instead of .html

var response = "[{
      "rank":"9",
      "content":"Alon",
      "UID":"5"
     },
     {
       "rank":"6",
       "content":"Tala",
       "UID":"6"
    }]";

// convert string to JSON
response = $.parseJSON(response);

$(function() {
    $.each(response, function(i, item) {
        var $tr = $('<tr>').append(
            $('<td>').text(item.rank),
            $('<td>').text(item.content),
            $('<td>').text(item.UID)
        ); //.appendTo('#records_table');
        console.log($tr.wrap('<p>').html());
    });
});

Web colors in an Android color xml resource file

With the help of excel I have converted the link above to android xml ready code:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="Black">#000000</color>
    <color name="Gunmetal">#2C3539</color>
    <color name="Midnight">#2B1B17</color>
    <color name="Charcoal">#34282C</color>
    <color name="Dark_Slate_Grey">#25383C</color>
    <color name="Oil">#3B3131</color>
    <color name="Black_Cat">#413839</color>
    <color name="Black_Eel">#463E3F</color>
    <color name="Black_Cow">#4C4646</color>
    <color name="Gray_Wolf">#504A4B</color>
    <color name="Vampire_Gray">#565051</color>
    <color name="Gray_Dolphin">#5C5858</color>
    <color name="Carbon_Gray">#625D5D</color>
    <color name="Ash_Gray">#666362</color>
    <color name="Cloudy_Gray">#6D6968</color>
    <color name="Smokey_Gray">#726E6D</color>
    <color name="Gray">#736F6E</color>
    <color name="Granite">#837E7C</color>
    <color name="Battleship_Gray">#848482</color>
    <color name="Gray_Cloud">#B6B6B4</color>
    <color name="Gray_Goose">#D1D0CE</color>
    <color name="Platinum">#E5E4E2</color>
    <color name="Metallic_Silver">#BCC6CC</color>
    <color name="Blue_Gray">#98AFC7</color>
    <color name="Light_Slate_Gray">#6D7B8D</color>
    <color name="Slate_Gray">#657383</color>
    <color name="Jet_Gray">#616D7E</color>
    <color name="Mist_Blue">#646D7E</color>
    <color name="Marble_Blue">#566D7E</color>
    <color name="Slate_Blue">#737CA1</color>
    <color name="Steel_Blue">#4863A0</color>
    <color name="Blue_Jay">#2B547E</color>
    <color name="Dark_Slate_Blue">#2B3856</color>
    <color name="Midnight_Blue">#151B54</color>
    <color name="Navy_Blue">#000080</color>
    <color name="Blue_Whale">#342D7E</color>
    <color name="Lapis_Blue">#15317E</color>
    <color name="Cornflower_Blue">#151B8D</color>
    <color name="Earth_Blue">#0000A0</color>
    <color name="Cobalt_Blue">#0020C2</color>
    <color name="Blueberry_Blue">#0041C2</color>
    <color name="Sapphire_Blue">#2554C7</color>
    <color name="Blue_Eyes">#1569C7</color>
    <color name="Royal_Blue">#2B60DE</color>
    <color name="Blue_Orchid">#1F45FC</color>
    <color name="Blue_Lotus">#6960EC</color>
    <color name="Light_Slate_Blue">#736AFF</color>
    <color name="Silk_Blue">#488AC7</color>
    <color name="Blue_Ivy">#3090C7</color>
    <color name="Blue_Koi">#659EC7</color>
    <color name="Columbia_Blue">#87AFC7</color>
    <color name="Baby_Blue">#95B9C7</color>
    <color name="Light_Steel_Blue">#728FCE</color>
    <color name="Ocean_Blue">#2B65EC</color>
    <color name="Blue_Ribbon">#306EFF</color>
    <color name="Blue_Dress">#157DEC</color>
    <color name="Dodger_Blue">#1589FF</color>
    <color name="Butterfly_Blue">#38ACEC</color>
    <color name="Iceberg">#56A5EC</color>
    <color name="Crystal_Blue">#5CB3FF</color>
    <color name="Deep_Sky_Blue">#3BB9FF</color>
    <color name="Denim_Blue">#79BAEC</color>
    <color name="Light_Sky_Blue">#82CAFA</color>
    <color name="Sky_Blue">#82CAFF</color>
    <color name="Jeans_Blue">#A0CFEC</color>
    <color name="Blue_Angel">#B7CEEC</color>
    <color name="Pastel_Blue">#B4CFEC</color>
    <color name="Sea_Blue">#C2DFFF</color>
    <color name="Powder_Blue">#C6DEFF</color>
    <color name="Coral_Blue">#AFDCEC</color>
    <color name="Light_Blue">#ADDFFF</color>
    <color name="Robin_Egg_Blue">#BDEDFF</color>
    <color name="Pale_Blue_Lily">#CFECEC</color>
    <color name="Light_Cyan">#E0FFFF</color>
    <color name="Water">#EBF4FA</color>
    <color name="AliceBlue">#F0F8FF</color>
    <color name="Azure">#F0FFFF</color>
    <color name="Light_Slate">#CCFFFF</color>
    <color name="Light_Aquamarine">#93FFE8</color>
    <color name="Electric_Blue">#9AFEFF</color>
    <color name="Aquamarine">#7FFFD4</color>
    <color name="Cyan_or_Aqua">#00FFFF</color>
    <color name="Tron_Blue">#7DFDFE</color>
    <color name="Blue_Zircon">#57FEFF</color>
    <color name="Blue_Lagoon">#8EEBEC</color>
    <color name="Celeste">#50EBEC</color>
    <color name="Blue_Diamond">#4EE2EC</color>
    <color name="Tiffany_Blue">#81D8D0</color>
    <color name="Cyan_Opaque">#92C7C7</color>
    <color name="Blue_Hosta">#77BFC7</color>
    <color name="Northern_Lights_Blue">#78C7C7</color>
    <color name="Medium_Turquoise">#48CCCD</color>
    <color name="Turquoise">#43C6DB</color>
    <color name="Jellyfish">#46C7C7</color>
    <color name="Mascaw_Blue_Green">#43BFC7</color>
    <color name="Light_Sea_Green">#3EA99F</color>
    <color name="Dark_Turquoise">#3B9C9C</color>
    <color name="Sea_Turtle_Green">#438D80</color>
    <color name="Medium_Aquamarine">#348781</color>
    <color name="Greenish_Blue">#307D7E</color>
    <color name="Grayish_Turquoise">#5E7D7E</color>
    <color name="Beetle_Green">#4C787E</color>
    <color name="Teal">#008080</color>
    <color name="Sea_Green">#4E8975</color>
    <color name="Camouflage_Green">#78866B</color>
    <color name="Hazel_Green">#617C58</color>
    <color name="Venom_Green">#728C00</color>
    <color name="Fern_Green">#667C26</color>
    <color name="Dark_Forrest_Green">#254117</color>
    <color name="Medium_Sea_Green">#306754</color>
    <color name="Medium_Forest_Green">#347235</color>
    <color name="Seaweed_Green">#437C17</color>
    <color name="Pine_Green">#387C44</color>
    <color name="Jungle_Green">#347C2C</color>
    <color name="Shamrock_Green">#347C17</color>
    <color name="Medium_Spring_Green">#348017</color>
    <color name="Forest_Green">#4E9258</color>
    <color name="Green_Onion">#6AA121</color>
    <color name="Spring_Green">#4AA02C</color>
    <color name="Lime_Green">#41A317</color>
    <color name="Clover_Green">#3EA055</color>
    <color name="Green_Snake">#6CBB3C</color>
    <color name="Alien_Green">#6CC417</color>
    <color name="Green_Apple">#4CC417</color>
    <color name="Yellow_Green">#52D017</color>
    <color name="Kelly_Green">#4CC552</color>
    <color name="Zombie_Green">#54C571</color>
    <color name="Frog_Green">#99C68E</color>
    <color name="Green_Peas">#89C35C</color>
    <color name="Dollar_Bill_Green">#85BB65</color>
    <color name="Dark_Sea_Green">#8BB381</color>
    <color name="Iguana_Green">#9CB071</color>
    <color name="Avocado_Green">#B2C248</color>
    <color name="Pistachio_Green">#9DC209</color>
    <color name="Salad_Green">#A1C935</color>
    <color name="Hummingbird_Green">#7FE817</color>
    <color name="Nebula_Green">#59E817</color>
    <color name="Stoplight_Go_Green">#57E964</color>
    <color name="Algae_Green">#64E986</color>
    <color name="Jade_Green">#5EFB6E</color>
    <color name="Green">#00FF00</color>
    <color name="Emerald_Green">#5FFB17</color>
    <color name="Lawn_Green">#87F717</color>
    <color name="Chartreuse">#8AFB17</color>
    <color name="Dragon_Green">#6AFB92</color>
    <color name="Mint_green">#98FF98</color>
    <color name="Green_Thumb">#B5EAAA</color>
    <color name="Light_Jade">#C3FDB8</color>
    <color name="Tea_Green">#CCFB5D</color>
    <color name="Green_Yellow">#B1FB17</color>
    <color name="Slime_Green">#BCE954</color>
    <color name="Goldenrod">#EDDA74</color>
    <color name="Harvest_Gold">#EDE275</color>
    <color name="Sun_Yellow">#FFE87C</color>
    <color name="Yellow">#FFFF00</color>
    <color name="Corn_Yellow">#FFF380</color>
    <color name="Parchment">#FFFFC2</color>
    <color name="Cream">#FFFFCC</color>
    <color name="Lemon_Chiffon">#FFF8C6</color>
    <color name="Cornsilk">#FFF8DC</color>
    <color name="Beige">#F5F5DC</color>
    <color name="AntiqueWhite">#FAEBD7</color>
    <color name="BlanchedAlmond">#FFEBCD</color>
    <color name="Vanilla">#F3E5AB</color>
    <color name="Tan_Brown">#ECE5B6</color>
    <color name="Peach">#FFE5B4</color>
    <color name="Mustard">#FFDB58</color>
    <color name="Rubber_Ducky_Yellow">#FFD801</color>
    <color name="Bright_Gold">#FDD017</color>
    <color name="Golden_brown">#EAC117</color>
    <color name="Macaroni_and_Cheese">#F2BB66</color>
    <color name="Saffron">#FBB917</color>
    <color name="Beer">#FBB117</color>
    <color name="Cantaloupe">#FFA62F</color>
    <color name="Bee_Yellow">#E9AB17</color>
    <color name="Brown_Sugar">#E2A76F</color>
    <color name="BurlyWood">#DEB887</color>
    <color name="Deep_Peach">#FFCBA4</color>
    <color name="Ginger_Brown">#C9BE62</color>
    <color name="School_Bus_Yellow">#E8A317</color>
    <color name="Sandy_Brown">#EE9A4D</color>
    <color name="Fall_Leaf_Brown">#C8B560</color>
    <color name="Gold">#D4A017</color>
    <color name="Sand">#C2B280</color>
    <color name="Cookie_Brown">#C7A317</color>
    <color name="Caramel">#C68E17</color>
    <color name="Brass">#B5A642</color>
    <color name="Khaki">#ADA96E</color>
    <color name="Camel_brown">#C19A6B</color>
    <color name="Bronze">#CD7F32</color>
    <color name="Tiger_Orange">#C88141</color>
    <color name="Cinnamon">#C58917</color>
    <color name="Dark_Goldenrod">#AF7817</color>
    <color name="Copper">#B87333</color>
    <color name="Wood">#966F33</color>
    <color name="Oak_Brown">#806517</color>
    <color name="Moccasin">#827839</color>
    <color name="Army_Brown">#827B60</color>
    <color name="Sandstone">#786D5F</color>
    <color name="Mocha">#493D26</color>
    <color name="Taupe">#483C32</color>
    <color name="Coffee">#6F4E37</color>
    <color name="Brown_Bear">#835C3B</color>
    <color name="Red_Dirt">#7F5217</color>
    <color name="Sepia">#7F462C</color>
    <color name="Orange_Salmon">#C47451</color>
    <color name="Rust">#C36241</color>
    <color name="Red_Fox">#C35817</color>
    <color name="Chocolate">#C85A17</color>
    <color name="Sedona">#CC6600</color>
    <color name="Papaya_Orange">#E56717</color>
    <color name="Halloween_Orange">#E66C2C</color>
    <color name="Pumpkin_Orange">#F87217</color>
    <color name="Construction_Cone_Orange">#F87431</color>
    <color name="Sunrise_Orange">#E67451</color>
    <color name="Mango_Orange">#FF8040</color>
    <color name="Dark_Orange">#F88017</color>
    <color name="Coral">#FF7F50</color>
    <color name="Basket_Ball_Orange">#F88158</color>
    <color name="Light_Salmon">#F9966B</color>
    <color name="Tangerine">#E78A61</color>
    <color name="Dark_Salmon">#E18B6B</color>
    <color name="Light_Coral">#E77471</color>
    <color name="Bean_Red">#F75D59</color>
    <color name="Valentine_Red">#E55451</color>
    <color name="Shocking_Orange">#E55B3C</color>
    <color name="Red">#FF0000</color>
    <color name="Scarlet">#FF2400</color>
    <color name="Ruby_Red">#F62217</color>
    <color name="Ferrari_Red">#F70D1A</color>
    <color name="Fire_Engine_Red">#F62817</color>
    <color name="Lava_Red">#E42217</color>
    <color name="Love_Red">#E41B17</color>
    <color name="Grapefruit">#DC381F</color>
    <color name="Chestnut_Red">#C34A2C</color>
    <color name="Cherry_Red">#C24641</color>
    <color name="Mahogany">#C04000</color>
    <color name="Chilli_Pepper">#C11B17</color>
    <color name="Cranberry">#9F000F</color>
    <color name="Red_Wine">#990012</color>
    <color name="Burgundy">#8C001A</color>
    <color name="Blood_Red">#7E3517</color>
    <color name="Sienna">#8A4117</color>
    <color name="Sangria">#7E3817</color>
    <color name="Firebrick">#800517</color>
    <color name="Maroon">#810541</color>
    <color name="Plum_Pie">#7D0541</color>
    <color name="Velvet_Maroon">#7E354D</color>
    <color name="Plum_Velvet">#7D0552</color>
    <color name="Rosy_Finch">#7F4E52</color>
    <color name="Puce">#7F5A58</color>
    <color name="Dull_Purple">#7F525D</color>
    <color name="Rosy_Brown">#B38481</color>
    <color name="Khaki_Rose">#C5908E</color>
    <color name="Pink_Bow">#C48189</color>
    <color name="Lipstick_Pink">#C48793</color>
    <color name="Rose">#E8ADAA</color>
    <color name="Desert_Sand">#EDC9AF</color>
    <color name="Pig_Pink">#FDD7E4</color>
    <color name="Cotton_Candy">#FCDFFF</color>
    <color name="Pink_Bubblegum">#FFDFDD</color>
    <color name="Misty_Rose">#FBBBB9</color>
    <color name="Pink">#FAAFBE</color>
    <color name="Light_Pink">#FAAFBA</color>
    <color name="Flamingo_Pink">#F9A7B0</color>
    <color name="Pink_Rose">#E7A1B0</color>
    <color name="Pink_Daisy">#E799A3</color>
    <color name="Cadillac_Pink">#E38AAE</color>
    <color name="Blush_Red">#E56E94</color>
    <color name="Hot_Pink">#F660AB</color>
    <color name="Watermelon_Pink">#FC6C85</color>
    <color name="Violet_Red">#F6358A</color>
    <color name="Deep_Pink">#F52887</color>
    <color name="Pink_Cupcake">#E45E9D</color>
    <color name="Pink_Lemonade">#E4287C</color>
    <color name="Neon_Pink">#F535AA</color>
    <color name="Magenta">#FF00FF</color>
    <color name="Dimorphotheca_Magenta">#E3319D</color>
    <color name="Bright_Neon_Pink">#F433FF</color>
    <color name="Pale_Violet_Red">#D16587</color>
    <color name="Tulip_Pink">#C25A7C</color>
    <color name="Medium_Violet_Red">#CA226B</color>
    <color name="Rogue_Pink">#C12869</color>
    <color name="Burnt_Pink">#C12267</color>
    <color name="Bashful_Pink">#C25283</color>
    <color name="Carnation_Pink">#C12283</color>
    <color name="Plum">#B93B8F</color>
    <color name="Viola_Purple">#7E587E</color>
    <color name="Purple_Iris">#571B7E</color>
    <color name="Plum_Purple">#583759</color>
    <color name="Indigo">#4B0082</color>
    <color name="Purple_Monster">#461B7E</color>
    <color name="Purple_Haze">#4E387E</color>
    <color name="Eggplant">#614051</color>
    <color name="Grape">#5E5A80</color>
    <color name="Purple_Jam">#6A287E</color>
    <color name="Dark_Orchid">#7D1B7E</color>
    <color name="Purple_Flower">#A74AC7</color>
    <color name="Medium_Orchid">#B048B5</color>
    <color name="Purple_Amethyst">#6C2DC7</color>
    <color name="Dark_Violet">#842DCE</color>
    <color name="Violet">#8D38C9</color>
    <color name="Purple_Sage_Bush">#7A5DC7</color>
    <color name="Lovely_Purple">#7F38EC</color>
    <color name="Purple">#8E35EF</color>
    <color name="Aztec_Purple">#893BFF</color>
    <color name="Medium_Purple">#8467D7</color>
    <color name="Jasmine_Purple">#A23BEC</color>
    <color name="Purple_Daffodil">#B041FF</color>
    <color name="Tyrian_Purple">#C45AEC</color>
    <color name="Crocus_Purple">#9172EC</color>
    <color name="Purple_Mimosa">#9E7BFF</color>
    <color name="Heliotrope_Purple">#D462FF</color>
    <color name="Crimson">#E238EC</color>
    <color name="Purple_Dragon">#C38EC7</color>
    <color name="Lilac">#C8A2C8</color>
    <color name="Blush_Pink">#E6A9EC</color>
    <color name="Mauve">#E0B0FF</color>
    <color name="Wisteria_Purple">#C6AEC7</color>
    <color name="Blossom_Pink">#F9B7FF</color>
    <color name="Thistle">#D2B9D3</color>
    <color name="Periwinkle">#E9CFEC</color>
    <color name="Lavender_Pinocchio">#EBDDE2</color>
    <color name="Lavender">#E3E4FA</color>
    <color name="Pearl">#FDEEF4</color>
    <color name="SeaShell">#FFF5EE</color>
    <color name="Milk_White">#FEFCFF</color>
    <color name="White">#FFFFFF</color>
</resources>

How to use a table type in a SELECT FROM statement?

Prior to Oracle 12C you cannot select from PL/SQL-defined tables, only from tables based on SQL types like this:

CREATE OR REPLACE TYPE exch_row AS OBJECT(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);


CREATE OR REPLACE TYPE exch_tbl AS TABLE OF exch_row;

In Oracle 12C it is now possible to select from PL/SQL tables that are defined in a package spec.

@import vs #import - iOS 7

It seems that since XCode 7.x a lot of warnings are coming out when enabling clang module with CLANG_ENABLE_MODULES

Take a look at Lots of warnings when building with Xcode 7 with 3rd party libraries

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Quoting http://php.net/manual/en/intro.mssql.php:

The MSSQL extension is not available anymore on Windows with PHP 5.3 or later. SQLSRV, an alternative driver for MS SQL is available from Microsoft: » http://msdn.microsoft.com/en-us/sqlserver/ff657782.aspx.

Once you downloaded that, follow the instructions at this page:

In a nutshell:

Put the driver file in your PHP extension directory.
Modify the php.ini file to include the driver. For example:

extension=php_sqlsrv_53_nts_vc9.dll  

Restart the Web server.

See Also (copied from that page)

The PHP Manual for the SQLSRV extension is located at http://php.net/manual/en/sqlsrv.installation.php and offers the following for Installation:

The SQLSRV extension is enabled by adding appropriate DLL file to your PHP extension directory and the corresponding entry to the php.ini file. The SQLSRV download comes with several driver files. Which driver file you use will depend on 3 factors: the PHP version you are using, whether you are using thread-safe or non-thread-safe PHP, and whether your PHP installation was compiled with the VC6 or VC9 compiler. For example, if you are running PHP 5.3, you are using non-thread-safe PHP, and your PHP installation was compiled with the VC9 compiler, you should use the php_sqlsrv_53_nts_vc9.dll file. (You should use a non-thread-safe version compiled with the VC9 compiler if you are using IIS as your web server). If you are running PHP 5.2, you are using thread-safe PHP, and your PHP installation was compiled with the VC6 compiler, you should use the php_sqlsrv_52_ts_vc6.dll file.

The drivers can also be used with PDO.

ImportError: No module named psycopg2

Recently faced this issue on my production server. I had installed pyscopg2 using

sudo pip install psycopg2

It worked beautifully on my local, but had me for a run on my ec2 server.

sudo python -m pip install psycopg2

The above command worked for me there. Posting here just in case it would help someone in future.

Minimal web server using netcat

LOL, a super lame hack, but at least curl and firefox accepts it:

while true ; do (dd if=/dev/zero count=10000;echo -e "HTTP/1.1\n\n $(date)") | nc -l  1500  ; done

You better replace it soon with something proper!

Ah yes, my nc were not exactly the same as yours, it did not like the -p option.

What do "branch", "tag" and "trunk" mean in Subversion repositories?

In addition to what Nick has said you can find out more at Streamed Lines: Branching Patterns for Parallel Software Development

enter image description here

In this figure main is the trunk, rel1-maint is a branch and 1.0 is a tag.

Freely convert between List<T> and IEnumerable<T>

List<string> myList = new List<string>();
IEnumerable<string> myEnumerable = myList;
List<string> listAgain = myEnumerable.ToList();

How long is the SHA256 hash?

Why would you make it VARCHAR? It doesn't vary. It's always 64 characters, which can be determined by running anything into one of the online SHA-256 calculators.

Install pip in docker

This command worked fine for me:

RUN apt-get -y install python3-pip

javascript /jQuery - For Loop

Use a regular for loop and format the index to be used in the selector.

var array = [];
for (var i = 0; i < 4; i++) {
    var selector = '' + i;
    if (selector.length == 1)
        selector = '0' + selector;
    selector = '#event' + selector;
    array.push($(selector, response).html());
}

"The import org.springframework cannot be resolved."

This answer from here helped me:

You should take a look at the build path of your project to check whether the referenced libraries are still there. So right-click on your project, then "Properties -> Java Build Path -> Libraries" and check whether you still have the spring library JARs in the place that is mentioned there. If not, just re-add them to your classpath within this dialog.

http://forum.spring.io/forum/spring-projects/springsource-tool-suite/98653-springframework-cannot-be-resolved-error

Convert Date format into DD/MMM/YYYY format in SQL Server

Try using the below query.

SELECT REPLACE(CONVERT(VARCHAR(11),GETDATE(),6), ' ','/');  

Result: 20/Jun/13

SELECT REPLACE(CONVERT(VARCHAR(11),GETDATE(),106), ' ','/');  

Result: 20/Jun/2013

Bootstrap: adding gaps between divs

The easiest way to do it is to add mb-5 to your classes. That is <div class='row mb-5'>.

NOTE:

  • mb varies betweeen 1 to 5
  • The Div MUST have the row class

how to drop database in sqlite?

If you want to delete database programatically you can use deleteDatabase from Context class:

deleteDatabase(String name)
Delete an existing private SQLiteDatabase associated with this Context's application package.

2D character array initialization in C

I think what you originally meant to do was to make an array only of characters, not of pointers:

char options[2][100];

options[0][0]='t';
options[0][1]='e';
options[0][2]='s';
options[0][3]='t';
options[0][4]='1';
options[0][5]='\0';  /* NUL termination of C string */

/* A standard C library function which copies strings. */
strcpy(options[1], "test2");

The code above shows two distinct methods of setting the character values in memory you have set aside to contain characters.

How to validate an email address in PHP

/(?![[:alnum:]]|@|-|_|\.)./

Nowadays, if you use a HTML5 form with type=email then you're already by 80% safe since browser engines have their own validator. To complement it, add this regex to your preg_match_all() and negate it:

if (!preg_match_all("/(?![[:alnum:]]|@|-|_|\.)./",$email)) { .. }

Find the regex used by HTML5 forms for validation
https://regex101.com/r/mPEKmy/1

How do I set default terminal to terminator?

Copy-paste the following into your current terminal:

gsettings set org.gnome.desktop.default-applications.terminal exec /usr/bin/terminator
gsettings set org.gnome.desktop.default-applications.terminal exec-arg "-x"

This modifies the dconf to make terminator the default program. You could also use dconf-editor (a GUI-based tool) to make changes to the dconf, as another answer has suggested. If you would like to learn and understand more about this topic, this may help you.

How to write a Python module/package?

Make a file named "hello.py"

If you are using Python 2.x

def func():
    print "Hello"

If you are using Python 3.x

def func():
    print("Hello")

Run the file. Then, you can try the following:

>>> import hello
>>> hello.func()
Hello

If you want a little bit hard, you can use the following:

If you are using Python 2.x

def say(text):
    print text

If you are using Python 3.x

def say(text):
    print(text)

See the one on the parenthesis beside the define? That is important. It is the one that you can use within the define.

Text - You can use it when you want the program to say what you want. According to its name, it is text. I hope you know what text means. It means "words" or "sentences".

Run the file. Then, you can try the following if you are using Python 3.x:

>>> import hello
>>> hello.say("hi")
hi
>>> from hello import say
>>> say("test")
test

For Python 2.x - I guess same thing with Python 3? No idea. Correct me if I made a mistake on Python 2.x (I know Python 2 but I am used with Python 3)

@try - catch block in Objective-C

Now I've found the problem.

Removing the obj_exception_throw from my breakpoints solved this. Now it's caught by the @try block and also, NSSetUncaughtExceptionHandler will handle this if a @try block is missing.

Performance differences between ArrayList and LinkedList

Ignore this answer for now. The other answers, particularly that of aix, are mostly correct. Over the long term they're the way to bet. And if you have enough data (on one benchmark on one machine, it seemed to be about one million entries) ArrayList and LinkedList do currently work as advertized. However, there are some fine points that apply in the early 21st century.

Modern computer technology seems, by my testing, to give an enormous edge to arrays. Elements of an array can be shifted and copied at insane speeds. As a result arrays and ArrayList will, in most practical situations, outperform LinkedList on inserts and deletes, often dramatically. In other words, ArrayList will beat LinkedList at its own game.

The downside of ArrayList is it tends to hang onto memory space after deletions, where LinkedList gives up space as it gives up entries.

The bigger downside of arrays and ArrayList is they fragment free memory and overwork the garbage collector. As an ArrayList expands, it creates new, bigger arrays, copies the old array to the new one, and frees the old one. Memory fills with big contiguous chunks of free memory that are not big enough for the next allocation. Eventually there's no suitable space for that allocation. Even though 90% of memory is free, no individual piece is big enough to do the job. The GC will work frantically to move things around, but if it takes too long to rearrange the space, it will throw an OutOfMemoryException. If it doesn't give up, it can still slow your program way down.

The worst of it is this problem can be hard to predict. Your program will run fine one time. Then, with a bit less memory available, with no warning, it slows or stops.

LinkedList uses small, dainty bits of memory and GC's love it. It still runs fine when you're using 99% of your available memory.

So in general, use ArrayList for smaller sets of data that are not likely to have most of their contents deleted, or when you have tight control over creation and growth. (For instance, creating one ArrayList that uses 90% of memory and using it without filling it for the duration of the program is fine. Continually creating and freeing ArrayList instances that use 10% of memory will kill you.) Otherwise, go with LinkedList (or a Map of some sort if you need random access). If you have very large collections (say over 100,000 elements), no concerns about the GC, and plan lots of inserts and deletes and no random access, run a few benchmarks to see what's fastest.

ReactJS - .JS vs .JSX

As already mentioned, there is no difference, if you create a file with .jsx or .js.

I would like to bring another expect of creating the files as .jsx while creating a component.

This is not mandatory, but an architectural approach that we can follow. So, in large projects we divide our components as Presentational components or Container components. Just to brief, in container components we write the logic to get data for the component and render the Presentational component with props. In presentational components, we usually donot write functional logic, presentational components are used to represent the UI with required props.

So, if you check the definition on JSX in React documents.

It says,

const element = <h1>Hello, world!</h1>;

It is called JSX, and it is a syntax extension to JavaScript. 
We recommend using it with React to describe what the UI should look like. 
JSX may remind you of a template language, but it comes with the full power of JavaScript.

JSX produces React “elements”. Instead of artificially separating technologies by putting
markup and logic in separate files, React separates concerns with loosely coupled units 
called “components” that contain both. 

React doesn’t require using JSX, but most people find it helpful as a visual aid when 
working with UI inside the JavaScript code. It also allows React to show more useful 
error and warning messages.

It means, It's not mandatory but you can think of creating presentational components with '.jsx' as it actually binds the props with the UI. and container components, as .js files as those contains logic to get the data.

It's a convention that you can follow while creating the .jsx or .js files, to logically and physically separate the code.

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

How to set $_GET variable

For the form, use:

<form name="form1" action="<?=$_SERVER['PHP_SELF'];?>" method="get">

and for getting the value, use the get method as follows:

$value = $_GET['name_to_send_using_get'];

Show/hide 'div' using JavaScript

How to show or hide an element:

In order to show or hide an element, manipulate the element's style property. In most cases, you probably just want to change the element's display property:

element.style.display = 'none';           // Hide
element.style.display = 'block';          // Show
element.style.display = 'inline';         // Show
element.style.display = 'inline-block';   // Show

Alternatively, if you would still like the element to occupy space (like if you were to hide a table cell), you could change the element's visibility property instead:

element.style.visibility = 'hidden';      // Hide
element.style.visibility = 'visible';     // Show

Hiding a collection of elements:

If you want to hide a collection of elements, just iterate over each element and change the element's display to none:

function hide (elements) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = 'none';
  }
}
// Usage:
hide(document.querySelectorAll('.target'));
hide(document.querySelector('.target'));
hide(document.getElementById('target'));

_x000D_
_x000D_
hide(document.querySelectorAll('.target'));_x000D_
_x000D_
function hide (elements) {_x000D_
  elements = elements.length ? elements : [elements];_x000D_
  for (var index = 0; index < elements.length; index++) {_x000D_
    elements[index].style.display = 'none';_x000D_
  }_x000D_
}
_x000D_
<div class="target">This div will be hidden.</div>_x000D_
_x000D_
<span class="target">This span will be hidden as well.</span>
_x000D_
_x000D_
_x000D_

Showing a collection of elements:

Most of the time, you will probably just be toggling between display: none and display: block, which means that the following may be sufficient when showing a collection of elements.

You can optionally specify the desired display as the second argument if you don't want it to default to block.

function show (elements, specifiedDisplay) {
  elements = elements.length ? elements : [elements];
  for (var index = 0; index < elements.length; index++) {
    elements[index].style.display = specifiedDisplay || 'block';
  }
}
// Usage:
var elements = document.querySelectorAll('.target');
show(elements);

show(elements, 'inline-block'); // The second param allows you to specify a display value

_x000D_
_x000D_
var elements = document.querySelectorAll('.target');_x000D_
_x000D_
show(elements, 'inline-block'); // The second param allows you to specify a display value_x000D_
_x000D_
show(document.getElementById('hidden-input'));_x000D_
_x000D_
function show (elements, specifiedDisplay) {_x000D_
  elements = elements.length ? elements : [elements];_x000D_
  for (var index = 0; index < elements.length; index++) {_x000D_
    elements[index].style.display = specifiedDisplay || 'block';_x000D_
  }_x000D_
}
_x000D_
<div class="target" style="display: none">This hidden div should have a display of 'inline-block' when it is shown.</div>_x000D_
_x000D_
<span>Inline span..</span>_x000D_
_x000D_
<input id="hidden-input" />
_x000D_
_x000D_
_x000D_

Alternatively, a better approach for showing the element(s) would be to merely remove the inline display styling in order to revert it back to its initial state. Then check the computed display style of the element in order to determine whether it is being hidden by a cascaded rule. If so, then show the element.

function show (elements, specifiedDisplay) {
  var computedDisplay, element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    // Remove the element's inline display styling
    element.style.display = '';
    computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display');

    if (computedDisplay === 'none') {
        element.style.display = specifiedDisplay || 'block';
    }
  }
}

_x000D_
_x000D_
show(document.querySelectorAll('.target'));_x000D_
_x000D_
function show (elements, specifiedDisplay) {_x000D_
  var computedDisplay, element, index;_x000D_
_x000D_
  elements = elements.length ? elements : [elements];_x000D_
  for (index = 0; index < elements.length; index++) {_x000D_
    element = elements[index];_x000D_
_x000D_
    // Remove the element's inline display styling_x000D_
    element.style.display = '';_x000D_
    computedDisplay = window.getComputedStyle(element, null).getPropertyValue('display');_x000D_
_x000D_
    if (computedDisplay === 'none') {_x000D_
        element.style.display = specifiedDisplay || 'block';_x000D_
    }_x000D_
  }_x000D_
}
_x000D_
<span class="target" style="display: none">Should revert back to being inline.</span>_x000D_
_x000D_
<span class="target" style="display: none">Inline as well.</span>_x000D_
_x000D_
<div class="target" style="display: none">Should revert back to being block level.</div>_x000D_
_x000D_
<span class="target" style="display: none">Should revert back to being inline.</span>
_x000D_
_x000D_
_x000D_

(If you want to take it a step further, you could even mimic what jQuery does and determine the element's default browser styling by appending the element to a blank iframe (without a conflicting stylesheet) and then retrieve the computed styling. In doing so, you will know the true initial display property value of the element and you won't have to hardcode a value in order to get the desired results.)

Toggling the display:

Similarly, if you would like to toggle the display of an element or collection of elements, you could simply iterate over each element and determine whether it is visible by checking the computed value of the display property. If it's visible, set the display to none, otherwise remove the inline display styling, and if it's still hidden, set the display to the specified value or the hardcoded default, block.

function toggle (elements, specifiedDisplay) {
  var element, index;

  elements = elements.length ? elements : [elements];
  for (index = 0; index < elements.length; index++) {
    element = elements[index];

    if (isElementHidden(element)) {
      element.style.display = '';

      // If the element is still hidden after removing the inline display
      if (isElementHidden(element)) {
        element.style.display = specifiedDisplay || 'block';
      }
    } else {
      element.style.display = 'none';
    }
  }
  function isElementHidden (element) {
    return window.getComputedStyle(element, null).getPropertyValue('display') === 'none';
  }
}
// Usage:
document.getElementById('toggle-button').addEventListener('click', function () {
  toggle(document.querySelectorAll('.target'));
});

_x000D_
_x000D_
document.getElementById('toggle-button').addEventListener('click', function () {_x000D_
    toggle(document.querySelectorAll('.target'));_x000D_
});_x000D_
_x000D_
function toggle (elements, specifiedDisplay) {_x000D_
  var element, index;_x000D_
_x000D_
  elements = elements.length ? elements : [elements];_x000D_
  for (index = 0; index < elements.length; index++) {_x000D_
    element = elements[index];_x000D_
_x000D_
    if (isElementHidden(element)) {_x000D_
      element.style.display = '';_x000D_
_x000D_
      // If the element is still hidden after removing the inline display_x000D_
      if (isElementHidden(element)) {_x000D_
        element.style.display = specifiedDisplay || 'block';_x000D_
      }_x000D_
    } else {_x000D_
      element.style.display = 'none';_x000D_
    }_x000D_
  }_x000D_
  function isElementHidden (element) {_x000D_
    return window.getComputedStyle(element, null).getPropertyValue('display') === 'none';_x000D_
  }_x000D_
}
_x000D_
.target { display: none; }
_x000D_
<button id="toggle-button">Toggle display</button>_x000D_
_x000D_
<span class="target">Toggle the span.</span>_x000D_
_x000D_
<div class="target">Toggle the div.</div>
_x000D_
_x000D_
_x000D_

Update a local branch with the changes from a tracked remote branch

You don't use the : syntax - pull always modifies the currently checked-out branch. Thus:

git pull origin my_remote_branch

while you have my_local_branch checked out will do what you want.

Since you already have the tracking branch set, you don't even need to specify - you could just do...

git pull

while you have my_local_branch checked out, and it will update from the tracked branch.

error: passing xxx as 'this' argument of xxx discards qualifiers

Let's me give a more detail example. As to the below struct:

struct Count{
    uint32_t c;

    Count(uint32_t i=0):c(i){}

    uint32_t getCount(){
        return c;
    }

    uint32_t add(const Count& count){
        uint32_t total = c + count.getCount();
        return total;
    }
};

enter image description here

As you see the above, the IDE(CLion), will give tips Non-const function 'getCount' is called on the const object. In the method add count is declared as const object, but the method getCount is not const method, so count.getCount() may change the members in count.

Compile error as below(core message in my compiler):

error: passing 'const xy_stl::Count' as 'this' argument discards qualifiers [-fpermissive]

To solve the above problem, you can:

  1. change the method uint32_t getCount(){...} to uint32_t getCount() const {...}. So count.getCount() won't change the members in count.

or

  1. change uint32_t add(const Count& count){...} to uint32_t add(Count& count){...}. So count don't care about changing members in it.

As to you problem, objects in the std::set are stored as const StudentT, but the method getId and getName are not const, so you give the above error.

You can also see this question Meaning of 'const' last in a function declaration of a class? for more detail.

Numpy AttributeError: 'float' object has no attribute 'exp'

Probably there's something wrong with the input values for X and/or T. The function from the question works ok:

import numpy as np
from math import e

def sigmoid(X, T):
  return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))

X = np.array([[1, 2, 3], [5, 0, 0]])
T = np.array([[1, 2], [1, 1], [4, 4]])

print(X.dot(T))
# Just to see if values are ok
print([1. / (1. + e ** el) for el in [-5, -10, -15, -16]])
print()
print(sigmoid(X, T))

Result:

[[15 16]
 [ 5 10]]

[0.9933071490757153, 0.9999546021312976, 0.999999694097773, 0.9999998874648379]

[[ 0.99999969  0.99999989]
 [ 0.99330715  0.9999546 ]]

Probably it's the dtype of your input arrays. Changing X to:

X = np.array([[1, 2, 3], [5, 0, 0]], dtype=object)

Gives:

Traceback (most recent call last):
  File "/[...]/stackoverflow_sigmoid.py", line 24, in <module>
    print sigmoid(X, T)
  File "/[...]/stackoverflow_sigmoid.py", line 14, in sigmoid
    return 1.0 / (1.0 + np.exp(-1.0 * np.dot(X, T)))
AttributeError: exp

Create table (structure) from existing table

Copy structure only (copy all the columns)

Select Top 0 * into NewTable from OldTable

Copy structure only (copy some columns)

Select Top 0 Col1,Col2,Col3,Col4,Col5 into NewTable from OldTable

Copy structure with data

Select * into NewTable from OldTable

If you already have a table with same structure and you just want to copy data then use this

Insert into NewTable Select * from OldTable

How to filter Android logcat by application?

Add your application's package in "Filter Name" by clicking on "+" button on left top corner in logcat.

XMLHttpRequest cannot load an URL with jQuery

Fiddle with 3 working solutions in action.

Given an external JSON:

myurl = 'http://wikidata.org/w/api.php?action=wbgetentities&sites=frwiki&titles=France&languages=zh-hans|zh-hant|fr&props=sitelinks|labels|aliases|descriptions&format=json'

Solution 1: $.ajax() + jsonp:

$.ajax({
  dataType: "jsonp",
  url: myurl ,
  }).done(function ( data ) {
  // do my stuff
});

Solution 2: $.ajax()+json+&calback=?:

$.ajax({
  dataType: "json",
  url: myurl + '&callback=?',
  }).done(function ( data ) {
  // do my stuff
});

Solution 3: $.getJSON()+calback=?:

$.getJSON( myurl + '&callback=?', function(data) {
  // do my stuff
});

Documentations: http://api.jquery.com/jQuery.ajax/ , http://api.jquery.com/jQuery.getJSON/

Set content of HTML <span> with Javascript

This is standards compliant and cross-browser safe.

Example: http://jsfiddle.net/kv9pw/

var span = document.getElementById('someID');

while( span.firstChild ) {
    span.removeChild( span.firstChild );
}
span.appendChild( document.createTextNode("some new content") );

Easier way to create circle div than using an image?

There's also [the bad idea of] using several (20+) horizontal or vertical 1px divs to construct a circle. This jQuery plugin uses this method to construct different shapes.

Java String.split() Regex

String[] ops = str.split("\\s*[a-zA-Z]+\\s*");
String[] notops = str.split("\\s*[^a-zA-Z]+\\s*");
String[] res = new String[ops.length+notops.length-1];
for(int i=0; i<res.length; i++) res[i] = i%2==0 ? notops[i/2] : ops[i/2+1];

This should do it. Everything nicely stored in res.

Deleting a local branch with Git

This worked for me...
I have removed the folders there in .git/worktrees folder and then tried "git delete -D branch-name".

LISTAGG function: "result of string concatenation is too long"

Short of using 12c overflow using the CLOB and substr will also work

rtrim(dbms_lob.substr(XMLAGG(XMLELEMENT(E,column_name,',').EXTRACT('//text()') ORDER BY column_name).GetClobVal(),1000,1),',')

Delete column from pandas DataFrame

The actual question posed, missed by most answers here is:

Why can't I use del df.column_name?

At first we need to understand the problem, which requires us to dive into python magic methods.

As Wes points out in his answer del df['column'] maps to the python magic method df.__delitem__('column') which is implemented in pandas to drop the column

However, as pointed out in the link above about python magic methods:

In fact, __del__ should almost never be used because of the precarious circumstances under which it is called; use it with caution!

You could argue that del df['column_name'] should not be used or encouraged, and thereby del df.column_name should not even be considered.

However, in theory, del df.column_name could be implemeted to work in pandas using the magic method __delattr__. This does however introduce certain problems, problems which the del df['column_name'] implementation already has, but in lesser degree.

Example Problem

What if I define a column in a dataframe called "dtypes" or "columns".

Then assume I want to delete these columns.

del df.dtypes would make the __delattr__ method confused as if it should delete the "dtypes" attribute or the "dtypes" column.

Architectural questions behind this problem

  1. Is a dataframe a collection of columns?
  2. Is a dataframe a collection of rows?
  3. Is a column an attribute of a dataframe?

Pandas answers:

  1. Yes, in all ways
  2. No, but if you want it to be, you can use the .ix, .loc or .iloc methods.
  3. Maybe, do you want to read data? Then yes, unless the name of the attribute is already taken by another attribute belonging to the dataframe. Do you want to modify data? Then no.

TLDR;

You cannot do del df.column_name because pandas has a quite wildly grown architecture that needs to be reconsidered in order for this kind of cognitive dissonance not to occur to its users.

Protip:

Don't use df.column_name, It may be pretty, but it causes cognitive dissonance

Zen of Python quotes that fits in here:

There are multiple ways of deleting a column.

There should be one-- and preferably only one --obvious way to do it.

Columns are sometimes attributes but sometimes not.

Special cases aren't special enough to break the rules.

Does del df.dtypes delete the dtypes attribute or the dtypes column?

In the face of ambiguity, refuse the temptation to guess.

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

I had the same problem and I could solve it by adding the entity into persistence.xml. The problem was caused due to the fact that the entity was not added to the persistence config. Edit your persistence file:

<persistence-unit name="MY_PU" transaction-type="RESOURCE_LOCAL">
<provider>`enter code here`
     org.hibernate.jpa.HibernatePersistenceProvider
  </provider>
<class>mypackage.MyEntity</class>

...

Creating a singleton in Python

Here's my own implementation of singletons. All you have to do is decorate the class; to get the singleton, you then have to use the Instance method. Here's an example:

   @Singleton
   class Foo:
       def __init__(self):
           print 'Foo created'

   f = Foo() # Error, this isn't how you get the instance of a singleton

   f = Foo.Instance() # Good. Being explicit is in line with the Python Zen
   g = Foo.Instance() # Returns already created instance

   print f is g # True

And here's the code:

class Singleton:
    """
    A non-thread-safe helper class to ease implementing singletons.
    This should be used as a decorator -- not a metaclass -- to the
    class that should be a singleton.

    The decorated class can define one `__init__` function that
    takes only the `self` argument. Other than that, there are
    no restrictions that apply to the decorated class.

    To get the singleton instance, use the `Instance` method. Trying
    to use `__call__` will result in a `TypeError` being raised.

    Limitations: The decorated class cannot be inherited from.

    """

    def __init__(self, decorated):
        self._decorated = decorated

    def Instance(self):
        """
        Returns the singleton instance. Upon its first call, it creates a
        new instance of the decorated class and calls its `__init__` method.
        On all subsequent calls, the already created instance is returned.

        """
        try:
            return self._instance
        except AttributeError:
            self._instance = self._decorated()
            return self._instance

    def __call__(self):
        raise TypeError('Singletons must be accessed through `Instance()`.')

    def __instancecheck__(self, inst):
        return isinstance(inst, self._decorated)

Can I add a UNIQUE constraint to a PostgreSQL table, after it's already created?

If you had a table that already had a existing constraints based on lets say: name and lastname and you wanted to add one more unique constraint, you had to drop the entire constrain by:

ALTER TABLE your_table DROP CONSTRAINT constraint_name;

Make sure tha the new constraint you wanted to add is unique/ not null ( if its Microsoft Sql, it can contain only one null value) across all data on that table, and then you could re-create it.

ALTER TABLE table_name
ADD CONSTRAINT constraint_name UNIQUE (column1, column2, ... column_n);

Using awk to print all columns from the nth to the last

This was irritating me so much, I sat down and wrote a cut-like field specification parser, tested with GNU Awk 3.1.7.

First, create a new Awk library script called pfcut, with e.g.

sudo nano /usr/share/awk/pfcut

Then, paste in the script below, and save. After that, this is how the usage looks like:

$ echo "t1 t2 t3 t4 t5 t6 t7" | awk -f pfcut --source '/^/ { pfcut("-4"); }'
t1 t2 t3 t4

$ echo "t1 t2 t3 t4 t5 t6 t7" | awk -f pfcut --source '/^/ { pfcut("2-"); }'
t2 t3 t4 t5 t6 t7

$ echo "t1 t2 t3 t4 t5 t6 t7" | awk -f pfcut --source '/^/ { pfcut("-2,4,6-"); }'
t1 t2 t4 t6 t7

To avoid typing all that, I guess the best one can do (see otherwise Automatically load a user function at startup with awk? - Unix & Linux Stack Exchange) is add an alias to ~/.bashrc; e.g. with:

$ echo "alias awk-pfcut='awk -f pfcut --source'" >> ~/.bashrc
$ source ~/.bashrc     # refresh bash aliases

... then you can just call:

$ echo "t1 t2 t3 t4 t5 t6 t7" | awk-pfcut '/^/ { pfcut("-2,4,6-"); }'
t1 t2 t4 t6 t7

Here is the source of the pfcut script:

# pfcut - print fields like cut
#
# sdaau, GNU GPL
# Nov, 2013

function spfcut(formatstring)
{
  # parse format string
  numsplitscomma = split(formatstring, fsa, ",");
  numspecparts = 0;
  split("", parts); # clear/initialize array (for e.g. `tail` piping into `awk`)
  for(i=1;i<=numsplitscomma;i++) {
    commapart=fsa[i];
    numsplitsminus = split(fsa[i], cpa, "-");
    # assume here a range is always just two parts: "a-b"
    # also assume user has already sorted the ranges
    #print numsplitsminus, cpa[1], cpa[2]; # debug
    if(numsplitsminus==2) {
     if ((cpa[1]) == "") cpa[1] = 1;
     if ((cpa[2]) == "") cpa[2] = NF;
     for(j=cpa[1];j<=cpa[2];j++) {
       parts[numspecparts++] = j;
     }
    } else parts[numspecparts++] = commapart;
  }
  n=asort(parts); outs="";
  for(i=1;i<=n;i++) {
    outs = outs sprintf("%s%s", $parts[i], (i==n)?"":OFS); 
    #print(i, parts[i]); # debug
  }
  return outs;
}

function pfcut(formatstring) {
  print spfcut(formatstring);
}

How to copy multiple files in one layer using a Dockerfile?

COPY <all> <the> <things> <last-arg-is-destination>

But here is an important excerpt from the docs:

If you have multiple Dockerfile steps that use different files from your context, COPY them individually, rather than all at once. This ensures that each step’s build cache is only invalidated (forcing the step to be re-run) if the specifically required files change.

https://docs.docker.com/develop/develop-images/dockerfile_best-practices/#add-or-copy

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

Please take a look at my project on Sourceforge which has user types for standard SQL Date and Time types as well as JSR 310 and Joda Time. All of the types try to address the offsetting issue. See http://sourceforge.net/projects/usertype/

EDIT: In response to Derek Mahar's question attached to this comment:

"Chris, do your user types work with Hibernate 3 or greater? – Derek Mahar Nov 7 '10 at 12:30"

Yes these types support Hibernate 3.x versions including Hibernate 3.6.

Create boolean column in MySQL with false as default value?

If you are making the boolean column as not null then the default 'default' value is false; you don't have to explicitly specify it.

error: request for member '..' in '..' which is of non-class type

I ran into a case where I got that error message and had

Foo foo(Bar());

and was basically trying to pass in a temporary Bar object to the Foo constructor. Turns out the compiler was translating this to

Foo foo(Bar(*)());

that is, a function declaration whose name is foo that returns a Foo that takes in an argument -- a function pointer returning a Bar with 0 arguments. When passing in temporaries like this, better to use Bar{} instead of Bar() to eliminate ambiguity.

Django request get parameters

You may also use:

request.POST.get('section','') # => [39]
request.POST.get('MAINS','') # => [137] 
request.GET.get('section','') # => [39]
request.GET.get('MAINS','') # => [137]

Using this ensures that you don't get an error. If the POST/GET data with any key is not defined then instead of raising an exception the fallback value (second argument of .get() will be used).

Get current time in milliseconds in Python?

If you want a simple method in your code that returns the milliseconds with datetime:

from datetime import datetime
from datetime import timedelta

start_time = datetime.now()

# returns the elapsed milliseconds since the start of the program
def millis():
   dt = datetime.now() - start_time
   ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
   return ms

How to $watch multiple variable change in angular

Angular 1.3 provides $watchGroup specifically for this purpose:

https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$watchGroup

This seems to provide the same ultimate result as a standard $watch on an array of expressions. I like it because it makes the intention clearer in the code.

Aborting a shell script if any command returns a non-zero value

The if statements in your example are unnecessary. Just do it like this:

dosomething1 || exit 1

If you take Ville Laurikari's advice and use set -e then for some commands you may need to use this:

dosomething || true

The || true will make the command pipeline have a true return value even if the command fails so the the -e option will not kill the script.

Fragment Inside Fragment

enter image description here

I needed some more context, so I made an example to show how this is done. The most helpful thing I read while preparing was this:

Activity

activity_main.xml

Add a FrameLayout to your activity to hold the parent fragment.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Activity"/>

    <FrameLayout
        android:id="@+id/parent_fragment_container"
        android:layout_width="match_parent"
        android:layout_height="200dp"/>

 </LinearLayout>

MainActivity.java

Load the parent fragment and implement the fragment listeners. (See fragment communication.)

import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements ParentFragment.OnFragmentInteractionListener, ChildFragment.OnFragmentInteractionListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Begin the transaction
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.parent_fragment_container, new ParentFragment());
        ft.commit();
    }

    @Override
    public void messageFromParentFragment(Uri uri) {
        Log.i("TAG", "received communication from parent fragment");
    }

    @Override
    public void messageFromChildFragment(Uri uri) {
        Log.i("TAG", "received communication from child fragment");
    }
}

Parent Fragment

fragment_parent.xml

Add another FrameLayout container for the child fragment.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:layout_margin="20dp"
              android:background="#91d0c2">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Parent fragment"/>

    <FrameLayout
        android:id="@+id/child_fragment_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>

</LinearLayout>

ParentFragment.java

Use getChildFragmentManager in onViewCreated to set up the child fragment.

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;    

public class ParentFragment extends Fragment {

    private OnFragmentInteractionListener mListener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_parent, container, false);
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        Fragment childFragment = new ChildFragment();
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        transaction.replace(R.id.child_fragment_container, childFragment).commit();
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void messageFromParentFragment(Uri uri);
    }
}

Child Fragment

fragment_child.xml

There is nothing special here.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:layout_margin="20dp"
              android:background="#f1ff91">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Child fragment"/>
</LinearLayout>

ChildFragment.java

There is nothing too special here, either.

import android.support.v4.app.Fragment;

public class ChildFragment extends Fragment {

    private OnFragmentInteractionListener mListener;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_child, container, false);
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }


    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void messageFromChildFragment(Uri uri);
    }
}

Notes

  • The support library is being used so that nested fragments can be used before Android 4.2.

How to get and set the current web page scroll position?

I went with the HTML5 local storage solution... All my links call a function which sets this before changing window.location:

localStorage.topper = document.body.scrollTop;

and each page has this in the body's onLoad:

  if(localStorage.topper > 0){ 
    window.scrollTo(0,localStorage.topper);
  }

Hide Text with CSS, Best Practice?

Can't you use simply display: none; like this

HTML

<div id="web-title">
   <a href="http://website.com" title="Website" rel="home">
       <span class="webname">Website Name</span>
   </a>
</div>

CSS

.webname {
   display: none;
}

Or how about playing with visibility if you are concerned to reserve the space

.webname {
   visibility: hidden;
}

Select data between a date/time range

MySQL date format is this : Y-M-D. You are using Y/M/D. That's is wrong. modify your query.

If you insert the date like Y/M/D, It will be insert null value in the database.

If you are using PHP and date you are getting from the form is like this Y/M/D, you can replace this with using the statement .

out_date=date('Y-m-d', strtotime(str_replace('/', '-', $data["input_date"])))

Allow User to input HTML in ASP.NET MVC - ValidateInput or AllowHtml

I have faced this problem during development of a E-Commerce site using NopCommerce, I got this solution by 3 different ways as like the previous answers. But according to the NopCommerce structure I didn't found those three at a time. I have just seen that there they are using just [AllowHtml] and it's working fine except any problem. As previously asked question

Personally I don't prefer [ValidateInput(false)] because i's skipping total model entity checking, which is insecure. But if anyone just write have a look here

[AllowHtml] 
public string BlogText {get;set;}

then it just skip only single property, and just allow only particular property and check hardly all other entities. Therefore it seems preferable towards mine.

PHP mail not working for some reason

This might be the issue of your SMTP config in your php.ini file.

Since you new to PHP, You can find php.ini file in your root directory of PHP installation folder and check for SMTP = and smtp_port= and change the value to

SMTP = your mail server e.g) mail.yourdomain.com
smtp_port = 25(check your admin for original port)

In case your server require authentication for sending mail, use PEAR mail function.

Run a shell script with an html button

As stated by Luke you need to use a server side language, like php. This is a really simple php example:

<?php
if ($_GET['run']) {
  # This code will run if ?run=true is set.
  exec("/path/to/name.sh");
}
?>

<!-- This link will add ?run=true to your URL, myfilename.php?run=true -->
<a href="?run=true">Click Me!</a>

Save this as myfilename.php and place it on a machine with a web server with php installed. The same thing can be accomplished with asp, java, ruby, python, ...

Abort Ajax requests using jQuery

Just call xhr.abort() whether it's jquery ajax object or native XMLHTTPRequest object.

example:

//jQuery ajax
$(document).ready(function(){
    var xhr = $.get('/server');
    setTimeout(function(){xhr.abort();}, 2000);
});

//native XMLHTTPRequest
var xhr = new XMLHttpRequest();
xhr.open('GET','/server',true);
xhr.send();
setTimeout(function(){xhr.abort();}, 2000);

Are there such things as variables within an Excel formula?

You could define a name for the VLOOKUP part of the formula.

  1. Highlight the cell that contains this formula
  2. On the Insert menu, go Name, and click Define
  3. Enter a name for your variable (e.g. 'Value')
  4. In the Refers To box, enter your VLOOKUP formula: =VLOOKUP(A1,B:B, 1, 0)
  5. Click Add, and close the dialog
  6. In your original formula, replace the VLOOKUP parts with the name you just defined: =IF( Value > 10, Value - 10, Value )

Step (1) is important here: I guess on the second row, you want Excel to use VLOOKUP(A2,B:B, 1, 0), the third row VLOOKUP(A3,B:B, 1, 0), etc. Step (4) achieves this by using relative references (A1 and B:B), not absolute references ($A$1 and $B:$B).

Note:

  1. For newer Excel versions with the ribbon, go to Formulas ribbon -> Define Name. It's the same after that. Also, to use your name, you can do "Use in Formula", right under Define Name, while editing the formula, or else start typing it, and Excel will suggest the name (credits: Michael Rusch)

  2. Shortened steps: 1. Right click a cell and click Define name... 2. Enter a name and the formula which you want to associate with that name/local variable 3. Use variable (credits: Jens Bodal)