Programs & Examples On #Percentage

Percentage is a ratio or fraction of a quantity that shows the ratio from whole part of quantity. Percentage demonstrate how much part is there out of 100.

How to make rounded percentages add up to 100%

check if this is valid or not as far as my test cases I am able to get this working.

let's say number is k;

  1. sort percentage by descending oder.
  2. iterate over each percentage from descending order.
  3. calculate percentage of k for first percentage take Math.Ceil of output.
  4. next k = k-1
  5. iterate over till all percentage is consumed.

How do I print the percent sign(%) in c

there's no explanation in this topic why to print a percentage sign one must type %% and not for example escape character with percentage - \%.

from comp.lang.c FAQ list · Question 12.6 :

The reason it's tricky to print % signs with printf is that % is essentially printf's escape character. Whenever printf sees a %, it expects it to be followed by a character telling it what to do next. The two-character sequence %% is defined to print a single %.

To understand why \% can't work, remember that the backslash \ is the compiler's escape character, and controls how the compiler interprets source code characters at compile time. In this case, however, we want to control how printf interprets its format string at run-time. As far as the compiler is concerned, the escape sequence \% is undefined, and probably results in a single % character. It would be unlikely for both the \ and the % to make it through to printf, even if printf were prepared to treat the \ specially.

so the reason why one must type printf("%%"); to print single % is that's what is defined in printf function. % is an escape character of printf's, and \ of compiler.

Format number as percent in MS SQL Server

SELECT cast( cast(round(37.0/38.0,2) AS DECIMAL(18,2)) as varchar(100)) + ' %'

RESULT:  0.97 %

Calculate percentage Javascript

_x000D_
_x000D_
<div id="contentse "><br>
      <h2>Percentage Calculator</h2>
    <form action="/charactercount" class="align-items-center" style="border: 1px solid #eee;padding:15px;" method="post" enctype="multipart/form-data" name="form">
        <input type="hidden" name="csrfmiddlewaretoken" value="NCBdw9beXfKV07Tc1epTBPqJ0gzfkmHNXKrAauE34n3jn4TGeL8Vv6miOShhqv6O">
        <div style="border: 0px solid white;color:#eee;padding:5px;width:900px">
        <br><div class="input-float" style="float: left;"> what is <input type="text" id="aa" required=""> % of <input type="text" id="ab"> ? </div><div class="output-float"><input type="button" class="crm-submit" value="calculate" onclick="calculatea()"> &nbsp; <input type="text" id="ac" readonly="">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</div><br style="clear: both;"> </div><br>
        <hr><br>
        
        <div style="border: 0px solid white;color:#eee;padding:5px;width:900px">
        <div class="input-float" style="float: left;"><input type="text" id="ba"> is what percent of <input type="text" id="bb"> ? </div><div class="output-float"><input type="button" class="crm-submit" value="calculate" onclick="calculateb()"> &nbsp; <input type="text" id="bc" readonly=""> &nbsp; % </div><br style="clear: both;"></div><br>
        <hr><br>
        
        <div style="border: 0px solid white;color:#eee;padding:5px;width:900px">
        Find percentage change(increase/decrease) <br><br>
        <div class="input-float" style="float: left;">from <input type="text" id="ca"> to <input type="text" id="cb">&nbsp;?  </div><div class="output-float"><input type="button" class="crm-submit" value="calculate" onclick="calculatec()"> &nbsp; <input type="text" id="cc" readonly="">&nbsp;%</div><br style="clear: both;"></div>
    </form>
    </div>
_x000D_
_x000D_
_x000D_

Live example here: setool-percentage-calculator

Div Height in Percentage

There is the semicolon missing (;) after the "50%"

but you should also notice that the percentage of your div is connected to the div that contains it.

for instance:

<div id="wrapper">
  <div class="container">
   adsf
  </div>
</div>

#wrapper {
  height:100px;
}
.container
{
  width:80%;
  height:50%;
  background-color:#eee;
}

here the height of your .container will be 50px. it will be 50% of the 100px from the wrapper div.

if you have:

adsf

#wrapper {
  height:400px;
}
.container
{
  width:80%;
  height:50%;
  background-color:#eee;
}

then you .container will be 200px. 50% of the wrapper.

So you may want to look at the divs "wrapping" your ".container"...

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

How do I calculate the percentage of a number?

$percentage = 50;
$totalWidth = 350;

$new_width = ($percentage / 100) * $totalWidth;

how to calculate percentage in python

def percentage_match(mainvalue,comparevalue):
    if mainvalue >= comparevalue:
        matched_less = mainvalue - comparevalue
        no_percentage_matched = 100 - matched_less*100.0/mainvalue
        no_percentage_matched = str(no_percentage_matched) + ' %'
        return no_percentage_matched 
    else:
        print('please checkout your value')

print percentage_match(100,10)
Ans = 10.0 %

click or change event on radio using jquery

_x000D_
_x000D_
$( 'input[name="testGroup"]:radio' ).on('change', function(e) {_x000D_
     console.log(e.type);_x000D_
     return false;_x000D_
});
_x000D_
_x000D_
_x000D_

This syntax is a little more flexible to handle events. Not only can you observe "changes", but also other types of events can be controlled here too by using one single event handler. You can do this by passing the list of events as arguments to the first parameter. See jQuery On

Secondly, .change() is a shortcut for .on( "change", handler ). See here. I prefer using .on() rather than .change because I have more control over the events.

Lastly, I'm simply showing an alternative syntax to attach the event to the element.

How to edit hosts file via CMD?

echo 0.0.0.0 websitename.com >> %WINDIR%\System32\Drivers\Etc\Hosts

the >> appends the output of echo to the file.

Note that there are two reasons this might not work like you want it to. You may be aware of these, but I mention them just in case.

First, it won't affect a web browser, for example, that already has the current, "real" IP address resolved. So, it won't always take effect right away.

Second, it requires you to add an entry for every host name on a domain; just adding websitename.com will not block www.websitename.com, for example.

Create pandas Dataframe by appending one row at a time

before going to add a row, we have to convert the dataframe to dictionary there you can see the keys as columns in dataframe and values of the columns are again stored in the dictionary but there key for every column is the index number in dataframe. That idea make me to write the below code.

df2=df.to_dict()
values=["s_101","hyderabad",10,20,16,13,15,12,12,13,25,26,25,27,"good","bad"] #this is total row that we are going to add
i=0
for x in df.columns:   #here df.columns gives us the main dictionary key
    df2[x][101]=values[i]   #here the 101 is our index number it is also key of sub dictionary
    i+=1

Can not get a simple bootstrap modal to work

Also have a look at BootBox, it's really simple to show alerts and confirm boxes in a bootstrap modal. http://bootboxjs.com/

The implementation is as easy as this:

Normal alert:

bootbox.alert("Hello world!");

Confirm:

bootbox.confirm("Are you sure?", function(result) {
  Example.show("Confirm result: "+result);
}); 

Promt:

bootbox.prompt("What is your name?", function(result) {                
      if (result === null) {                                             
        Example.show("Prompt dismissed");                              
      } else {
        Example.show("Hi <b>"+result+"</b>");                          
      }
});

And even custom:

    bootbox.dialog("I am a custom dialog", [{
    "label" : "Success!",
    "class" : "btn-success",
    "callback": function() {
        Example.show("great success");
    }
}, {
    "label" : "Danger!",
    "class" : "btn-danger",
    "callback": function() {
        Example.show("uh oh, look out!");
    }
}, {
    "label" : "Click ME!",
    "class" : "btn-primary",
    "callback": function() {
        Example.show("Primary button");
    }
}, {
    "label" : "Just a button..."
}]);

What is a Java String's default initial value?

Any object if it is initailised , its defeault value is null, until unless we explicitly provide a default value.

How do I select child elements of any depth using XPath?

If you are using the XmlDocument and XmlNode.

Say:

XmlNode f = root.SelectSingleNode("//form[@id='myform']");

Use:

XmlNode s = f.SelectSingleNode(".//input[@type='submit']");

It depends on the tool that you use. But .// will select any child, any depth from a reference node.

Predicate Delegates in C#

A predicate is a function that returns true or false. A predicate delegate is a reference to a predicate.

So basically a predicate delegate is a reference to a function that returns true or false. Predicates are very useful for filtering a list of values - here is an example.

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list = new List<int> { 1, 2, 3 };

        Predicate<int> predicate = new Predicate<int>(greaterThanTwo);

        List<int> newList = list.FindAll(predicate);
    }

    static bool greaterThanTwo(int arg)
    {
        return arg > 2;
    }
}

Now if you are using C# 3 you can use a lambda to represent the predicate in a cleaner fashion:

using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        List<int> list = new List<int> { 1, 2, 3 };

        List<int> newList = list.FindAll(i => i > 2);
    }
}

How to jquery alert confirm box "yes" & "no"

See following snippet :

_x000D_
_x000D_
$(document).on("click", "a.deleteText", function() {_x000D_
    if (confirm('Are you sure ?')) {_x000D_
        $(this).prev('span.text').remove();_x000D_
    }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div class="container">_x000D_
    <span class="text">some text</span>_x000D_
    <a href="#" class="deleteText"><span class="delete-icon"> x Delete </span></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to set environment variables in Jenkins?

EnvInject Plugin aka (Environment Injector Plugin) gives you several options to set environment variables from Jenkins configuration.

By selecting Inject environment variables to the build process you will get:

  • Properties File Path
  • Properties Content
  • Script File Path

  • Script Content

  • and finally Evaluated Groovy script.


Evaluated Groovy script gives you possibility to set environment variable based on result of executed command:

  • with execute method:
    return [HOSTNAME_SHELL: 'hostname'.execute().text, 
        DATE_SHELL: 'date'.execute().text,
        ECHO_SHELL: 'echo hello world!'.execute().text
    ]
  • or with explicit Groovy code:
    return [HOSTNAME_GROOVY: java.net.InetAddress.getLocalHost().getHostName(),
        DATE_GROOVY: new Date()
    ] 

(More details about each method could be found in build-in help (?))


Unfortunately you can't do the same from Script Content as it states:

Execute a script file aimed at setting an environment such as creating folders, copying files, and so on. Give the script file content. You can use the above properties variables. However, adding or overriding environment variables in the script doesn't have any impacts in the build job.

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

Hopefully, this will help...

interface Param {
    title: string;
    callback: (error: Error, data: string) => void;
}

Or in a Function


let myfunction = (title: string, callback: (error: Error, data: string) => void): string => {

    callback(new Error(`Error Message Here.`), "This is callback data.");
    return title;

}

How can I provide multiple conditions for data trigger in WPF?

THIS ANSWER IS FOR ANIMATIONS ONLY


If you wanna implement the AND logic, you should use MultiTrigger, here is an example:

Suppose we want to do some actions if the property Text="" (empty string) AND IsKeyboardFocused="False", then your code should look like the following:

<MultiTrigger>
    <MultiTrigger.Conditions>
        <Condition Property="Text" Value="" />
        <Condition Property="IsKeyboardFocused" Value="False" />
    </MultiTrigger.Conditions>
        <MultiTrigger.EnterActions>
            <!-- Your actions here -->
        </MultiTrigger.EnterActions>
</MultiTrigger>

If you wanna implement the OR logic, there are couple of ways, and it depends on what you try to do:

The first option is to use multiple Triggers.
So, suppose you wanna do something if either Text="" OR IsKeyboardFocused="False",
then your code should look something like this:

<Trigger Property="IsEnabled" Value="false">
    <Setter Property="Opacity" TargetName="border" Value="0.56"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
    <Setter Property="BorderBrush" TargetName="border" 
            Value="{StaticResource TextBox.MouseOver.Border}"/>
</Trigger>


But the problem in this is what will I do if i wanna do something if either Text ISN'T null OR IsKeyboard="True"? This can be achieved by the second approach:
Recall De Morgan's rule, that says !(!x && !y) = x || y.
So we'll use it to solve the previous problem, by writing a multi trigger that it's triggered when Text="" and IsKeyboard="True", and we'll do our actions in EXIT ACTIONS, like this:

<MultiTrigger>
    <MultiTrigger.Conditions>
        <Condition Property="Text" Value="" />
        <Condition Property="IsKeyboardFocused" Value="False" />
    </MultiTrigger.Conditions>
    <MultiTrigger.ExitActions>
        <!-- Do something here -->
    </MultiTrigger.ExitActions>
</MultiTrigger>

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Well presumably it's not using the same version of Java when running it externally. Look through the startup scripts carefully to find where it picks up the version of Java to run. You should also check the startup logs to see whether they indicate which version is running.

Alternatively, unless you need the Java 7 features, you could always change your compiler preferences in Eclipse to target 1.6 instead.

make *** no targets specified and no makefile found. stop

Unpack the source from a working directory and cd into the file directory as root. Use the commands ./configure then make and make install

Shift column in pandas dataframe up by one?

df.gdp = df.gdp.shift(-1) ## shift up
df.gdp.drop(df.gdp.shape[0] - 1,inplace = True) ## removing the last row

Reading a json file in Android

Put that file in assets.

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

Read that file as:

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

            int size = is.available();

            byte[] buffer = new byte[size];

            is.read(buffer);

            is.close();

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


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

    }

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

JSONObject obj = new JSONObject(json_return_by_the_function);

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

Hope you will get what you want.

Make column fixed position in bootstrap

in Bootstrap 3 class="affix" works, but in Bootstrap 4 it does not. I solved this problem in Bootstrap 4 with class="sticky-top" (using position: fixed in CSS has its own problems)

code will be something like this:

<div class="row">
    <div class="col-lg-3">
        <div class="sticky-top">
            Fixed content
        </div>
    </div>
    <div class="col-lg-9">
        Normal scrollable content
    </div>
</div>

Split comma-separated input box values into array in jquery, and loop through it

use js split() method to create an array

var keywords = $('#searchKeywords').val().split(",");

then loop through the array using jQuery.each() function. as the documentation says:

In the case of an array, the callback is passed an array index and a corresponding array value each time

$.each(keywords, function(i, keyword){
   console.log(keyword);
});

Remove an array element and shift the remaining ones

You can't achieve what you want with arrays. Use vectors instead, and read about the std::remove algorithm. Something like:

std::remove(array, array+5, 3)

will work on your array, but it will not shorten it (why -- because it's impossible). With vectors, it'd be something like

v.erase(std::remove(v.begin(), v.end(), 3), v.end())

127 Return code from $?

This error is also at times deceiving. It says file is not found even though the files is indeed present. It could be because of invalid unreadable special characters present in the files that could be caused by the editor you are using. This link might help you in such cases.

-bash: ./my_script: /bin/bash^M: bad interpreter: No such file or directory

The best way to find out if it is this issue is to simple place an echo statement in the entire file and verify if the same error is thrown.

jQuery - on change input text

This worked for me

var change_temp = "";
$('#url_key').bind('keydown keyup',function(e){
    if(e.type == "keydown"){
        change_temp = $(this).val();
        return;
    }
    if($(this).val() != change_temp){
        // add the code to on change here 
    }

});

Which is the correct C# infinite loop, for (;;) or while (true)?

The original K&R book for C, from which C# can trace its ancestry, recommended

for (;;) ...

for infinite loops. It's unambiguous, easy to read, and has a long and noble history behind it.

Addendum (Feb 2017)

Of course, if you think that this looping form (or any other form) is too cryptic, you can always just add a comment.

// Infinite loop
for (;;)
    ...

Or:

for (;;)    // Loop forever
    ...

plot different color for different categorical levels using matplotlib

You can convert the categorical column into a numerical one by using the commands:

#we converting it into categorical data
cat_col = df['column_name'].astype('categorical') 

#we are getting codes for it 
cat_col = cat_col.cat.codes 

# we are using c parameter to change the color.
plt.scatter(df['column1'],df['column2'], c=cat_col) 

add a string prefix to each value in a string column using Pandas

You can use pandas.Series.map :

df['col'].map('str{}'.format)

It will apply the word "str" before all your values.

Bootstrap row class contains margin-left and margin-right which creates problems

I was facing this same issue and initially, I removed the row's right and left -ve margin and it removed the horizontal scroll, but it wasn't good. Then after 45 minutes of inspecting and searching, I found out that I was using container-fluid and was removing the padding and its inner row had left and right negative margins. So I gave container-fluid it's padding back and everything went back to normal.

If you do need to remove container-fluid padding, don't just remove every row's left and right negative margin in your project instead introduce a class and use that on your desired container

How to "comment-out" (add comment) in a batch/cmd?

Multi line comments

If there are large number of lines you want to comment out then it will be better if you can make multi line comments rather than commenting out every line.

See this post by Rob van der Woude on comment blocks:

The batch language doesn't have comment blocks, though there are ways to accomplish the effect.

GOTO EndComment1
This line is comment.
And so is this line.
And this one...
:EndComment1

You can use GOTO Label and :Label for making block comments.

Or, If the comment block appears at the end of the batch file, you can write EXIT at end of code and then any number of comments for your understanding.

@ECHO OFF
REM Do something
  •
  •
REM End of code; use GOTO:EOF instead of EXIT for Windows NT and later
EXIT

Start of comment block at end of batch file
This line is comment.
And so is this line.
And this one...

ant warning: "'includeantruntime' was not set"

If you like me work from commandline the quick answer is executing

export ANT_OPTS=-Dbuild.sysclasspath=ignore

And then run your ant script again.

JAVA_HOME should point to a JDK not a JRE

In IntelliJ IDEA go to File>Project Structure>SDK>JDK home path. Copy it and then go to My Computer>Advanced Settings>Environment Variables Change the JAVA_HOME path to what you have copied. Then open new cmd, and try mvn -v

It worked for me !!!

Creating a copy of a database in PostgreSQL

Postgres allows the use of any existing database on the server as a template when creating a new database. I'm not sure whether pgAdmin gives you the option on the create database dialog but you should be able to execute the following in a query window if it doesn't:

CREATE DATABASE newdb WITH TEMPLATE originaldb OWNER dbuser;

Still, you may get:

ERROR:  source database "originaldb" is being accessed by other users

To disconnect all other users from the database, you can use this query:

SELECT pg_terminate_backend(pg_stat_activity.pid) FROM pg_stat_activity 
WHERE pg_stat_activity.datname = 'originaldb' AND pid <> pg_backend_pid();

How to get Month Name from Calendar?

It returns English name of the month. 04 returns APRIL and so on.

String englishMonth (int month){
        return Month.of(month);
    }

Java: How to check if object is null?

It's probably slightly more efficient to catch a NullPointerException. The above methods mean that the runtime is checking for null pointers twice.

Purge or recreate a Ruby on Rails database

I think the best way to run this command:

**rake db:reset** it does db:drop, db:setup
 rake db:setup does db:create, db:schema:load, db:seed

Python: How to create a unique file name?

The uuid module would be a good choice, I prefer to use uuid.uuid4().hex as random filename because it will return a hex string without dashes.

import uuid
filename = uuid.uuid4().hex

The outputs should like this:

>>> import uuid
>>> uuid.uuid()
UUID('20818854-3564-415c-9edc-9262fbb54c82')
>>> str(uuid.uuid4())
'f705a69a-8e98-442b-bd2e-9de010132dc4'
>>> uuid.uuid4().hex
'5ad02dfb08a04d889e3aa9545985e304'  # <-- this one

How to write super-fast file-streaming code in C#?

Have you considered using the CCR since you are writing to separate files you can do everything in parallel (read and write) and the CCR makes it very easy to do this.

static void Main(string[] args)
    {
        Dispatcher dp = new Dispatcher();
        DispatcherQueue dq = new DispatcherQueue("DQ", dp);

        Port<long> offsetPort = new Port<long>();

        Arbiter.Activate(dq, Arbiter.Receive<long>(true, offsetPort,
            new Handler<long>(Split)));

        FileStream fs = File.Open(file_path, FileMode.Open);
        long size = fs.Length;
        fs.Dispose();

        for (long i = 0; i < size; i += split_size)
        {
            offsetPort.Post(i);
        }
    }

    private static void Split(long offset)
    {
        FileStream reader = new FileStream(file_path, FileMode.Open, 
            FileAccess.Read);
        reader.Seek(offset, SeekOrigin.Begin);
        long toRead = 0;
        if (offset + split_size <= reader.Length)
            toRead = split_size;
        else
            toRead = reader.Length - offset;

        byte[] buff = new byte[toRead];
        reader.Read(buff, 0, (int)toRead);
        reader.Dispose();
        File.WriteAllBytes("c:\\out" + offset + ".txt", buff);
    }

This code posts offsets to a CCR port which causes a Thread to be created to execute the code in the Split method. This causes you to open the file multiple times but gets rid of the need for synchronization. You can make it more memory efficient but you'll have to sacrifice speed.

ERROR: Google Maps API error: MissingKeyMapError

The script element that loads the API is missing the required authentication parameter. If you are using the standard Maps JavaScript API, you must use a key parameter with a valid API key. If you are a Premium Plan customer, you must use either a client parameter with your client ID or a key parameter with a valid API key.

See the guide to API keys and client IDs.

Reshaping data.frame from wide to long format

You can also use the cdata package, which uses the concept of (transformation) control table:

# data
wide <- read.table(text="Code Country        1950    1951    1952    1953    1954
AFG  Afghanistan    20,249  21,352  22,532  23,557  24,555
ALB  Albania        8,097   8,986   10,058  11,123  12,246", header=TRUE, check.names=FALSE)

library(cdata)
# build control table
drec <- data.frame(
    Year=as.character(1950:1954),
    Value=as.character(1950:1954),
    stringsAsFactors=FALSE
)
drec <- cdata::rowrecs_to_blocks_spec(drec, recordKeys=c("Code", "Country"))

# apply control table
cdata::layout_by(drec, wide)

I am currently exploring that package and find it quite accessible. It is designed for much more complicated transformations and includes the backtransformation. There is a tutorial available.

How to insert data using wpdb

You have to check your quotes properly,

$sql = $wpdb->prepare(
    "INSERT INTO `wp_submitted_form`      
       (`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`) 
 values ($name, $email, $phone, $country, $course, $message, $datesent)");
$wpdb->query($sql);

OR you can use like,

$sql = "INSERT INTO `wp_submitted_form`
          (`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`) 
   values ($name, $email, $phone, $country, $course, $message, $datesent)";

$wpdb->query($sql);

Read http://codex.wordpress.org/Class_Reference/wpdb

How to upgrade pip3?

The Problem

You use pip (the Python 2 one). Now you want to upgrade pip (the Python 3 one). After that, pip is the Python 3 one.

The solution

Use pip2 and pip3. This way it is explicit.

If you want to use pip, just check where it is (which pip) and change the link. For example:

$ which pip
/usr/local/bin/pip

$ pip --version
pip 9.0.1 from /usr/local/lib/python3.5/dist-packages (python 3.5)

$ which pip2
/usr/local/bin/pip2

$ sudo rm /usr/local/bin/pip
$ sudo ln -s /usr/local/bin/pip2 /usr/local/bin/pip

$ pip --version
pip 9.0.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)

What is an example of the Liskov Substitution Principle?

LSP says that ''Objects should be replaceable by their subtypes''. On the other hand, this principle points to

Child classes should never break the parent class`s type definitions.

and the following example helps to have a better understanding of LSP.

Without LSP:

public interface CustomerLayout{

    public void render();
}


public FreeCustomer implements CustomerLayout {
     ...
    @Override
    public void render(){
        //code
    }
}


public PremiumCustomer implements CustomerLayout{
    ...
    @Override
    public void render(){
        if(!hasSeenAd)
            return; //it isn`t rendered in this case
        //code
    }
}

public void renderView(CustomerLayout layout){
    layout.render();
}

Fixing by LSP:

public interface CustomerLayout{
    public void render();
}


public FreeCustomer implements CustomerLayout {
     ...
    @Override
    public void render(){
        //code
    }
}


public PremiumCustomer implements CustomerLayout{
    ...
    @Override
    public void render(){
        if(!hasSeenAd)
            showAd();//it has a specific behavior based on its requirement
        //code
    }
}

public void renderView(CustomerLayout layout){
    layout.render();
}

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

this.form.submit();

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

git checkout tag, git pull fails in branch

I had the same problem and fixed it with this command:

$ git push -u origin master

From the help file the -u basically sets the default for pulls:

-u, --set-upstream`

  For every branch that is up to date or successfully pushed, add 
  upstream (tracking) reference, used by argument-less git-pull(1) and
  other commands. For more information, see branch.<name>.merge in 
  git-config(1).

MySQL ORDER BY rand(), name ASC

Beware of ORDER BY RAND() because of performance and results. Check this article out: http://jan.kneschke.de/projects/mysql/order-by-rand/

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

Try one of these:

  1. Use column alias:

    ORDER BY RadioServiceCodeId,RadioService

  2. Use column position:

    ORDER BY 1,2

You can only order by columns that actually appear in the result of the DISTINCT query - the underlying data isn't available for ordering on.

Fastest way to check a string is alphanumeric in Java

I've written the tests that compare using regular expressions (as per other answers) against not using regular expressions. Tests done on a quad core OSX10.8 machine running Java 1.6

Interestingly using regular expressions turns out to be about 5-10 times slower than manually iterating over a string. Furthermore the isAlphanumeric2() function is marginally faster than isAlphanumeric(). One supports the case where extended Unicode numbers are allowed, and the other is for when only standard ASCII numbers are allowed.

public class QuickTest extends TestCase {

    private final int reps = 1000000;

    public void testRegexp() {
        for(int i = 0; i < reps; i++)
            ("ab4r3rgf"+i).matches("[a-zA-Z0-9]");
    }

public void testIsAlphanumeric() {
    for(int i = 0; i < reps; i++)
        isAlphanumeric("ab4r3rgf"+i);
}

public void testIsAlphanumeric2() {
    for(int i = 0; i < reps; i++)
        isAlphanumeric2("ab4r3rgf"+i);
}

    public boolean isAlphanumeric(String str) {
        for (int i=0; i<str.length(); i++) {
            char c = str.charAt(i);
            if (!Character.isLetterOrDigit(c))
                return false;
        }

        return true;
    }

    public boolean isAlphanumeric2(String str) {
        for (int i=0; i<str.length(); i++) {
            char c = str.charAt(i);
            if (c < 0x30 || (c >= 0x3a && c <= 0x40) || (c > 0x5a && c <= 0x60) || c > 0x7a)
                return false;
        }
        return true;
    }

}

Why do I get access denied to data folder when using adb?

There are two things to remember if you want to browse everything on your device.

  1. You need to have a phone with root access in order to browse the data folder on an Android phone. That means either you have a developer device (ADP1 or an ION from Google I/O) or you've found a way to 'root' your phone some other way.
  2. You need to be running ADB in root mode, do this by executing: adb root

How to run PyCharm in Ubuntu - "Run in Terminal" or "Run"?

The question is already answered, Updating answer to add the PyCharm bin directory to $PATH var, so that pycharm editor can be opened from anywhere(path) in terminal.

Edit the bashrc file,

nano .bashrc

Add following line at the end of bashrc file

export PATH="<path-to-unpacked-pycharm-installation-directory>/bin:$PATH"

Now you can open pycharm from anywhere in terminal

pycharm.sh

Oracle - Insert New Row with Auto Incremental ID

ELXAN@DB1> create table cedvel(id integer,ad varchar2(15));

Table created.

ELXAN@DB1> alter table cedvel add constraint pk_ad primary key(id);

Table altered.

ELXAN@DB1> create sequence test_seq start with 1 increment by 1;

Sequence created.

ELXAN@DB1> create or replace trigger ad_insert
before insert on cedvel
REFERENCING NEW AS NEW OLD AS OLD
for each row
begin
    select test_seq.nextval into :new.id from dual;
end;
/  2    3    4    5    6    7    8 

Trigger created.

ELXAN@DB1> insert into cedvel (ad) values ('nese');

1 row created.

How to draw a checkmark / tick using CSS?

only css, quite simple I find it:

_x000D_
_x000D_
.checkmark {_x000D_
      display: inline-block;_x000D_
      transform: rotate(45deg);_x000D_
      height: 25px;_x000D_
      width: 12px;_x000D_
      margin-left: 60%; _x000D_
      border-bottom: 7px solid #78b13f;_x000D_
      border-right: 7px solid #78b13f;_x000D_
    }
_x000D_
<div class="checkmark"></div>
_x000D_
_x000D_
_x000D_

Custom method names in ASP.NET Web API

This is the best method I have come up with so far to incorporate extra GET methods while supporting the normal REST methods as well. Add the following routes to your WebApiConfig:

routes.MapHttpRoute("DefaultApiWithId", "Api/{controller}/{id}", new { id = RouteParameter.Optional }, new { id = @"\d+" });
routes.MapHttpRoute("DefaultApiWithAction", "Api/{controller}/{action}");
routes.MapHttpRoute("DefaultApiGet", "Api/{controller}", new { action = "Get" }, new { httpMethod = new HttpMethodConstraint(HttpMethod.Get) });
routes.MapHttpRoute("DefaultApiPost", "Api/{controller}", new {action = "Post"}, new {httpMethod = new HttpMethodConstraint(HttpMethod.Post)});

I verified this solution with the test class below. I was able to successfully hit each method in my controller below:

public class TestController : ApiController
{
    public string Get()
    {
        return string.Empty;
    }

    public string Get(int id)
    {
        return string.Empty;
    }

    public string GetAll()
    {
        return string.Empty;
    }

    public void Post([FromBody]string value)
    {
    }

    public void Put(int id, [FromBody]string value)
    {
    }

    public void Delete(int id)
    {
    }
}

I verified that it supports the following requests:

GET /Test
GET /Test/1
GET /Test/GetAll
POST /Test
PUT /Test/1
DELETE /Test/1

Note That if your extra GET actions do not begin with 'Get' you may want to add an HttpGet attribute to the method.

How to convert hex to rgb using Java?

I guess this should do it:

/**
 * 
 * @param colorStr e.g. "#FFFFFF"
 * @return 
 */
public static Color hex2Rgb(String colorStr) {
    return new Color(
            Integer.valueOf( colorStr.substring( 1, 3 ), 16 ),
            Integer.valueOf( colorStr.substring( 3, 5 ), 16 ),
            Integer.valueOf( colorStr.substring( 5, 7 ), 16 ) );
}

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

How to stop execution after a certain time in Java?

If you can't go over your time limit (it's a hard limit) then a thread is your best bet. You can use a loop to terminate the thread once you get to the time threshold. Whatever is going on in that thread at the time can be interrupted, allowing calculations to stop almost instantly. Here is an example:

Thread t = new Thread(myRunnable); // myRunnable does your calculations

long startTime = System.currentTimeMillis();
long endTime = startTime + 60000L;

t.start(); // Kick off calculations

while (System.currentTimeMillis() < endTime) {
    // Still within time theshold, wait a little longer
    try {
         Thread.sleep(500L);  // Sleep 1/2 second
    } catch (InterruptedException e) {
         // Someone woke us up during sleep, that's OK
    }
}

t.interrupt();  // Tell the thread to stop
t.join();       // Wait for the thread to cleanup and finish

That will give you resolution to about 1/2 second. By polling more often in the while loop, you can get that down.

Your runnable's run would look something like this:

public void run() {
    while (true) {
        try {
            // Long running work
            calculateMassOfUniverse();
        } catch (InterruptedException e) {
            // We were signaled, clean things up
            cleanupStuff();
            break;           // Leave the loop, thread will exit
    }
}

Update based on Dmitri's answer

Dmitri pointed out TimerTask, which would let you avoid the loop. You could just do the join call and the TimerTask you setup would take care of interrupting the thread. This would let you get more exact resolution without having to poll in a loop.

How to restore the permissions of files and directories within git if they have been modified?

i know this is old, but i came from google and i didn't find an answer

i have a simple solution if you have no change you want to keep :

git config core.fileMode true
git reset --hard HEAD

How to check if there exists a process with a given pid in Python?

Building upon ntrrgc's I've beefed up the windows version so it checks the process exit code and checks for permissions:

def pid_exists(pid):
    """Check whether pid exists in the current process table."""
    if os.name == 'posix':
        import errno
        if pid < 0:
            return False
        try:
            os.kill(pid, 0)
        except OSError as e:
            return e.errno == errno.EPERM
        else:
            return True
    else:
        import ctypes
        kernel32 = ctypes.windll.kernel32
        HANDLE = ctypes.c_void_p
        DWORD = ctypes.c_ulong
        LPDWORD = ctypes.POINTER(DWORD)
        class ExitCodeProcess(ctypes.Structure):
            _fields_ = [ ('hProcess', HANDLE),
                ('lpExitCode', LPDWORD)]

        SYNCHRONIZE = 0x100000
        process = kernel32.OpenProcess(SYNCHRONIZE, 0, pid)
        if not process:
            return False

        ec = ExitCodeProcess()
        out = kernel32.GetExitCodeProcess(process, ctypes.byref(ec))
        if not out:
            err = kernel32.GetLastError()
            if kernel32.GetLastError() == 5:
                # Access is denied.
                logging.warning("Access is denied to get pid info.")
            kernel32.CloseHandle(process)
            return False
        elif bool(ec.lpExitCode):
            # print ec.lpExitCode.contents
            # There is an exist code, it quit
            kernel32.CloseHandle(process)
            return False
        # No exit code, it's running.
        kernel32.CloseHandle(process)
        return True

Conditional Replace Pandas

Try this:

df.my_channel = df.my_channel.where(df.my_channel <= 20000, other= 0)

or

df.my_channel = df.my_channel.mask(df.my_channel > 20000, other= 0)

How do I use a C# Class Library in a project?

In the Solution Explorer window, right click the project you want to use your class library from and click the 'Add Reference' menu item. Then if the class library is in the same solution file, go to the projects tab and select it; if it's not in the same tab, you can go to the Browse tab and find it that way.

Then you can use anything in that assembly.

Show Console in Windows Application?

Easiest way is to start a WinForms application, go to settings and change the type to a console application.

Adding a rule in iptables in debian to open a new port

About your command line:

root@debian:/# sudo iptables -A INPUT -p tcp --dport 3306 --jump ACCEPT
root@debian:/# iptables-save
  • You are already authenticated as root so sudo is redundant there.

  • You are missing the -j or --jump just before the ACCEPT parameter (just tought that was a typo and you are inserting it correctly).

About yout question:

If you are inserting the iptables rule correctly as you pointed it in the question, maybe the issue is related to the hypervisor (virtual machine provider) you are using.

If you provide the hypervisor name (VirtualBox, VMWare?) I can further guide you on this but here are some suggestions you can try first:

check your vmachine network settings and:

  • if it is set to NAT, then you won't be able to connect from your base machine to the vmachine.

  • if it is set to Hosted, you have to configure first its network settings, it is usually to provide them an IP in the range 192.168.56.0/24, since is the default the hypervisors use for this.

  • if it is set to Bridge, same as Hosted but you can configure it whenever IP range makes sense for you configuration.

Hope this helps.

Data binding for TextBox

You need a bindingsource object to act as an intermediary and assist in the binding. Then instead of updating the user interface, update the underlining model.

var model = (Fruit) bindingSource1.DataSource;

model.FruitType = "oranges";

bindingSource.ResetBindings();

Read up on BindingSource and simple data binding for Windows Forms.

How to find a text inside SQL Server procedures / triggers?

Just wrote this for generic full outer cross ref

create table #XRefDBs(xtype varchar(2),SourceDB varchar(100), Object varchar(100), RefDB varchar(100))

declare @sourcedbname varchar(100),
        @searchfordbname varchar(100),
        @sql nvarchar(4000)
declare curs cursor for
    select name 
    from sysdatabases
    where dbid>4
open curs
fetch next from curs into @sourcedbname
while @@fetch_status=0
    begin
    print @sourcedbname
    declare curs2 cursor for 
        select name 
        from sysdatabases
        where dbid>4
        and name <> @sourcedbname
    open curs2
    fetch next from curs2 into @searchfordbname
    while @@fetch_status=0
        begin
        print @searchfordbname
        set @sql = 
        'INSERT INTO #XRefDBs (xtype,SourceDB,Object, RefDB)
        select DISTINCT o.xtype,'''+@sourcedbname+''', o.name,'''+@searchfordbname+'''
        from '+@sourcedbname+'.dbo.syscomments c
        join '+@sourcedbname+'.dbo.sysobjects o on c.id=o.id
        where o.xtype in (''V'',''P'',''FN'',''TR'')
        and (text like ''%'+@searchfordbname+'.%''
          or text like ''%'+@searchfordbname+'].%'')'
        print @sql
        exec sp_executesql @sql
        fetch next from curs2 into @searchfordbname
        end
    close curs2
    deallocate curs2
    fetch next from curs into @sourcedbname
    end
close curs
deallocate curs

select * from #XRefDBs

How do I check if an object's type is a particular subclass in C++?

dynamic_cast can determine if the type contains the target type anywhere in the inheritance hierarchy (yes, it's a little-known feature that if B inherits from A and C, it can turn an A* directly into a C*). typeid() can determine the exact type of the object. However, these should both be used extremely sparingly. As has been mentioned already, you should always be avoiding dynamic type identification, because it indicates a design flaw. (also, if you know the object is for sure of the target type, you can do a downcast with a static_cast. Boost offers a polymorphic_downcast that will do a downcast with dynamic_cast and assert in debug mode, and in release mode it will just use a static_cast).

How do I add target="_blank" to a link within a specified div?

Non-jquery:

// Very old browsers
// var linkList = document.getElementById('link_other').getElementsByTagName('a');

// New browsers (IE8+)
var linkList = document.querySelectorAll('#link_other a');

for(var i in linkList){
 linkList[i].setAttribute('target', '_blank');
}

Saving to CSV in Excel loses regional date format

A not so scalable fix that I used for this is to copy the data to a plain text editor, convert the cells to text and then copy the data back to the spreadsheet.

How to define constants in Visual C# like #define in C?

What is the "Visual C#"? There is no such thing. Just C#, or .NET C# :)

Also, Python's convention for constants CONSTANT_NAME is not very common in C#. We are usually using CamelCase according to MSDN standards, e.g. public const string ExtractedMagicString = "vs2019";

Source: Defining constants in C#

Get a resource using getResource()

if you are calling from static method, use :

TestGameTable.class.getClassLoader().getResource("dice.jpg");

How do you get current active/default Environment profile programmatically in Spring?

Here is a more complete example.

Autowire Environment

First you will want to autowire the environment bean.

@Autowired
private Environment environment;

Check if Profiles exist in Active Profiles

Then you can use getActiveProfiles() to find out if the profile exists in the list of active profiles. Here is an example that takes the String[] from getActiveProfiles(), gets a stream from that array, then uses matchers to check for multiple profiles(Case-Insensitive) which returns a boolean if they exist.

//Check if Active profiles contains "local" or "test"
if(Arrays.stream(environment.getActiveProfiles()).anyMatch(
   env -> (env.equalsIgnoreCase("test") 
   || env.equalsIgnoreCase("local")) )) 
{
   doSomethingForLocalOrTest();
}
//Check if Active profiles contains "prod"
else if(Arrays.stream(environment.getActiveProfiles()).anyMatch(
   env -> (env.equalsIgnoreCase("prod")) )) 
{
   doSomethingForProd();
}

You can also achieve similar functionality using the annotation @Profile("local") Profiles allow for selective configuration based on a passed-in or environment parameter. Here is more information on this technique: Spring Profiles

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

Any reason to prefer getClass() over instanceof when generating .equals()?

If you want to ensure only that class will match then use getClass() ==. If you want to match subclasses then instanceof is needed.

Also, instanceof will not match against a null but is safe to compare against a null. So you don't have to null check it.

if ( ! (obj instanceof MyClass) ) { return false; }

How to overcome TypeError: unhashable type: 'list'

As indicated by the other answers, the error is to due to k = list[0:j], where your key is converted to a list. One thing you could try is reworking your code to take advantage of the split function:

# Using with ensures that the file is properly closed when you're done
with open('filename.txt', 'rb') as f:
  d = {}
  # Here we use readlines() to split the file into a list where each element is a line
  for line in f.readlines():
    # Now we split the file on `x`, since the part before the x will be
    # the key and the part after the value
    line = line.split('x')
    # Take the line parts and strip out the spaces, assigning them to the variables
    # Once you get a bit more comfortable, this works as well:
    # key, value = [x.strip() for x in line] 
    key = line[0].strip()
    value = line[1].strip()
    # Now we check if the dictionary contains the key; if so, append the new value,
    # and if not, make a new list that contains the current value
    # (For future reference, this is a great place for a defaultdict :)
    if key in d:
      d[key].append(value)
    else:
      d[key] = [value]

print d
# {'AAA': ['111', '112'], 'AAC': ['123'], 'AAB': ['111']}

Note that if you are using Python 3.x, you'll have to make a minor adjustment to get it work properly. If you open the file with rb, you'll need to use line = line.split(b'x') (which makes sure you are splitting the byte with the proper type of string). You can also open the file using with open('filename.txt', 'rU') as f: (or even with open('filename.txt', 'r') as f:) and it should work fine.

jQuery: Setting select list 'selected' based on text, failing strangely

Using the filter() function seems to work in your test cases (tested in Firefox). The selector would look like this:

$('#mySelect1 option').filter(function () {
    return $(this).text() === 'Banana';
});

add scroll bar to table body

These solutions often have issues with the header columns aligning with the body columns, and may not work properly when resizing. I know you didn't want to use an additional library, but if you happen to be using jQuery, this one is really small. It supports fixed header, footer, column spanning (colspan), horizontal scrolling, resizing, and an optional number of rows to display before scrolling starts.

jQuery.scrollTableBody (GitHub)

As long as you have a table with proper <thead>, <tbody>, and (optional) <tfoot>, all you need to do is this:

$('table').scrollTableBody();

How to position the form in the center screen?

Try using this:

this.setBounds(x,y,w,h);

In Firebase, is there a way to get the number of children of a node without loading all the node data?

This is a little late in the game as several others have already answered nicely, but I'll share how I might implement it.

This hinges on the fact that the Firebase REST API offers a shallow=true parameter.

Assume you have a post object and each one can have a number of comments:

{
 "posts": {
  "$postKey": {
   "comments": {
     ...  
   }
  }
 }
}

You obviously don't want to fetch all of the comments, just the number of comments.

Assuming you have the key for a post, you can send a GET request to https://yourapp.firebaseio.com/posts/[the post key]/comments?shallow=true.

This will return an object of key-value pairs, where each key is the key of a comment and its value is true:

{
 "comment1key": true,
 "comment2key": true,
 ...,
 "comment9999key": true
}

The size of this response is much smaller than requesting the equivalent data, and now you can calculate the number of keys in the response to find your value (e.g. commentCount = Object.keys(result).length).

This may not completely solve your problem, as you are still calculating the number of keys returned, and you can't necessarily subscribe to the value as it changes, but it does greatly reduce the size of the returned data without requiring any changes to your schema.

What does it mean to have an index to scalar variable error? python

exponent is a 1D array. This means that exponent[0] is a scalar, and exponent[0][i] is trying to access it as if it were an array.

Did you mean to say:

L = identity(len(l))
for i in xrange(len(l)):
    L[i][i] = exponent[i]

or even

L = diag(exponent)

?

grep using a character vector with multiple patterns

In addition to @Marek's comment about not including fixed==TRUE, you also need to not have the spaces in your regular expression. It should be "A1|A9|A6".

You also mention that there are lots of patterns. Assuming that they are in a vector

toMatch <- c("A1", "A9", "A6")

Then you can create your regular expression directly using paste and collapse = "|".

matches <- unique (grep(paste(toMatch,collapse="|"), 
                        myfile$Letter, value=TRUE))

"Use the new keyword if hiding was intended" warning

In the code below, Class A implements the interface IShow and implements its method ShowData. Class B inherits Class A. In order to use ShowData method in Class B, we have to use keyword new in the ShowData method in order to hide the base class Class A method and use override keyword in order to extend the method.

interface IShow
{
    protected void ShowData();
}

class A : IShow
{
    protected void ShowData()
    {
        Console.WriteLine("This is Class A");
    }
}

class B : A
{
    protected new void ShowData()
    {
        Console.WriteLine("This is Class B");
    }
}

Set a cookie to never expire

You can't but what if you set expire time to now + 100 years ?

R barplot Y-axis scale too short

Simplest solution seems to be specifying the ylim range. Here is some code to do this automatically (left default, right - adjusted):

# default y-axis
barplot(dat, beside=TRUE)

# automatically adjusted y-axis
barplot(dat, beside=TRUE, ylim=range(pretty(c(0, dat))))

img

The trick is to use pretty() which returns a list of interval breaks covering all values of the provided data. It guarantees that the maximum returned value is 1) a round number 2) greater than maximum value in the data.

In the example 0 was also added pretty(c(0, dat)) which makes sure that axis starts from 0.

$(document).on("click"... not working?

An old post, but I love to share as I have the same case but I finally knew the problem :

Problem is : We make a function to work with specified an HTML element, but the HTML element related to this function is not yet created (because the element was dynamically generated). To make it works, we should make the function at the same time we create the element. Element first than make function related to it.

Simply word, a function will only works to the element that created before it (him). Any elements that created dynamically means after him.

But please inspect this sample that did not heed the above case :

<div class="btn-list" id="selected-country"></div>

Dynamically appended :

<button class="btn-map" data-country="'+country+'">'+ country+' </button>

This function is working good by clicking the button :

$(document).ready(function() {    
        $('#selected-country').on('click','.btn-map', function(){ 
        var datacountry = $(this).data('country'); console.log(datacountry);
    });
})

or you can use body like :

$('body').on('click','.btn-map', function(){ 
            var datacountry = $(this).data('country'); console.log(datacountry);
        });

compare to this that not working :

$(document).ready(function() {     
$('.btn-map').on("click", function() { 
        var datacountry = $(this).data('country'); alert(datacountry);
    });
});

hope it will help

In Ruby on Rails, what's the difference between DateTime, Timestamp, Time and Date?

  1. :datetime (8 bytes)

    • Stores Date and Time formatted YYYY-MM-DD HH:MM:SS
    • Useful for columns like birth_date
  2. :timestamp (4 bytes)

    • Stores number of seconds since 1970-01-01
    • Useful for columns like updated_at, created_at
  3. :date (3 bytes)
    • Stores Date
  4. :time (3 bytes)
    • Stores Time

ASP.NET GridView RowIndex As CommandArgument

<asp:LinkButton ID="LnkBtn" runat="server" Text="Text" RowIndex='<%# Container.DisplayIndex %>' CommandArgument='<%# Eval("??") %>' OnClick="LnkBtn_Click" />

inside your event handler :

Protected Sub LnkBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
  dim rowIndex as integer = sender.Attributes("RowIndex")
  'Here you can use also the command argument for any other value.
End Sub

How to sleep for five seconds in a batch file/cmd

I was trying to do this from within an msbuild task, and choice and timeout both did not work due to I/O redirection.

I ended up using sleep.exe from http://sourceforge.net/projects/unxutils, which is nice because it doesn't require any install and it's tiny.


Trying with choice:

<Target Name="TestCmd">
  <Exec Command="choice /C YN /D Y /t 5 " />
</Target>

Results in:

TestCmd:
  choice /C YN /D Y /t 5

EXEC : error : The file is either empty or does not contain the valid choices. [test.proj]
  [Y,N]?
C:\test.proj(5,9): error MSB3073: The command "choice /C YN /D Y /t 5 " exited with code 255.

Trying with timeout:

<Target Name="TestCmd">
  <Exec Command="timeout /t 5 " />
</Target>

Results in:

TestCmd:
  timeout /t 5
EXEC : error : Input redirection is not supported, exiting the process immediately. [test.proj]
C:\test.proj(5,7): error MSB3073: The command "timeout /t 5 " exited with code 1.

Aside:

I am actually using <Exec Command="sleep 2 & dbghost.exe" /> because I am executing dbghost.exe multiple times in parallel and it creates temp files/databases based on the current epoch time in seconds - which of course means if you start multiple instances, each uses the same temp name. I was originally trying to use MSBuild Extension Pack Thread.Sleep command, but it seems that (usually) it was running the sleep task fine, but then starting the <exec> task in all threads at the same time, and of course dbghost.exe would fail with conflicts. So far, using sleep.exe seems to be more reliable.

Regular expression for exact match of a string

if you have a the input password in a variable and you want to match exactly 123456 then anchors will help you:

/^123456$/

in perl the test for matching the password would be something like

print "MATCH_OK" if ($input_pass=~/^123456$/);

EDIT:

bart kiers is right tho, why don't you use a strcmp() for this? every language has it in its own way

as a second thought, you may want to consider a safer authentication mechanism :)

FileNotFoundException while getting the InputStream object from HttpURLConnection

To anyone with this problem in the future, the reason is because the status code was a 404 (or in my case was a 500). It appears the InpuStream function will throw an error when the status code is not 200.

In my case I control my own server and was returning a 500 status code to indicate an error occurred. Despite me also sending a body with a string message detailing the error, the inputstream threw an error regardless of the body being completely readable.

If you control your server I suppose this can be handled by sending yourself a 200 status code and then handling whatever the string error response was.

Change the selected value of a drop-down list with jQuery

These solutions seem to assume that each item in your drop down lists has a val() value relating to their position in the drop down list.

Things are a little more complicated if this isn't the case.

To read the selected index of a drop down list, you would use this:

$("#dropDownList").prop("selectedIndex");

To set the selected index of a drop down list, you would use this:

$("#dropDownList").prop("selectedIndex", 1);

Note that the prop() feature requires JQuery v1.6 or later.

Let's see how you would use these two functions.

Supposing you had a drop down list of month names.

<select id="listOfMonths">
  <option id="JAN">January</option>
  <option id="FEB">February</option>
  <option id="MAR">March</option>
</select>

You could add a "Previous Month" and "Next Month" button, which looks at the currently selected drop down list item, and changes it to the previous/next month:

<button id="btnPrevMonth" title="Prev" onclick="btnPrevMonth_Click();return false;" />
<button id="btnNextMonth" title="Next" onclick="btnNextMonth_Click();return false;" />

And here's the JavaScript which these buttons would run:

function btnPrevMonth_Click() {
    var selectedIndex = $("#listOfMonths").prop("selectedIndex");
    if (selectedIndex > 0) {
        $("#listOfMonths").prop("selectedIndex", selectedIndex - 1);
    }
}
function btnNextMonth_Click() {
    //  Note:  the JQuery "prop" function requires JQuery v1.6 or later
    var selectedIndex = $("#listOfMonths").prop("selectedIndex");
    var itemsInDropDownList = $("#listOfMonths option").length;

    //  If we're not already selecting the last item in the drop down list, then increment the SelectedIndex
    if (selectedIndex < (itemsInDropDownList - 1)) {
        $("#listOfMonths").prop("selectedIndex", selectedIndex + 1);
    }
}

My site is also useful for showing how to populate a drop down list with JSON data:

http://mikesknowledgebase.com/pages/Services/WebServices-Page8.htm

How do I convert datetime.timedelta to minutes, hours in Python?

I don't think it's a good idea to caculate yourself.

If you just want a pretty output, just covert it into str with str() function or directly print() it.

And if there's further usage of the hours and minutes, you can parse it to datetime object use datetime.strptime()(and extract the time part with datetime.time() mehtod), for example:

import datetime

delta = datetime.timedelta(seconds=10000)
time_obj = datetime.datetime.strptime(str(delta),'%H:%M:%S').time()

Mysql - How to quit/exit from stored procedure

If you want an "early exit" for a situation in which there was no error, then use the accepted answer posted by @piotrm. Most typically, however, you will be bailing due to an error condition (especially in a SQL procedure).

As of MySQL v5.5 you can throw an exception. Negating exception handlers, etc. that will achieve the same result, but in a cleaner, more precise manner.

Here's how:

DECLARE CUSTOM_EXCEPTION CONDITION FOR SQLSTATE '45000';

IF <Some Error Condition> THEN      
    SIGNAL CUSTOM_EXCEPTION
    SET MESSAGE_TEXT = 'Your Custom Error Message';
END IF;     

Note SQLSTATE '45000' equates to "Unhandled user-defined exception condition". By default, this will produce an error code of 1644 (which has that same meaning). Note that you can throw other condition codes or error codes if you want (plus additional details for exception handling).

For more on this subject, check out:

https://dev.mysql.com/doc/refman/5.5/en/signal.html

How to raise an error within a MySQL function

http://www.databasejournal.com/features/mysql/mysql-error-handling-using-the-signal-and-resignal-statements.html

Addendum

As I'm re-reading this post of mine, I realized I had something additional to add. Prior to MySQL v5.5, there was a way to emulate throwing an exception. It's not the same thing exactly, but this was the analogue: Create an error via calling a procedure which does not exist. Call the procedure by a name which is meaningful in order to get a useful means by which to determine what the problem was. When the error occurs, you'll get to see the line of failure (depending on your execution context).

For example:

CALL AttemptedToInsertSomethingInvalid;

Note that when you create a procedure, there is no validation performed on such things. So while in something like a compiled language, you could never call a function that wasn't there, in a script like this it will simply fail at runtime, which is exactly what is desired in this case!

How to set image name in Dockerfile?

How to build an image with custom name without using yml file:

docker build -t image_name .

How to run a container with custom name:

docker run -d --name container_name image_name

Get the current displaying UIViewController on the screen in AppDelegate.m

I have found that iOS 8 has screwed everything up. In iOS 7 there is a new UITransitionView on the view hierarchy whenever you have a modally presented UINavigationController. Anyway, here's my code that finds gets the topmost VC. Calling getTopMostViewController should return a VC that you should be able to send a message like presentViewController:animated:completion. It's purpose is to get you a VC that you can use to present a modal VC, so it will most likely stop and return at container classes like UINavigationController and NOT the VC contained within them. Should not be hard to adapt the code to do that too. I've tested this code in various situations in iOS 6, 7 and 8. Please let me know if you find bugs.

+ (UIViewController*) getTopMostViewController
{
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(window in windows) {
            if (window.windowLevel == UIWindowLevelNormal) {
                break;
            }
        }
    }

    for (UIView *subView in [window subviews])
    {
        UIResponder *responder = [subView nextResponder];

        //added this block of code for iOS 8 which puts a UITransitionView in between the UIWindow and the UILayoutContainerView
        if ([responder isEqual:window])
        {
            //this is a UITransitionView
            if ([[subView subviews] count])
            {
                UIView *subSubView = [subView subviews][0]; //this should be the UILayoutContainerView
                responder = [subSubView nextResponder];
            }
        }

        if([responder isKindOfClass:[UIViewController class]]) {
            return [self topViewController: (UIViewController *) responder];
        }
    }

    return nil;
}

+ (UIViewController *) topViewController: (UIViewController *) controller
{
    BOOL isPresenting = NO;
    do {
        // this path is called only on iOS 6+, so -presentedViewController is fine here.
        UIViewController *presented = [controller presentedViewController];
        isPresenting = presented != nil;
        if(presented != nil) {
            controller = presented;
        }

    } while (isPresenting);

    return controller;
}

How to get info on sent PHP curl request

You can also use a proxy tool like Charles to capture the outgoing request headers, data, etc. by passing the proxy details through CURLOPT_PROXY to your curl_setopt_array method.

For example:

$proxy = '127.0.0.1:8888';
$opt = array (
    CURLOPT_URL => "http://www.example.com",
    CURLOPT_PROXY => $proxy,
    CURLOPT_POST => true,
    CURLOPT_VERBOSE => true,
    );

$ch = curl_init();
curl_setopt_array($ch, $opt);
curl_exec($ch);
curl_close($ch);

Hashing with SHA1 Algorithm in C#

Fastest way is this :

    public static string GetHash(string input)
    {
        return string.Join("", (new SHA1Managed().ComputeHash(Encoding.UTF8.GetBytes(input))).Select(x => x.ToString("X2")).ToArray());
    }

For Small character output use x2 in replace of of X2

Purpose of Activator.CreateInstance with example?

My good friend MSDN can explain it to you, with an example

Here is the code in case the link or content changes in the future:

using System;

class DynamicInstanceList
{
    private static string instanceSpec = "System.EventArgs;System.Random;" +
        "System.Exception;System.Object;System.Version";

    public static void Main()
    {
        string[] instances = instanceSpec.Split(';');
        Array instlist = Array.CreateInstance(typeof(object), instances.Length);
        object item;
        for (int i = 0; i < instances.Length; i++)
        {
            // create the object from the specification string
            Console.WriteLine("Creating instance of: {0}", instances[i]);
            item = Activator.CreateInstance(Type.GetType(instances[i]));
            instlist.SetValue(item, i);
        }
        Console.WriteLine("\nObjects and their default values:\n");
        foreach (object o in instlist)
        {
            Console.WriteLine("Type:     {0}\nValue:    {1}\nHashCode: {2}\n",
                o.GetType().FullName, o.ToString(), o.GetHashCode());
        }
    }
}

// This program will display output similar to the following: 
// 
// Creating instance of: System.EventArgs 
// Creating instance of: System.Random 
// Creating instance of: System.Exception 
// Creating instance of: System.Object 
// Creating instance of: System.Version 
// 
// Objects and their default values: 
// 
// Type:     System.EventArgs 
// Value:    System.EventArgs 
// HashCode: 46104728 
// 
// Type:     System.Random 
// Value:    System.Random 
// HashCode: 12289376 
// 
// Type:     System.Exception 
// Value:    System.Exception: Exception of type 'System.Exception' was thrown. 
// HashCode: 55530882 
// 
// Type:     System.Object 
// Value:    System.Object 
// HashCode: 30015890 
// 
// Type:     System.Version 
// Value:    0.0 
// HashCode: 1048575

How to completely remove borders from HTML table

In a bootstrap environment none of the top answers helped, but applying the following removed all borders:

.noBorder {
    border:none !important;
}

Applied as:

<td class="noBorder">

Change primary key column in SQL Server

Necromancing.
It looks you have just as good a schema to work with as me... Here is how to do it correctly:

In this example, the table name is dbo.T_SYS_Language_Forms, and the column name is LANG_UID

-- First, chech if the table exists...
IF 0 < (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE = 'BASE TABLE'
    AND TABLE_SCHEMA = 'dbo'
    AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
    -- Check for NULL values in the primary-key column
    IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
    BEGIN
        ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL 

        -- No, don't drop, FK references might already exist...
        -- Drop PK if exists 
        -- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name 
        --DECLARE @pkDropCommand nvarchar(1000) 
        --SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
        --WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
        --AND TABLE_SCHEMA = 'dbo' 
        --AND TABLE_NAME = 'T_SYS_Language_Forms' 
        ----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
        --))
        ---- PRINT @pkDropCommand 
        --EXECUTE(@pkDropCommand) 

        -- Instead do
        -- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';


        -- Check if they keys are unique (it is very possible they might not be) 
        IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
        BEGIN

            -- If no Primary key for this table
            IF 0 =  
            (
                SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
                AND TABLE_SCHEMA = 'dbo' 
                AND TABLE_NAME = 'T_SYS_Language_Forms' 
                -- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
            )
                ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
            ;

            -- Adding foreign key
            IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms') 
                ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID); 
        END -- End uniqueness check
        ELSE
            PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...' 
    END -- End NULL check
    ELSE
        PRINT 'FSCK, need to figure out how to update NULL value(s)...' 
END 

Make install, but not to default directories?

If the package provides a Makefile.PL - one can use:

perl Makefile.PL PREFIX=/home/my/local/lib LIB=/home/my/local/lib
make
make test
make install

* further explanation: https://www.perlmonks.org/?node_id=564720

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!

Thus, the way I fixed it was:

apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -

Then running a new "apt-get update" worked flawlessly!

using if else with eval in aspx page

If you are trying to bind is a Model class, you can add a new readonly property to it like:

public string FormattedPercentage
{
    get
    {
        If(this.Percentage < 50)
            return "0 %";
        else 
            return string.Format("{0} %", this.Percentage)        
     }
}

Otherwise you can use Andrei's or kostas ch. suggestions if you cannot modify the class itself

IIS: Display all sites and bindings in PowerShell

I found this question because I wanted to generate a web page with links to all the websites running on my IIS instance. I used Alexander Shapkin's answer to come up with the following to generate a bunch of links.

$hostname = "localhost"

Foreach ($Site in get-website) {
    Foreach ($Bind in $Site.bindings.collection) {
        $data = [PSCustomObject]@{
            name=$Site.name;
            Protocol=$Bind.Protocol;
            Bindings=$Bind.BindingInformation
        }
        $data.Bindings = $data.Bindings -replace '(:$)', ''
        $html = "<a href=""" + $data.Protocol + "://" + $data.Bindings + """>" + $data.name + "</a>"
        $html.Replace("*", $hostname);
    }
}

Then I paste the results into this hastily written HTML:

<html>
<style>
    a { display: block; }
</style>
{paste PowerShell results here}
</body>
</html>

How to do a https request with bad certificate?

The correct way to do this if you want to maintain the default transport settings is now (as of Go 1.13):

customTransport := http.DefaultTransport.(*http.Transport).Clone()
customTransport.TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
client = &http.Client{Transport: customTransport}

Transport.Clone makes a deep copy of the transport. This way you don't have to worry about missing any new fields that get added to the Transport struct over time.

Drop a temporary table if it exists

From SQL Server 2016 you can just use

 DROP TABLE IF EXISTS ##CLIENTS_KEYWORD

On previous versions you can use

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
/*Then it exists*/
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD
(
   client_id INT
)

You could also consider truncating the table instead rather than dropping and recreating.

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
  TRUNCATE TABLE ##CLIENTS_KEYWORD
ELSE
  CREATE TABLE ##CLIENTS_KEYWORD
  (
     client_id INT
  ) 

How do I force Robocopy to overwrite files?

This is really weird, why nobody is mentioning the /IM switch ?! I've been using it for a long time in backup jobs. But I tried googling just now and I couldn't land on a single web page that says anything about it even on MS website !!! Also found so many user posts complaining about the same issue!!

Anyway.. to use Robocopy to overwrite EVERYTHING what ever size or time in source or distination you must include these three switches in your command (/IS /IT /IM)

/IS :: Include Same files. (Includes same size files)
/IT :: Include Tweaked files. (Includes same files with different Attributes)
/IM :: Include Modified files (Includes same files with different times).

This is the exact command I use to transfer few TeraBytes of mostly 1GB+ files (ISOs - Disk Images - 4K Videos):

robocopy B:\Source D:\Destination /E /J /COPYALL /MT:1 /DCOPY:DATE /IS /IT /IM /X /V /NP /LOG:A:\ROBOCOPY.LOG

I did a small test for you .. and here is the result:

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :      1028      1028         0         0         0       169
   Files :      8053      8053         0         0         0         1
   Bytes : 649.666 g 649.666 g         0         0         0   1.707 g
   Times :   2:46:53   0:41:43                       0:00:00   0:41:44


   Speed :           278653398 Bytes/sec.
   Speed :           15944.675 MegaBytes/min.
   Ended : Friday, August 21, 2020 7:34:33 AM

Dest, Disk: WD Gold 6TB (Compare the write speed with my result)

Even with those "Extras", that's for reporting only because of the "/X" switch. As you can see nothing was Skipped and Total number and size of all files are equal to the Copied. Sometimes It will show small number of skipped files when I abuse it and cancel it multiple times during operation but even with that the values in the first 2 columns are always Equal. I also confirmed that once before by running a PowerShell script that scans all files in destination and generate a report of all time-stamps.

Some performance tips from my history with it and so many tests & troubles!:

. Despite of what most users online advise to use maximum threads "/MT:128" like it's a general trick to get the best performance ... PLEASE DON'T USE "/MT:128" WITH VERY LARGE FILES ... that's a big mistake and it will decrease your drive performance dramatically after several runs .. it will create very high fragmentation or even cause the files system to fail in some cases and you end up spending valuable time trying to recover a RAW partition and all that nonsense. And above all that, It will perform 4-6 times slower!!

For very large files:

  1. Use Only "One" thread "/MT:1" | Impact: BIG
  2. Must use "/J" to disable buffering. | Impact: High
  3. Use "/NP" with "/LOG:file" and Don't output to the console by "/TEE" | Impact: Medium.
  4. Put the "/LOG:file" on a separate drive from the source or destination | Impact: Low.

For regular big files:

  1. Use multi threads, I would not exceed "/MT:4" | Impact: BIG
  2. IF destination disk has low Cache specs use "/J" to disable buffering | Impact: High
  3. & 4 same as above.

For thousands of tiny files:

  1. Go nuts :) with Multi threads, at first I would start with 16 and multibly by 2 while monitoring the disk performance. Once it starts dropping I'll fall back to the prevouse value and stik with it | Impact: BIG
  2. Don't use "/J" | Impact: High
  3. Use "/NP" with "/LOG:file" and Don't output to the console by "/TEE" | Impact: HIGH.
  4. Put the "/LOG:file" on a separate drive from the source or destination | Impact: HIGH.

Update .NET web service to use TLS 1.2

if you're using .Net earlier than 4.5 you wont have Tls12 in the enum so state is explicitly mentioned here

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

Simple dictionary in C++

If you are into optimization, and assuming the input is always one of the four characters, the function below might be worth a try as a replacement for the map:

char map(const char in)
{ return ((in & 2) ? '\x8a' - in : '\x95' - in); }

It works based on the fact that you are dealing with two symmetric pairs. The conditional works to tell apart the A/T pair from the G/C one ('G' and 'C' happen to have the second-least-significant bit in common). The remaining arithmetics performs the symmetric mapping. It's based on the fact that a = (a + b) - b is true for any a,b.

The network adapter could not establish the connection - Oracle 11g

First check your listener is on or off. Go to net manager then Local -> service naming -> orcl. Then change your HOST NAME and put your PC name. Now go to LISTENER and change the HOST and put your PC name.

How to move (and overwrite) all files from one directory to another?

mv -f source target

From the man page:

-f, --force
          do not prompt before overwriting

How to set xlim and ylim for a subplot in matplotlib

You should use the OO interface to matplotlib, rather than the state machine interface. Almost all of the plt.* function are thin wrappers that basically do gca().*.

plt.subplot returns an axes object. Once you have a reference to the axes object you can plot directly to it, change its limits, etc.

import matplotlib.pyplot as plt

ax1 = plt.subplot(131)
ax1.scatter([1, 2], [3, 4])
ax1.set_xlim([0, 5])
ax1.set_ylim([0, 5])


ax2 = plt.subplot(132)
ax2.scatter([1, 2],[3, 4])
ax2.set_xlim([0, 5])
ax2.set_ylim([0, 5])

and so on for as many axes as you want.

or better, wrap it all up in a loop:

import matplotlib.pyplot as plt

DATA_x = ([1, 2],
          [2, 3],
          [3, 4])

DATA_y = DATA_x[::-1]

XLIMS = [[0, 10]] * 3
YLIMS = [[0, 10]] * 3

for j, (x, y, xlim, ylim) in enumerate(zip(DATA_x, DATA_y, XLIMS, YLIMS)):
    ax = plt.subplot(1, 3, j + 1)
    ax.scatter(x, y)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

CSS body background image fixed to full screen even when zooming in/out

I've used these techniques before and they both work well. If you read the pros/cons of each you can decide which is right for your site.

Alternatively you could use the full size background image jQuery plugin if you want to get away from the bugs in the above.

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

Convert HH:MM:SS string to seconds only in javascript

try

time="12:12:12";
tt=time.split(":");
sec=tt[0]*3600+tt[1]*60+tt[2]*1;

Use awk to find average of a column

awk 's+=$2{print s/NR}' table | tail -1

I am using tail -1 to print the last line which should have the average number...

Does :before not work on img elements?

Here's another solution using a div container for img while using :hover::after to achieve the effect.

The HTML as follows:

<div id=img_container><img src='' style='height:300px; width:300px;'></img></div>

The CSS as follows:

#img_container { 
    margin:0; 
    position:relative; 
} 

#img_container:hover::after { 
    content:''; 
    display:block; 
    position:absolute; 
    width:300px; 
    height:300px; 
    background:url(''); 
    z-index:1; 
    top:0;
} 

To see it in action, check out the fiddle I've created. Just so you know this is cross browser friendly and there's no need to trick the code with 'fake content'.

Creating a LinkedList class from scratch

Linked List Program with following functionalities

1 Insert At Start
2 Insert At End
3 Insert At any Position
4 Delete At any Position
5 Display 
6 Get Size
7 Empty Status
8 Replace data at given postion
9 Search Element by position
10 Delete a Node by Given Data
11 Search Element Iteratively
12 Search Element Recursively




 package com.elegant.ds.linkedlist.practice;

import java.util.Scanner;

class Node {

    Node link = null;
    int data = 0;

    public Node() {
        link = null;
        data = 0;
    }

    public Node(int data, Node link) {
        this.data = data;
        this.link = null;
    }

    public Node getLink() {
        return link;
    }

    public void setLink(Node link) {
        this.link = link;
    }

    public int getData() {
        return data;
    }

    public void setData(int data) {
        this.data = data;
    }

}

class SinglyLinkedListImpl {

    Node start = null;
    Node end = null;
    int size = 0;

    public SinglyLinkedListImpl() {
        start = null;
        end = null;
        size = 0;
    }

    public void insertAtStart(int data) {
        Node nptr = new Node(data, null);
        if (start == null) {
            start = nptr;
            end = start;
        } else {
            nptr.setLink(start);
            start = nptr;
        }
        size++;
    }

    public void insertAtEnd(int data) {
        Node nptr = new Node(data, null);
        if (start == null) {
            start = nptr;
            end = nptr;
        } else {
            end.setLink(nptr);
            end = nptr;
        }
        size++;
    }

    public void insertAtPosition(int position, int data) {
        Node nptr = new Node(data, null);
        Node ptr = start;
        position = position - 1;
        for (int i = 1; i < size; i++) {
            if (i == position) {
                Node temp = ptr.getLink();
                ptr.setLink(nptr);
                nptr.setLink(temp);
                break;
            }
            ptr = ptr.getLink();
        }
        size++;
    }

    public void repleaceDataAtPosition(int position, int data) {
        if (start == null) {
            System.out.println("Empty!");
            return;
        }

        Node ptr = start;
        for (int i = 1; i < size; i++) {
            if (i == position) {
                ptr.setData(data);
            }
            ptr = ptr.getLink();
        }
    }

    public void deleteAtPosition(int position) {
        if (start == null) {
            System.out.println("Empty!");
            return;
        }

        if (position == size) {
            Node startPtr = start;
            Node endPtr = start;
            while (startPtr != null) {
                endPtr = startPtr;
                startPtr = startPtr.getLink();
            }
            end = endPtr;
            end.setLink(null);
            size--;
            return;
        }

        Node ptr = start;
        position = position - 1;
        for (int i = 1; i < size; i++) {

            if (i == position) {
                Node temp = ptr.getLink();
                temp = temp.getLink();
                ptr.setLink(temp);
                break;
            }
            ptr = ptr.getLink();
        }
        size--;
    }

    public void deleteNodeByGivenData(int data) {
        if (start == null) {
            System.out.println("Empty!");
            return;
        }

        if (start.getData() == data && start.getLink() == null) {
            start = null;
            end = null;
            size--;
            return;
        }

        if (start.getData() == data && start.getLink() != null) {
            start = start.getLink();
            size--;
            return;
        }

        if (end.getData() == data) {
            Node startPtr = start;
            Node endPtr = start;

            startPtr = startPtr.getLink();
            while (startPtr.getLink() != null) {
                endPtr = startPtr;
                startPtr = startPtr.getLink();
            }
            end = endPtr;
            end.setLink(null);
            size--;
            return;
        }

        Node startPtr = start;
        Node prevLink = startPtr;
        startPtr = startPtr.getLink();
        while (startPtr.getData() != data && startPtr.getLink() != null) {
            prevLink = startPtr;
            startPtr = startPtr.getLink();
        }
        if (startPtr.getData() == data) {
            Node temp = prevLink.getLink();
            temp = temp.getLink();
            prevLink.setLink(temp);
            size--;
            return;
        }

        System.out.println(data + " not found!");
    }

    public void disply() {
        if (start == null) {
            System.out.println("Empty!");
            return;
        }

        if (start.getLink() == null) {
            System.out.println(start.getData());
            return;
        }

        Node ptr = start;
        System.out.print(ptr.getData() + "->");
        ptr = start.getLink();
        while (ptr.getLink() != null) {
            System.out.print(ptr.getData() + "->");
            ptr = ptr.getLink();
        }
        System.out.println(ptr.getData() + "\n");
    }

    public void searchElementByPosition(int position) {
        if (position == 1) {
            System.out.println("Element at " + position + " is : " + start.getData());
            return;
        }

        if (position == size) {
            System.out.println("Element at " + position + " is : " + end.getData());
            return;
        }

        Node ptr = start;
        for (int i = 1; i < size; i++) {
            if (i == position) {
                System.out.println("Element at " + position + " is : " + ptr.getData());
                break;
            }
            ptr = ptr.getLink();
        }
    }

    public void searchElementIteratively(int data) {

        if (isEmpty()) {
            System.out.println("Empty!");
            return;
        }

        if (start.getData() == data) {
            System.out.println(data + " found at " + 1 + " position");
            return;
        }

        if (start.getLink() != null && end.getData() == data) {
            System.out.println(data + " found at " + size + " position");
            return;
        }

        Node startPtr = start;
        int position = 0;
        while (startPtr.getLink() != null) {
            ++position;
            if (startPtr.getData() == data) {
                break;
            }
            startPtr = startPtr.getLink();
        }
        if (startPtr.getData() == data) {
            System.out.println(data + " found at " + position);
            return;
        }

        System.out.println(data + " No found!");
    }

    public void searchElementRecursively(Node start, int data, int count) {

        if (isEmpty()) {
            System.out.println("Empty!");
            return;
        }
        if (start.getData() == data) {
            System.out.println(data + " found at " + (++count));
            return;
        }
        if (start.getLink() == null) {
            System.out.println(data + " not found!");
            return;
        }
        searchElementRecursively(start.getLink(), data, ++count);
    }

    public int getSize() {
        return size;
    }

    public boolean isEmpty() {
        return start == null;
    }
}

public class SinglyLinkedList {

    @SuppressWarnings("resource")
    public static void main(String[] args) {
        SinglyLinkedListImpl listImpl = new SinglyLinkedListImpl();
        System.out.println("Singly Linked list : ");
        boolean yes = true;
        do {
            System.out.println("1 Insert At Start :");
            System.out.println("2 Insert At End :");
            System.out.println("3 Insert At any Position :");
            System.out.println("4 Delete At any Position :");
            System.out.println("5 Display :");
            System.out.println("6 Get Size");
            System.out.println("7 Empty Status");
            System.out.println("8 Replace data at given postion");
            System.out.println("9 Search Element by position ");
            System.out.println("10 Delete a Node by Given Data");
            System.out.println("11 Search Element Iteratively");
            System.out.println("12 Search Element Recursively");
            System.out.println("13 Exit :");
            Scanner scanner = new Scanner(System.in);
            int choice = scanner.nextInt();
            switch (choice) {
            case 1:
                listImpl.insertAtStart(scanner.nextInt());
                break;

            case 2:
                listImpl.insertAtEnd(scanner.nextInt());
                break;

            case 3:
                int position = scanner.nextInt();
                if (position <= 1 || position > listImpl.getSize()) {
                    System.out.println("invalid position!");
                } else {
                    listImpl.insertAtPosition(position, scanner.nextInt());
                }
                break;

            case 4:
                int deletePosition = scanner.nextInt();
                if (deletePosition <= 1 || deletePosition > listImpl.getSize()) {
                    System.out.println("invalid position!");
                } else {
                    listImpl.deleteAtPosition(deletePosition);
                }
                break;

            case 5:
                listImpl.disply();
                break;

            case 6:
                System.out.println(listImpl.getSize());
                break;

            case 7:
                System.out.println(listImpl.isEmpty());
                break;

            case 8:
                int replacePosition = scanner.nextInt();
                if (replacePosition < 1 || replacePosition > listImpl.getSize()) {
                    System.out.println("Invalid position!");
                } else {
                    listImpl.repleaceDataAtPosition(replacePosition, scanner.nextInt());
                }
                break;

            case 9:
                int searchPosition = scanner.nextInt();
                if (searchPosition < 1 || searchPosition > listImpl.getSize()) {
                    System.out.println("Invalid position!");
                } else {
                    listImpl.searchElementByPosition(searchPosition);
                }
                break;

            case 10:
                listImpl.deleteNodeByGivenData(scanner.nextInt());
                break;

            case 11:
                listImpl.searchElementIteratively(scanner.nextInt());
                break;

            case 12:
                listImpl.searchElementRecursively(listImpl.start, scanner.nextInt(), 0);
                break;

            default:
                System.out.println("invalid choice");
                break;
            }
        } while (yes);
    }
}

It will help you in linked list.

How to display (print) vector in Matlab?

You might try this way:

fprintf('%s: (%i,%i,%i)\r\n','Answer',1,2,3)

I hope this helps.

How to generate a Dockerfile from an image?

How to generate or reverse a Dockerfile from an image?

You can.

alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm alpine/dfimage"
dfimage -sV=1.36 nginx:latest

It will pull the target docker image automaticlaly and export Dockerfile. Parameter -sV=1.36 is not always required.

Reference: https://hub.docker.com/repository/docker/alpine/dfimage

below is the old answer, it doesn't work any more.

$ docker pull centurylink/dockerfile-from-image
$ alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm centurylink/dockerfile-from-image"
$ dfimage --help
Usage: dockerfile-from-image.rb [options] <image_id>
    -f, --full-tree                  Generate Dockerfile for all parent layers
    -h, --help                       Show this message

how to use XPath with XDocument?

you can use the example from Microsoft - for you without namespace:

using System.Xml.Linq;
using System.Xml.XPath;
var e = xdoc.XPathSelectElement("./Report/ReportInfo/Name");     

should do it

Capturing Groups From a Grep RegEx

I prefer the one line python or perl command, both often included in major linux disdribution

echo $'
<a href="http://stackoverflow.com">
</a>
<a href="http://google.com">
</a>
' |  python -c $'
import re
import sys
for i in sys.stdin:
  g=re.match(r\'.*href="(.*)"\',i);
  if g is not None:
    print g.group(1)
'

and to handle files:

ls *.txt | python -c $'
import sys
import re
for i in sys.stdin:
  i=i.strip()
  f=open(i,"r")
  for j in f:
    g=re.match(r\'.*href="(.*)"\',j);
    if g is not None:
      print g.group(1)
  f.close()
'

Count textarea characters

This code gets the maximum value from the maxlength attribute of the textarea and decreases the value as the user types.

<DEMO>

_x000D_
_x000D_
var el_t = document.getElementById('textarea');_x000D_
var length = el_t.getAttribute("maxlength");_x000D_
var el_c = document.getElementById('count');_x000D_
el_c.innerHTML = length;_x000D_
el_t.onkeyup = function () {_x000D_
  document.getElementById('count').innerHTML = (length - this.value.length);_x000D_
};
_x000D_
<textarea id="textarea" name="text"_x000D_
 maxlength="500"></textarea>_x000D_
<span id="count"></span>
_x000D_
_x000D_
_x000D_

How to check is Apache2 is stopped in Ubuntu?

You can also type "top" and look at the list of running processes.

Laravel Fluent Query Builder Join with subquery

Query with sub query in Laravel

$resortData = DB::table('resort')
        ->leftJoin('country', 'resort.country', '=', 'country.id')
        ->leftJoin('states', 'resort.state', '=', 'states.id')
        ->leftJoin('city', 'resort.city', '=', 'city.id')
        ->select('resort.*', 'country.name as country_name', 'states.name as state_name','city.name as city_name', DB::raw("(SELECT GROUP_CONCAT(amenities.name) from resort_amenities LEFT JOIN amenities on amenities.id= resort_amenities.amenities_id WHERE resort_amenities.resort_id=resort.id) as amenities_name"))->groupBy('resort.id')
        ->orderBy('resort.id', 'DESC')
       ->get();

Django Multiple Choice Field / Checkbox Select Multiple

ManyToManyField isn`t a good choice.You can use some snippets to implement MultipleChoiceField.You can be inspired by MultiSelectField with comma separated values (Field + FormField) But it has some bug in it.And you can install django-multiselectfield.This is more prefect.

Storing image in database directly or as base64 data?

I came across this really great talk by Facebook engineers about the Efficient Storage of Billions of Photos in a database

Convert normal date to unix timestamp

You could simply use the unary + operator

(+new Date('2012.08.10')/1000).toFixed(0);

http://xkr.us/articles/javascript/unary-add/ - look under Dates.

How are people unit testing with Entity Framework 6, should you bother?

It is important to test what you are expecting entity framework to do (i.e. validate your expectations). One way to do this that I have used successfully, is using moq as shown in this example (to long to copy into this answer):

https://docs.microsoft.com/en-us/ef/ef6/fundamentals/testing/mocking

However be careful... A SQL context is not guaranteed to return things in a specific order unless you have an appropriate "OrderBy" in your linq query, so its possible to write things that pass when you test using an in-memory list (linq-to-entities) but fail in your uat / live environment when (linq-to-sql) gets used.

How to convert ISO8859-15 to UTF8?

You can use ISO-8859-9 encoding:

iconv -f ISO-8859-9 Agreement.txt -t UTF-8 -o agreement.txt

How to update column value in laravel

Version 1:

// Update data of question values with $data from formulay
$Q1 = Question::find($id);
$Q1->fill($data);
$Q1->push();

Version 2:

$Q1 = Question::find($id);
$Q1->field = 'YOUR TEXT OR VALUE';
$Q1->save();

In case of answered question you can use them:

$page = Page::find($id);
$page2update = $page->where('image', $path);
$page2update->image = 'IMGVALUE';
$page2update->save();

Does JavaScript pass by reference?

In the interest of creating a simple example that uses const...

const myRef = { foo: 'bar' };
const myVal = true;

function passes(r, v) {
  r.foo = 'baz';
  v = false;
}

passes(myRef, myVal);

console.log(myRef, myVal); // Object {foo: "baz"} true

What does string::npos mean in this code?

we have to use string::size_type for the return type of the find function otherwise the comparison with string::npos might not work. size_type, which is defined by the allocator of the string, must be an unsigned integral type. The default allocator, allocator, uses type size_t as size_type. Because -1 is converted into an unsigned integral type, npos is the maximum unsigned value of its type. However, the exact value depends on the exact definition of type size_type. Unfortunately, these maximum values differ. In fact, (unsigned long)-1 differs from (unsigned short)-1 if the size of the types differs. Thus, the comparison

idx == std::string::npos

might yield false if idx has the value -1 and idx and string::npos have different types:

std::string s;
...
int idx = s.find("not found"); // assume it returns npos
if (idx == std::string::npos) { // ERROR: comparison might not work
...
}

One way to avoid this error is to check whether the search fails directly:

if (s.find("hi") == std::string::npos) {
...
}

However, often you need the index of the matching character position. Thus, another simple solution is to define your own signed value for npos:

const int NPOS = -1;

Now the comparison looks a bit different and even more convenient:

if (idx == NPOS) { // works almost always
...
}

Reading specific columns from a text file in python

f=open(file,"r")
lines=f.readlines()
result=[]
for x in lines:
    result.append(x.split(' ')[1])
f.close()

You can do the same using a list comprehension

print([x.split(' ')[1] for x in open(file).readlines()])

Docs on split()

string.split(s[, sep[, maxsplit]])

Return a list of the words of the string s. If the optional second argument sep is absent or None, the words are separated by arbitrary strings of whitespace characters (space, tab, newline, return, formfeed). If the second argument sep is present and not None, it specifies a string to be used as the word separator. The returned list will then have one more item than the number of non-overlapping occurrences of the separator in the string.

So, you can omit the space I used and do just x.split() but this will also remove tabs and newlines, be aware of that.

Is it worth using Python's re.compile?

There is one addition perk of using re.compile(), in the form of adding comments to my regex patterns using re.VERBOSE

pattern = '''
hello[ ]world    # Some info on my pattern logic. [ ] to recognize space
'''

re.search(pattern, 'hello world', re.VERBOSE)

Although this does not affect the speed of running your code, I like to do it this way as it is part of my commenting habit. I throughly dislike spending time trying to remember the logic that went behind my code 2 months down the line when I want to make modifications.

Iterate through a C++ Vector using a 'for' loop

The reason why you don't see such practice is quite subjective and cannot have a definite answer, because I have seen many of the code which uses your mentioned way rather than iterator style code.

Following can be reasons of people not considering vector.size() way of looping:

  1. Being paranoid about calling size() every time in the loop condition. However either it's a non-issue or it can be trivially fixed
  2. Preferring std::for_each() over the for loop itself
  3. Later changing the container from std::vector to other one (e.g. map, list) will also demand the change of the looping mechanism, because not every container support size() style of looping

C++11 provides a good facility to move through the containers. That is called "range based for loop" (or "enhanced for loop" in Java).

With little code you can traverse through the full (mandatory!) std::vector:

vector<int> vi;
...
for(int i : vi) 
  cout << "i = " << i << endl;

How to check if type is Boolean

BENCHMARKING:

All pretty similar...

const { performance } = require('perf_hooks');

const boolyah = true;
var t0 = 0;
var t1 = 0;
const loops = 1000000;
var results = { 1: 0, 2: 0, 3: 0, 4: 0 };

for (i = 0; i < loops; i++) {

    t0 = performance.now();
    boolyah === false || boolyah === true;
    t1 = performance.now();
    results['1'] += t1 - t0;

    t0 = performance.now();
    'boolean' === typeof boolyah;
    t1 = performance.now();
    results['2'] += t1 - t0;

    t0 = performance.now();
    !!boolyah === boolyah;
    t1 = performance.now();
    results['3'] += t1 - t0;

    t0 = performance.now();
    Boolean(boolyah) === boolyah;
    t1 = performance.now();
    results['4'] += t1 - t0;
}

console.log(results);

  // RESULTS
  // '0': 135.09559339284897,
  // '1': 136.38034391403198,
  // '2': 136.29421120882034,
  // '3': 135.1228678226471,
  // '4': 135.11531442403793

Embedding a media player in a website using HTML

Here is a solution to make an accessible audio player with valid xHTML and non-intrusive javascript thanks to W3C Web Audio API :

What to do :

  1. If the browser is able to read, then we display controls
  2. If the browser is not able to read, we just render a link to the file

First of all, we check if the browser implements Web Audio API:

if (typeof Audio === 'undefined') {
    // abort
}

Then we instanciate an Audio object:

var player = new Audio('mysong.ogg');

Then we can check if the browser is able to decode this type of file :

if(!player.canPlayType('audio/ogg')) {
    // abort
}

Or even if it can play the codec :

if(!player.canPlayType('audio/ogg; codecs="vorbis"')) {
    // abort
}

Then we can use player.play(), player.pause();

I have done a tiny JQuery plugin that I called nanodio to test this.

You can check how it works on my demo page (sorry, but text is in french :p )

Just click on a link to play, and click again to pause. If the browser can read it natively, it will. If it can't, it should download the file.

This is just a little example, but you can improve it to use any element of your page as a control button or generate ones on the fly with javascript... Whatever you want.

What's the difference between ng-model and ng-bind

If you are hesitating between using ng-bind or ng-model, try to answer these questions:


Do you only need to display data?

  • Yes: ng-bind (one-way binding)

  • No: ng-model (two-way binding)

Do you need to bind text content (and not value)?

  • Yes: ng-bind

  • No: ng-model (you should not use ng-bind where value is required)

Is your tag a HTML <input>?

  • Yes: ng-model (you cannot use ng-bind with <input> tag)

  • No: ng-bind

How to create many labels and textboxes dynamically depending on the value of an integer variable?

Suppose you have a button that when pressed sets n to 5, you could then generate labels and textboxes on your form like so.

var n = 5;
for (int i = 0; i < n; i++)
{
    //Create label
    Label label = new Label();
    label.Text = String.Format("Label {0}", i);
    //Position label on screen
    label.Left = 10;
    label.Top = (i + 1) * 20;
    //Create textbox
    TextBox textBox = new TextBox();
    //Position textbox on screen
    textBox.Left = 120;
    textBox.Top = (i + 1) * 20;
    //Add controls to form
    this.Controls.Add(label);
    this.Controls.Add(textBox);
}

This will not only add them to the form but position them decently as well.

EC2 Instance Cloning

You can use AWS API or console UI to create an AMI(Amazon Machine Image) of your running instance. You can specify to reboot the instance when create your AMI. Then you can use AWS API or console UI to launch more instances with the AMI you created.

How to repeat last command in python interpreter shell?

alt+p  
go into options tab
configure idle
Keys

look under history-previous for the command, you can change it to something you like better once here.

How to declare a variable in SQL Server and use it in the same Stored Procedure

None of the above methods worked for me so i'm posting the way i did

DELIMITER $$
CREATE PROCEDURE AddBrand()
BEGIN 

DECLARE BrandName varchar(50);
DECLARE CategoryID,BrandID  int;
SELECT BrandID = BrandID FROM tblBrand 
WHERE BrandName = BrandName;

INSERT INTO tblBrandinCategory (CategoryID, BrandID) 
       VALUES (CategoryID, BrandID);
END$$

ListAGG in SQLSERVER

This might be useful to someone also ..

i.e. For a data analyst and data profiling type of purposes ..(i.e. not grouped by) ..

Prior to the SQL*Server 2017 String_agg function existence ..

(i.e. returns just one row ..)

select distinct
SUBSTRING (
stuff(( select distinct ',' + [FieldB] from tablename order by 1 FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)') 
,1,0,'' ) 
,2,9999)
from 
    tablename 

e.g. returns comma separated values A,B

How to use JavaScript variables in jQuery selectors?

$("input").click(function(){
        var name = $(this).attr("name");
        $('input[name="' + name + '"]').hide();    
    });   

Also works with ID:

var id = $(this).attr("id");
$('input[id="' + id + '"]').hide();

when, (sometimes)

$('input#' + id).hide();

does not work, as it should.

You can even do both:

$('input[name="' + name + '"][id="' + id + '"]').hide();

How do I setup the dotenv file in Node.js?

I had a problem also with .env variables not loading and being undefined.

What I tried:

index.js:

import dotenv from 'dotenv';
dotenv.config();
import models from './models';

models.js

import Sequelize from 'sequelize';
const sequelize = new Sequelize(
    process.env.DATABASE,
    process.env.DATABASE_USER,
    process.env.DATABASE_PASSWORD,
    {
        dialect: 'postgres',
    }
);

Apparently, because of how loading the imports works in nodejs, the import of models in index.js caused that the models.js was executed before dotenv.config(). Therefore I got undefined values from process.env.

When I changed models.js to do the dotenv configuration like:

import Sequelize from 'sequelize';
import dotenv from 'dotenv';
dotenv.config();
const sequelize = new Sequelize(
    process.env.DATABASE,
    process.env.DATABASE_USER,
    process.env.DATABASE_PASSWORD,
    {
        dialect: 'postgres',
    }
);

it started to work!

How to convert List<string> to List<int>?

This may be overkill for this simple problem. But for Try-Do methods in connection with Linq, I tend to use anonymous classes for more expressive code. It is similar to the answers from Olivier Jacot-Descombes and BA TabNabber:

List<int> ints = strings
    .Select(idString => new { ParseSuccessful = Int32.TryParse(idString, out var id), Value = id })
    .Where(id => id.ParseSuccessful)
    .Select(id => id.Value)
    .ToList();

Understanding lambda in python and using it to pass multiple arguments

Why do you need to state both 'x' and 'y' before the ':'?

You could actually in some situations(when you have only one argument) do not put the x and y before ":".

>>> flist = []
>>> for i in range(3):
...     flist.append(lambda : i)

but the i in the lambda will be bound by name, so,

>>> flist[0]()
2
>>> flist[2]()
2
>>>

different from what you may want.

How Stuff and 'For Xml Path' work in SQL Server?

This article covers various ways of concatenating strings in SQL, including an improved version of your code which doesn't XML-encode the concatenated values.

SELECT ID, abc = STUFF
(
    (
        SELECT ',' + name
        FROM temp1 As T2
        -- You only want to combine rows for a single ID here:
        WHERE T2.ID = T1.ID
        ORDER BY name
        FOR XML PATH (''), TYPE
    ).value('.', 'varchar(max)')
, 1, 1, '')
FROM temp1 As T1
GROUP BY id

To understand what's happening, start with the inner query:

SELECT ',' + name
FROM temp1 As T2
WHERE T2.ID = 42 -- Pick a random ID from the table
ORDER BY name
FOR XML PATH (''), TYPE

Because you're specifying FOR XML, you'll get a single row containing an XML fragment representing all of the rows.

Because you haven't specified a column alias for the first column, each row would be wrapped in an XML element with the name specified in brackets after the FOR XML PATH. For example, if you had FOR XML PATH ('X'), you'd get an XML document that looked like:

<X>,aaa</X>
<X>,bbb</X>
...

But, since you haven't specified an element name, you just get a list of values:

,aaa,bbb,...

The .value('.', 'varchar(max)') simply retrieves the value from the resulting XML fragment, without XML-encoding any "special" characters. You now have a string that looks like:

',aaa,bbb,...'

The STUFF function then removes the leading comma, giving you a final result that looks like:

'aaa,bbb,...'

It looks quite confusing at first glance, but it does tend to perform quite well compared to some of the other options.

How to center a table of the screen (vertically and horizontally)

One way to center any element of unknown height and width both horizontally and vertically:

table {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

See Example

Alternatively, use a flex container:

.parent-element {
    display: flex;
    justify-content: center;
    align-items: center;
}

Converting int to bytes in Python 3

The documentation says:

bytes(int) -> bytes object of size given by the parameter
              initialized with null bytes

The sequence:

b'3\r\n'

It is the character '3' (decimal 51) the character '\r' (13) and '\n' (10).

Therefore, the way would treat it as such, for example:

>>> bytes([51, 13, 10])
b'3\r\n'

>>> bytes('3', 'utf8') + b'\r\n'
b'3\r\n'

>>> n = 3
>>> bytes(str(n), 'ascii') + b'\r\n'
b'3\r\n'

Tested on IPython 1.1.0 & Python 3.2.3

How to hide the keyboard when I press return key in a UITextField?

First make your file delegate for UITextField

@interface MYLoginViewController () <UITextFieldDelegate>

@end

Then add this method to your code.

- (BOOL)textFieldShouldReturn:(UITextField *)textField {        
    [textField resignFirstResponder];
    return YES;
}

Also add self.textField.delegate = self;

Running a command in a new Mac OS X Terminal window

I made a function version of Oscar's answer, this one also copies the environment and changes to the appropriate directory

function new_window {
    TMP_FILE=$(mktemp "/tmp/command.XXXXXX")
    echo "#!/usr/bin/env bash" > $TMP_FILE

    # Copy over environment (including functions), but filter out readonly stuff
    set | grep -v "\(BASH_VERSINFO\|EUID\|PPID\|SHELLOPTS\|UID\)" >> $TMP_FILE

    # Copy over exported envrionment
    export -p >> $TMP_FILE

    # Change to directory
    echo "cd $(pwd)" >> $TMP_FILE

    # Copy over target command line
    echo "$@" >> $TMP_FILE

    chmod +x "$TMP_FILE"
    open -b com.apple.terminal "$TMP_FILE"

    sleep .1 # Wait for terminal to start
    rm "$TMP_FILE"
}

You can use it like this:

new_window my command here

or

new_window ssh example.com

using OR and NOT in solr query

Putting together comments from a couple different answers here, in the Solr docs and on the other SO question, I found that the following syntax produces the correct result for my use case

(my_field=my_value or my_field is null):

(my_field:"my_value" OR (*:* NOT my_field:*))

This works for solr 4.1.0. This is slightly different than the use case in the OP; but, I thought that others would find it useful.

SCP Permission denied (publickey). on EC2 only when using -r flag on directories

The -i flag specifies the private key (.pem file) to use. If you don't specify that flag (as in your first command) it will use your default ssh key (usually under ~/.ssh/).

So in your first command, you are actually asking scp to upload the .pem file itself using your default ssh key. I don't think that is what you want.

Try instead with:

scp -r -i /Applications/XAMPP/htdocs/keypairfile.pem uploads/* ec2-user@publicdns:/var/www/html/uploads

jQuery: Can I call delay() between addClass() and such?

Try this:

function removeClassDelayed(jqObj, c, to) {    
    setTimeout(function() { jqObj.removeClass(c); }, to);
}
removeClassDelayed($("#div"), "error", 1000);

How to unstash only certain files?

First list all the stashes

git stash list

?

stash@{0}: WIP on Produktkonfigurator: 132c06a5 Cursor bei glyphicon plus und close zu zeigende Hand ändern
stash@{1}: WIP on Produktkonfigurator: 132c06a5 Cursor bei glyphicon plus und close zu zeigende Hand ändern
stash@{2}: WIP on master: 7e450c81 Merge branch 'Offlineseite'

Then show which files are in the stash (lets pick stash 1):

git stash show 1 --name-only

//Hint: you can also write
//git stash show stash@{1} --name-only

?

 ajax/product.php
 ajax/productPrice.php
 errors/Company/js/offlineMain.phtml
 errors/Company/mage.php
 errors/Company/page.phtml
 js/konfigurator/konfigurator.js

Then apply the file you like to:

git checkout stash@{1} -- <filename>

or whole folder:

git checkout stash@{1} /errors

It also works without -- but it is recommended to use them. See this post.

It is also conventional to recognize a double hyphen as a signal to stop option interpretation and treat all following arguments literally.

How to implement authenticated routes in React Router 4?

The solution which ultimately worked best for my organization is detailed below, it just adds a check on render for the sysadmin route and redirects the user to a different main path of the application if they are not allowed to be in the page.

SysAdminRoute.tsx

import React from 'react';
import { Route, Redirect, RouteProps } from 'react-router-dom';
import AuthService from '../services/AuthService';
import { appSectionPageUrls } from './appSectionPageUrls';
interface IProps extends RouteProps {}
export const SysAdminRoute = (props: IProps) => {
    var authService = new AuthService();
    if (!authService.getIsSysAdmin()) { //example
        authService.logout();
        return (<Redirect to={{
            pathname: appSectionPageUrls.site //front-facing
        }} />);
    }
    return (<Route {...props} />);
}

There are 3 main routes for our implementation, the public facing /site, the logged in client /app, and sys admin tools at /sysadmin. You get redirected based on your 'authiness' and this is the page at /sysadmin.

SysAdminNav.tsx

<Switch>
    <SysAdminRoute exact path={sysadminUrls.someSysAdminUrl} render={() => <SomeSysAdminUrl/> } />
    //etc
</Switch>

Is it possible to wait until all javascript files are loaded before executing javascript code?

Thats work for me:

var jsScripts = [];

jsScripts.push("/js/script1.js" );
jsScripts.push("/js/script2.js" );
jsScripts.push("/js/script3.js" );

$(jsScripts).each(function( index, value ) {
    $.holdReady( true );
    $.getScript( value ).done(function(script, status) {
        console.log('Loaded ' + index + ' : ' + value + ' (' + status + ')');                
        $.holdReady( false );
    });
});

Setting UILabel text to bold

Use attributed string:

// Define attributes
let labelFont = UIFont(name: "HelveticaNeue-Bold", size: 18)
let attributes :Dictionary = [NSFontAttributeName : labelFont]

// Create attributed string
var attrString = NSAttributedString(string: "Foo", attributes:attributes)
label.attributedText = attrString

You need to define attributes.

Using attributed string you can mix colors, sizes, fonts etc within one text

What is the purpose of the word 'self'?

it's an explicit reference to the class instance object.

Pass variables between two PHP pages without using a form or the URL of page

Use Sessions.

Page1:

session_start();
$_SESSION['message'] = "Some message"

Page2:

session_start();
var_dump($_SESSION['message']);

Modifying a subset of rows in a pandas dataframe

To replace multiples columns convert to numpy array using .values:

df.loc[df.A==0, ['B', 'C']] = df.loc[df.A==0, ['B', 'C']].values / 2

Trim last 3 characters of a line WITHOUT using sed, or perl, etc

Here's an old-fashioned unix trick for removing the last 3 characters from a line that makes no use of sed OR awk...

> echo 987654321 | rev | cut -c 4- | rev

987654

Unlike the earlier example using 'cut', this does not require knowledge of the line length.

The import org.apache.commons cannot be resolved in eclipse juno

If you got a Apache Maven project, it's easy to use this package in your project. Just specify it in your pom.xml:

<project>
...

    <properties>
        <version.commons-io>2.4</version.commons-io>
    </properties>

    <dependencies>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${version.commons-io}</version>
        </dependency>
    </dependencies>

...
</project>

Can we update primary key values of a table?

Primary key attributes are just as updateable as any other attributes of a table. Stability is often a desirable property of a key but definitely not an absolute requirement. If it makes sense from a business perpective to update a key then there's no fundamental reason why you shouldn't.

Appending the same string to a list of strings in Python

new_list = [word_in_list + end_string for word_in_list in old_list]

Using names such as "list" for your variable names is bad since it will overwrite/override the builtins.

XPath to select Element by attribute value

Try doing this :

/Employees/Employee[@id=4]/*/text()

Loop through an array of strings in Bash?

This is also easy to read:

FilePath=(
    "/tmp/path1/"    #FilePath[0]
    "/tmp/path2/"    #FilePath[1]
)

#Loop
for Path in "${FilePath[@]}"
do
    echo "$Path"
done

unique() for more than one variable

How about using unique() itself?

df <- data.frame(yad = c("BARBIE", "BARBIE", "BAKUGAN", "BAKUGAN"),
                 per = c("AYLIK",  "AYLIK",  "2 AYLIK", "2 AYLIK"),
                 hmm = 1:4)

df
#       yad     per hmm
# 1  BARBIE   AYLIK   1
# 2  BARBIE   AYLIK   2
# 3 BAKUGAN 2 AYLIK   3
# 4 BAKUGAN 2 AYLIK   4

unique(df[c("yad", "per")])
#       yad     per
# 1  BARBIE   AYLIK
# 3 BAKUGAN 2 AYLIK

missing private key in the distribution certificate on keychain

I lost hours and hours to resolve this issue, but it's fixed by just restarting MAC...

z-index not working with fixed positioning

Give the #under a negative z-index, e.g. -1

This happens because the z-index property is ignored in position: static;, which happens to be the default value; so in the CSS code you wrote, z-index is 1 for both elements no matter how high you set it in #over.

By giving #under a negative value, it will be behind any z-index: 1; element, i.e. #over.

Whether a variable is undefined

function my_url (base, opt)
{
    var retval = ["" + base];
    retval.push( opt.page_name ? "&page_name=" + opt.page_name : "");
    retval.push( opt.table_name ? "&table_name=" + opt.table_name : "");
    retval.push( opt.optionResult ? "&optionResult=" + opt.optionResult : "");
    return retval.join("");
}

my_url("?z=z",  { page_name : "pageX" /* no table_name and optionResult */ } );

/* Returns:
     ?z=z&page_name=pageX
*/

This avoids using typeof whatever === "undefined". (Also, there isn't any string concatenation.)

Why do people write #!/usr/bin/env python on the first line of a Python script?

It allows you to select the executable that you wish to use; which is very handy if perhaps you have multiple python installs, and different modules in each and wish to choose. e.g.

#!/bin/sh
#
# Choose the python we need. Explanation:
# a) '''\' translates to \ in shell, and starts a python multi-line string
# b) "" strings are treated as string concat by python, shell ignores them
# c) "true" command ignores its arguments
# c) exit before the ending ''' so the shell reads no further
# d) reset set docstrings to ignore the multiline comment code
#
"true" '''\'
PREFERRED_PYTHON=/Library/Frameworks/Python.framework/Versions/2.7/bin/python
ALTERNATIVE_PYTHON=/Library/Frameworks/Python.framework/Versions/3.6/bin/python3
FALLBACK_PYTHON=python3

if [ -x $PREFERRED_PYTHON ]; then
    echo Using preferred python $ALTERNATIVE_PYTHON
    exec $PREFERRED_PYTHON "$0" "$@"
elif [ -x $ALTERNATIVE_PYTHON ]; then
    echo Using alternative python $ALTERNATIVE_PYTHON
    exec $ALTERNATIVE_PYTHON "$0" "$@"
else
    echo Using fallback python $FALLBACK_PYTHON
    exec python3 "$0" "$@"
fi
exit 127
'''

__doc__ = """What this file does"""
print(__doc__)
import platform
print(platform.python_version())

How to read a large file line by line?

Best way to read large file, line by line is to use python enumerate function

with open(file_name, "rU") as read_file:
    for i, row in enumerate(read_file, 1):
        #do something
        #i in line of that line
        #row containts all data of that line

SQL Server IN vs. EXISTS Performance

The execution plans are typically going to be identical in these cases, but until you see how the optimizer factors in all the other aspects of indexes etc., you really will never know.

How do you change the width and height of Twitter Bootstrap's tooltips?

Just override bootstrap.css

The default value in BS2 is max-width:200px; So you can increase it with whatever fits your needs.

.tooltip-inner {
    max-width: 350px;
    /* If max-width does not work, try using width instead */
    width: 350px; 
}

Dynamically Changing log4j log level

I have used this method with success to reduce the verbosity of the "org.apache.http" logs:

ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory.getLogger("org.apache.http");
logger.setLevel(Level.TRACE);
logger.setAdditive(false);

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

Scanner scanner = new Scanner(System.in);
String str = scanner.next();
str += scanner.readLine();

String str = scanner.next(); ===> it fetch the 1st word of the line (hello world!! => "hello") str += scanner.nextLine(); ===> This method returns the rest of the current line, excluding any line separator at the end. (hello world!! => " world!!")

Align labels in form next to input

You can also try using flex-box

<head><style>
body {
    color:white;
    font-family:arial;
    font-size:1.2em;
}
form {
    margin:0 auto;
    padding:20px;
    background:#444;
}
.input-group {
    margin-top:10px;
    width:60%;
    display:flex;
    justify-content:space-between;
    flex-wrap:wrap;
}
label, input {
    flex-basis:100px;
}
</style></head>
<body>

<form>
    <div class="wrapper">
        <div class="input-group">
            <label for="user_name">name:</label>
            <input type="text" id="user_name">
        </div>
        <div class="input-group">
            <label for="user_pass">Password:</label>
            <input type="password" id="user_pass">
        </div>
    </div>
</form>

</body>
</html>

How to check all versions of python installed on osx and centos

compgen -c python | grep -P '^python\d'

This lists some other python things too, But hey, You can identify all python versions among them.

How to fix missing dependency warning when using useEffect React Hook?

just disable eslint for the next line;

useEffect(() => {
   fetchBusinesses();
// eslint-disable-next-line
}, []);

in this way you are using it just like a component did mount (called once)

updated

or

const fetchBusinesses = useCallback(() => {
 // your logic in here
 }, [someDeps])

useEffect(() => {
   fetchBusinesses();
// no need to skip eslint warning
}, [fetchBusinesses]); 

fetchBusinesses will be called everytime someDeps will change

includes() not working in all browsers

import 'core-js/es7/array' 

into polyfill.ts worked for me.

How do I make a composite key with SQL Server Management Studio?

here is some code to do it:

-- Sample Table
create table myTable 
(
    Column1 int not null,
    Column2 int not null
)
GO

-- Add Constraint
ALTER TABLE myTable
    ADD CONSTRAINT pk_myConstraint PRIMARY KEY (Column1,Column2)
GO

I added the constraint as a separate statement because I presume your table has already been created.

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

Even though utf8_decode is a useful solution, I prefer to correct the encoding errors on the table itself. In my opinion it is better to correct the bad characters themselves than making "hacks" in the code. Simply do a replace on the field on the table. To correct the bad encoded characters from OP :

update <table> set <field> = replace(<field>, "ë", "ë")
update <table> set <field> = replace(<field>, "Ã", "à")
update <table> set <field> = replace(<field>, "ì", "ì")
update <table> set <field> = replace(<field>, "ù", "ù")

Where <table> is the name of the mysql table and <field> is the name of the column in the table. Here is a very good check-list for those typically bad encoded windows-1252 to utf-8 characters -> Debugging Chart Mapping Windows-1252 Characters to UTF-8 Bytes to Latin-1 Characters.

Remember to backup your table before trying to replace any characters with SQL!

[I know this is an answer to a very old question, but was facing the issue once again. Some old windows machine didnt encoded the text correct before inserting it to the utf8_general_ci collated table.]

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

you can use the return statement without any parameter to exit a function

def foo(element):
    do something
    if check is true:
        do more (because check was succesful)
    else:
        return
    do much much more...

or raise an exception if you want to be informed of the problem

def foo(element):
    do something
    if check is true:
        do more (because check was succesful)
    else:
        raise Exception("cause of the problem")
    do much much more...

Authenticate with GitHub using a token

By having struggling so many hours on applying GitHub token finally it works as below:

$ cf_export GITHUB_TOKEN=$(codefresh get context github --decrypt -o yaml | yq -y .spec.data.auth.password)

  • code follows Codefresh guidance on cloning a repo using token (freestyle}
  • test carried: sed %d%H%M on match word '-123456-whatever'
  • push back to the repo (which is private repo)
  • triggered by DockerHub webhooks

Following is the complete code:

version: '1.0'
steps:
  get_git_token:
    title: Reading Github token
    image: codefresh/cli
    commands:
      - cf_export GITHUB_TOKEN=$(codefresh get context github --decrypt -o yaml | yq -y .spec.data.auth.password)
  main_clone:
    title: Updating the repo
    image: alpine/git:latest
    commands:
      - git clone https://chetabahana:[email protected]/chetabahana/compose.git
      - cd compose && git remote rm origin
      - git config --global user.name "chetabahana"
      - git config --global user.email "[email protected]"
      - git remote add origin https://chetabahana:[email protected]/chetabahana/compose.git
      - sed -i "s/-[0-9]\{1,\}-\([a-zA-Z0-9_]*\)'/-`date +%d%H%M`-whatever'/g" cloudbuild.yaml
      - git status && git add . && git commit -m "fresh commit" && git push -u origin master

Output...

On branch master 
Changes not staged for commit: 
  (use "git add ..." to update what will be committed) 
  (use "git checkout -- ..." to discard changes in working directory) 

modified:   cloudbuild.yaml 

no changes added to commit (use "git add" and/or "git commit -a") 
[master dbab20f] fresh commit 
 1 file changed, 1 insertion(+), 1 deletion(-) 
Enumerating objects: 5, done. 
Counting objects:  20% (1/5) ...  Counting objects: 100% (5/5), done. 
Delta compression using up to 4 threads 
Compressing objects:  33% (1/3) ... Writing objects: 100% (3/3), 283 bytes | 283.00 KiB/s, done. 
Total 3 (delta 2), reused 0 (delta 0) 
remote: Resolving deltas:   0% (0/2)  ...   (2/2), completed with 2 local objects. 
To https://github.com/chetabahana/compose.git 
   bbb6d2f..dbab20f  master -> master 
Branch 'master' set up to track remote branch 'master' from 'origin'. 
Reading environment variable exporting file contents. 
Successfully ran freestyle step: Cloning the repo 

SQL Server IIF vs CASE

IIF is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.

CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.

call a function in success of datatable ajax call

This works fine for me. Another way don't work good

                'ajax': {
                    complete: function (data) {
                        console.log(data['responseJSON']);
                    },
                    'url': 'xxx.php',
                },

How to upload and parse a CSV file in php

function doParseCSVFile($filesArray)
    {
        if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) { 

            $strFilePath = $filesArray['frmUpload']['tmp_name']; 

            $strFileHandle = fopen($strFilePath,"r");
            $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 
            $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 

            do { 
                if ($line_of_text[0]) { 
                    $strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
                    ExecuteQry($strInsertSql);
                }               
            } while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);

        } else {
            return FALSE;
        }
    }

How to update Git clone

git pull origin master

this will sync your master to the central repo and if new branches are pushed to the central repo it will also update your clone copy.

C# Foreach statement does not contain public definition for GetEnumerator

You should implement the IEnumerable interface (CarBootSaleList should impl it in your case).

http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator.aspx

But it is usually easier to subclass System.Collections.ObjectModel.Collection and friends

http://msdn.microsoft.com/en-us/library/system.collections.objectmodel.aspx

Your code also seems a bit strange, like you are nesting lists?

How do I select the parent form based on which submit button is clicked?

You can select the form like this:

$("#submit").click(function(){
    var form = $(this).parents('form:first');
    ...
});

However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

To select fields inside the form, use the form context. For example:

$("input[name='somename']",form).val();

Is it possible to get the current spark context settings in PySpark?

For a complete overview of your Spark environment and configuration I found the following code snippets useful:

SparkContext:

for item in sorted(sc._conf.getAll()): print(item)

Hadoop Configuration:

hadoopConf = {}
iterator = sc._jsc.hadoopConfiguration().iterator()
while iterator.hasNext():
    prop = iterator.next()
    hadoopConf[prop.getKey()] = prop.getValue()
for item in sorted(hadoopConf.items()): print(item)

Environment variables:

import os
for item in sorted(os.environ.items()): print(item)

Setting selection to Nothing when programming Excel

Cells(1,1).Select

It will take you to cell A1, thereby canceling your existing selection.

Bootstrap 3 truncate long text inside rows of a table in a responsive way

You need to use table-layout:fixed in order for CSS ellipsis to work on the table cells.

.table {
  table-layout:fixed;
}

.table td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

demo: http://bootply.com/9njmoY2CmS

"Initializing" variables in python?

You are asking to initialize four variables using a single float object, which of course is not iterable. You can do -

  1. grade_1, grade_2, grade_3, grade_4 = [0.0 for _ in range(4)]
  2. grade_1 = grade_2 = grade_3 = grade_4 = 0.0

Unless you want to initialize them with different values of course.

Change values on matplotlib imshow() graph axis

I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.

Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.

Here is an attempt at this with your data:

import matplotlib.pyplot as plt

# ... define 2D array hist as you did

plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case

Sass nth-child nesting

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
      }
    }
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      }
      &.last {
        &:nth-child(-2n+4){
          background-color: $bg;
        }
      }
    }
  }
}

and here is a quick demo: http://codepen.io/anon/pen/BEImD

----EDIT----

Here's another approach to avoid retyping background-color:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  }
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;
      }
    }

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      }
      &.last {
        &:nth-child(-2n+4){
          @extend %highlight;
        }
      }
    }
  }
}

Comparing two joda DateTime instances

This code (example) :

    Chronology ch1 = GregorianChronology.getInstance();     Chronology ch2 = ISOChronology.getInstance();      DateTime dt = new DateTime("2013-12-31T22:59:21+01:00",ch1);     DateTime dt2 = new DateTime("2013-12-31T22:59:21+01:00",ch2);      System.out.println(dt);     System.out.println(dt2);      boolean b = dt.equals(dt2);      System.out.println(b); 

Will print :

2013-12-31T16:59:21.000-05:00 2013-12-31T16:59:21.000-05:00 false 

You are probably comparing two DateTimes with same date but different Chronology.

jQuery How do you get an image to fade in on load?

You have a syntax error on line 5:

$('#logo').hide();.fadeIn(3000);

Should be:

$('#logo').hide().fadeIn(3000);

Make docker use IPv4 for port binding

As @daniel-t points out in the comment: github.com/docker/docker/issues/2174 is about showing binding only to IPv6 in netstat, but that is not an issue. As that github issues states:

When setting up the proxy, Docker requests the loopback address '127.0.0.1', Linux realises this is an address that exists in IPv6 (as ::0) and opens on both (but it is formally an IPv6 socket). When you run netstat it sees this and tells you it is an IPv6 - but it is still listening on IPv4. If you have played with your settings a little, you may have disabled this trick Linux does - by setting net.ipv6.bindv6only = 1.

In other words, just because you see it as IPv6 only, it is still able to communicate on IPv4 unless you have IPv6 set to only bind on IPv6 with the net.ipv6.bindv6only setting. To be clear, net.ipv6.bindv6only should be 0 - you can run sysctl net.ipv6.bindv6only to verify.

Disable all Database related auto configuration in Spring Boot

There's a way to exclude specific auto-configuration classes using @SpringBootApplication annotation.

@Import(MyPersistenceConfiguration.class)
@SpringBootApplication(exclude = {
        DataSourceAutoConfiguration.class, 
        DataSourceTransactionManagerAutoConfiguration.class,
        HibernateJpaAutoConfiguration.class})
public class MySpringBootApplication {         
    public static void main(String[] args) {
        SpringApplication.run(MySpringBootApplication.class, args);
    }
}

@SpringBootApplication#exclude attribute is an alias for @EnableAutoConfiguration#exclude attribute and I find it rather handy and useful.
I added @Import(MyPersistenceConfiguration.class) to the example to demonstrate how you can apply your custom database configuration.

Rails Active Record find(:all, :order => ) issue

Make sure to check the schema at the database level directly. I've gotten burned by this before, where, for example, a migration was initially written to create a :datetime column, and I ran it locally, then tweaked the migration to a :date before actually deploying. Thus everyone's database looks good except for mine, and the bugs are subtle.

How to print a dictionary's key?

A dictionary has, by definition, an arbitrary number of keys. There is no "the key". You have the keys() method, which gives you a python list of all the keys, and you have the iteritems() method, which returns key-value pairs, so

for key, value in mydic.iteritems() :
    print key, value

Python 3 version:

for key, value in mydic.items() :
    print (key, value)

So you have a handle on the keys, but they only really mean sense if coupled to a value. I hope I have understood your question.