Programs & Examples On #Operations research

Operations Research is the application of quantitative techniques to decision making, typically involving mathematical optimization. Problems include dynamic programming, linear programming and Integer programming & discrete optimization.

Exit a Script On Error

If you put set -e in a script, the script will terminate as soon as any command inside it fails (i.e. as soon as any command returns a nonzero status). This doesn't let you write your own message, but often the failing command's own messages are enough.

The advantage of this approach is that it's automatic: you don't run the risk of forgetting to deal with an error case.

Commands whose status is tested by a conditional (such as if, && or ||) do not terminate the script (otherwise the conditional would be pointless). An idiom for the occasional command whose failure doesn't matter is command-that-may-fail || true. You can also turn set -e off for a part of the script with set +e.

What does servletcontext.getRealPath("/") mean and when should I use it

A web application's context path is the directory that contains the web application's WEB-INF directory. It can be thought of as the 'home' of the web app. Often, when writing web applications, it can be important to get the actual location of this directory in the file system, since this allows you to do things such as read from files or write to files.

This location can be obtained via the ServletContext object's getRealPath() method. This method can be passed a String parameter set to File.separator to get the path using the operating system's file separator ("/" for UNIX, "\" for Windows).

What is the color code for transparency in CSS?

There is no transparency component of the color hex string. There is opacity, which is a float from 0.0 to 1.0.

Responsive bootstrap 3 timepicker?

Kendo UI provides the best and ultimate collection of JavaScript UI components with libraries for jQuery, Angular, React, and Vue. You can quickly build eye-catching, high-performance, responsive web applications regardless of your JavaScript framework choice. Here is a timepicker UI component from them:

Also below is an alternate and a simple solution

<!--Css-->
<link href="css/timepicker.css" type="text/css" rel="stylesheet" />

<!--Html-->
<div class="row">
    <div class="col">
        <label class="label-in">Time</label>
        <input class="timepicker" id="event-time" type="text" value="" required="">
    </div>
</div>

<!--Script-->
<script src="Scripts/ClockPicker.js"></script>
<script>
   $('.timepicker').timepicker({
     });
</script>

Here is yet another popular framework Bootstrap Time Picker from mdbootstrap

What is /var/www/html?

/var/www/html is just the default root folder of the web server. You can change that to be whatever folder you want by editing your apache.conf file (usually located in /etc/apache/conf) and changing the DocumentRoot attribute (see http://httpd.apache.org/docs/current/mod/core.html#documentroot for info on that)

Many hosts don't let you change these things yourself, so your mileage may vary. Some let you change them, but only with the built in admin tools (cPanel, for example) instead of via a command line or editing the raw config files.

TypeError: unhashable type: 'numpy.ndarray'

Your variable energies probably has the wrong shape:

>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'

And that's what happens if you read columnar data using your approach:

>>> data
array([[  1.,   2.,   3.],
       [  3.,   4.,   5.],
       [  5.,   6.,   7.],
       [  8.,   9.,  10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
       [ 3.],
       [ 5.],
       [ 8.]])

Probably you can simply use

>>> data[:,0]
array([ 1.,  3.,  5.,  8.])

instead.

(P.S. Your code looks like it's undecided about whether it's data or elementdata. I've assumed it's simply a typo.)

How do I create a Bash alias?

On OS X you want to use ~/.bash_profile. This is because by default Terminal.app opens a login shell for each new window.

See more about the different configuration files and when they are used here: What's the difference between .bashrc, .bash_profile, and .environment?

and in relation to OSX here: About .bash_profile, .bashrc, and where should alias be written in?

JOptionPane - input dialog box program

After that you have to parse the results. Suppose results are in integers, then

int testint1 = Integer.parse(test1);

Similarly others should be parsed. Now the results should be checked for two higher marks in them, by using if statement After that take out the average.

How to completely uninstall Visual Studio 2010?

Download and install IOBIT uninstaller: http://www.iobit.com/advanceduninstaller.php, find the date in which you install Visual Studio and select all programas from that date r elated to VS. Then run de batch uninstaller. It is not a fully automated solution but it is a lot quicker than going one by one int he add / remove programs in Windows. It even has a power scan to clean the registry.

Breaking out of a nested loop

Since I first saw break in C a couple of decades back, this problem has vexed me. I was hoping some language enhancement would have an extension to break which would work thus:

break; // our trusty friend, breaks out of current looping construct.
break 2; // breaks out of the current and it's parent looping construct.
break 3; // breaks out of 3 looping constructs.
break all; // totally decimates any looping constructs in force.

Program to find prime numbers

It may just be my opinion, but there's another serious error in your program (setting aside the given 'prime number' question, which has been thoroughly answered).

Like the rest of the responders, I'm assuming this is homework, which indicates you want to become a developer (presumably).

You need to learn to compartmentalize your code. It's not something you'll always need to do in a project, but it's good to know how to do it.

Your method prime_num(long num) could stand a better, more descriptive name. And if it is supposed to find all prime numbers less than a given number, it should return them as a list. This makes it easier to seperate your display and your functionality.

If it simply returned an IList containing prime numbers you could then display them in your main function (perhaps calling another outside function to pretty print them) or use them in further calculations down the line.

So my best recommendation to you is to do something like this:

public void main(string args[])
{
    //Get the number you want to use as input
    long x = number;//'number' can be hard coded or retrieved from ReadLine() or from the given arguments

    IList<long> primes = FindSmallerPrimes(number);

    DisplayPrimes(primes);
}

public IList<long> FindSmallerPrimes(long largestNumber)
{
    List<long> returnList = new List<long>();
    //Find the primes, using a method as described by another answer, add them to returnList
    return returnList;
}

public void DisplayPrimes(IList<long> primes)
{
    foreach(long l in primes)
    {
        Console.WriteLine ( "Prime:" + l.ToString() );
    }
}

Even if you end up working somewhere where speration like this isn't needed, it's good to know how to do it.

Negative matching using grep (match lines that do not contain foo)

grep -v is your friend:

grep --help | grep invert  

-v, --invert-match select non-matching lines

Also check out the related -L (the complement of -l).

-L, --files-without-match only print FILE names containing no match

Returning http status code from Web Api controller

Try this :

return new ContentResult() { 
    StatusCode = 404, 
    Content = "Not found" 
};

Plotting a fast Fourier transform in Python

I write this additional answer to explain the origins of the diffusion of the spikes when using FFT and especially discuss the scipy.fftpack tutorial with which I disagree at some point.

In this example, the recording time tmax=N*T=0.75. The signal is sin(50*2*pi*x) + 0.5*sin(80*2*pi*x). The frequency signal should contain two spikes at frequencies 50 and 80 with amplitudes 1 and 0.5. However, if the analysed signal does not have a integer number of periods diffusion can appear due to the truncation of the signal:

  • Pike 1: 50*tmax=37.5 => frequency 50 is not a multiple of 1/tmax => Presence of diffusion due to signal truncation at this frequency.
  • Pike 2: 80*tmax=60 => frequency 80 is a multiple of 1/tmax => No diffusion due to signal truncation at this frequency.

Here is a code that analyses the same signal as in the tutorial (sin(50*2*pi*x) + 0.5*sin(80*2*pi*x)), but with the slight differences:

  1. The original scipy.fftpack example.
  2. The original scipy.fftpack example with an integer number of signal periods (tmax=1.0 instead of 0.75 to avoid truncation diffusion).
  3. The original scipy.fftpack example with an integer number of signal periods and where the dates and frequencies are taken from the FFT theory.

The code:

import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack

# 1. Linspace
N = 600
# Sample spacing
tmax = 3/4
T = tmax / N # =1.0 / 800.0
x1 = np.linspace(0.0, N*T, N)
y1 = np.sin(50.0 * 2.0*np.pi*x1) + 0.5*np.sin(80.0 * 2.0*np.pi*x1)
yf1 = scipy.fftpack.fft(y1)
xf1 = np.linspace(0.0, 1.0/(2.0*T), N//2)

# 2. Integer number of periods
tmax = 1
T = tmax / N # Sample spacing
x2 = np.linspace(0.0, N*T, N)
y2 = np.sin(50.0 * 2.0*np.pi*x2) + 0.5*np.sin(80.0 * 2.0*np.pi*x2)
yf2 = scipy.fftpack.fft(y2)
xf2 = np.linspace(0.0, 1.0/(2.0*T), N//2)

# 3. Correct positioning of dates relatively to FFT theory ('arange' instead of 'linspace')
tmax = 1
T = tmax / N # Sample spacing
x3 = T * np.arange(N)
y3 = np.sin(50.0 * 2.0*np.pi*x3) + 0.5*np.sin(80.0 * 2.0*np.pi*x3)
yf3 = scipy.fftpack.fft(y3)
xf3 = 1/(N*T) * np.arange(N)[:N//2]

fig, ax = plt.subplots()
# Plotting only the left part of the spectrum to not show aliasing
ax.plot(xf1, 2.0/N * np.abs(yf1[:N//2]), label='fftpack tutorial')
ax.plot(xf2, 2.0/N * np.abs(yf2[:N//2]), label='Integer number of periods')
ax.plot(xf3, 2.0/N * np.abs(yf3[:N//2]), label='Correct positioning of dates')
plt.legend()
plt.grid()
plt.show()

Output:

As it can be here, even with using an integer number of periods some diffusion still remains. This behaviour is due to a bad positioning of dates and frequencies in the scipy.fftpack tutorial. Hence, in the theory of discrete Fourier transforms:

  • the signal should be evaluated at dates t=0,T,...,(N-1)*T where T is the sampling period and the total duration of the signal is tmax=N*T. Note that we stop at tmax-T.
  • the associated frequencies are f=0,df,...,(N-1)*df where df=1/tmax=1/(N*T) is the sampling frequency. All harmonics of the signal should be multiple of the sampling frequency to avoid diffusion.

In the example above, you can see that the use of arange instead of linspace enables to avoid additional diffusion in the frequency spectrum. Moreover, using the linspace version also leads to an offset of the spikes that are located at slightly higher frequencies than what they should be as it can be seen in the first picture where the spikes are a little bit at the right of the frequencies 50 and 80.

I'll just conclude that the example of usage should be replace by the following code (which is less misleading in my opinion):

import numpy as np
from scipy.fftpack import fft

# Number of sample points
N = 600
T = 1.0 / 800.0
x = T*np.arange(N)
y = np.sin(50.0 * 2.0*np.pi*x) + 0.5*np.sin(80.0 * 2.0*np.pi*x)
yf = fft(y)
xf = 1/(N*T)*np.arange(N//2)
import matplotlib.pyplot as plt
plt.plot(xf, 2.0/N * np.abs(yf[0:N//2]))
plt.grid()
plt.show()

Output (the second spike is not diffused anymore):

I think this answer still bring some additional explanations on how to apply correctly discrete Fourier transform. Obviously, my answer is too long and there is always additional things to say (ewerlopes talked briefly about aliasing for instance and a lot can be said about windowing), so I'll stop.

I think that it is very important to understand deeply the principles of discrete Fourier transform when applying it because we all know so much people adding factors here and there when applying it in order to obtain what they want.

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

There is a new spec called the Native File System API that allows you to do this properly like this:

const result = await window.chooseFileSystemEntries({ type: "save-file" });

There is a demo here, but I believe it is using an origin trial so it may not work in your own website unless you sign up or enable a config flag, and it obviously only works in Chrome. If you're making an Electron app this might be an option though.

Convert Uri to String and String to Uri

I need to know way for converting uri to string and string to uri.

Use toString() to convert a Uri to a String. Use Uri.parse() to convert a String to a Uri.

this code doesn't work

That is not a valid string representation of a Uri. A Uri has a scheme, and "/external/images/media/470939" does not have a scheme.

Remove characters from NSString?

If you want to support more than one space at a time, or support any whitespace, you can do this:

NSString* noSpaces =
    [[myString componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]]
                           componentsJoinedByString:@""];

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

In my case I faced this issue in my simulator because my computer's date was behind of current date. So do check this case too when you face SSL error.

No ConcurrentList<T> in .Net 4.0?

ConcurrentList (as a resizeable array, not a linked list) is not easy to write with nonblocking operations. Its API doesn't translate well to a "concurrent" version.

What is an instance variable in Java?

Instance variable is the variable declared inside a class, but outside a method: something like:

class IronMan {

    /** These are all instance variables **/
    public String realName;
    public String[] superPowers;
    public int age;

    /** Getters and setters here **/
}

Now this IronMan Class can be instantiated in another class to use these variables. Something like:

class Avengers {

    public static void main(String[] a) {
        IronMan ironman = new IronMan();
        ironman.realName = "Tony Stark";
        // or
        ironman.setAge(30);
    }

}

This is how we use the instance variables. Shameless plug: This example was pulled from this free e-book here here.

"unary operator expected" error in Bash if condition

Took me a while to find this but note that if you have a spacing error you will also get the same error:

[: =: unary operator expected

Correct:

if [ "$APP_ENV" = "staging" ]

vs

if ["$APP_ENV" = "staging" ]

As always setting -x debug variable helps to find these:

set -x

How can I remove a child node in HTML using JavaScript?

You have to remove any event handlers you've set on the node before you remove it, to avoid memory leaks in IE

In Java, what purpose do the keywords `final`, `finally` and `finalize` fulfil?

final: final is a keyword. The variable decleared as final should be initialized only once and cannot be changed. Java classes declared as final cannot be extended. Methods declared as final cannot be overridden.

finally: finally is a block. The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling - it allows the programmer to avoid having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

finalize: finalize is a method. Before an object is garbage collected, the runtime system calls its finalize() method. You can write system resources release code in finalize() method before getting garbage collected.

How to hide Bootstrap previous modal when you opening new one?

You hide Bootstrap modals with:

$('#modal').modal('hide');

Saying $().hide() makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.

Correct set of dependencies for using Jackson mapper

I spent few hours on this.

Even if I had the right dependency the problem was fixed only after I deleted the com.fasterxml.jackson folder in the .m2 repository under C:\Users\username.m2 and updated the project

Filtering JSON array using jQuery grep()

_x000D_
_x000D_
var data = {_x000D_
  "items": [{_x000D_
    "id": 1,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 2,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 3,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 4,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 5,_x000D_
    "category": "cat1"_x000D_
  }]_x000D_
};_x000D_
//Filters an array of numbers to include only numbers bigger then zero._x000D_
//Exact Data you want..._x000D_
var returnedData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1" && element.id === 3;_x000D_
}, false);_x000D_
console.log(returnedData);_x000D_
$('#id').text('Id is:-' + returnedData[0].id)_x000D_
$('#category').text('Category is:-' + returnedData[0].category)_x000D_
//Filter an array of numbers to include numbers that are not bigger than zero._x000D_
//Exact Data you don't want..._x000D_
var returnedOppositeData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1";_x000D_
}, true);_x000D_
console.log(returnedOppositeData);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p id='id'></p>_x000D_
<p id='category'></p>
_x000D_
_x000D_
_x000D_

The $.grep() method eliminates items from an array as necessary so that only remaining items carry a given search. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.

How to get the current directory in a C program?

#include <stdio.h>  /* defines FILENAME_MAX */
//#define WINDOWS  /* uncomment this line to use it for windows.*/
#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif

int main(){
  char buff[FILENAME_MAX];
  GetCurrentDir( buff, FILENAME_MAX );
  printf("Current working dir: %s\n", buff);
  return 1;
}

How to delete or add column in SQLITE?

http://www.sqlite.org/lang_altertable.html

As you can see in the diagram, only ADD COLUMN is supported. There is a (kinda heavy) workaround, though: http://www.sqlite.org/faq.html#q11

Storing WPF Image Resources

In code to load a resource in the executing assembly where my image Freq.png was in the folder Icons and defined as Resource:

this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/" 
    + Assembly.GetExecutingAssembly().GetName().Name 
    + ";component/" 
    + "Icons/Freq.png", UriKind.Absolute)); 

I also made a function:

/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
    if (assembly == null)
    {
        assembly = Assembly.GetCallingAssembly();
    }

    if (pathInApplication[0] == '/')
    {
        pathInApplication = pathInApplication.Substring(1);
    }
    return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute)); 
}

Usage (assumption you put the function in a ResourceHelper class):

this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");

Note: see MSDN Pack URIs in WPF:
pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml

What does DIM stand for in Visual Basic and BASIC?

Short for Dimension. It's a type of variable. You declare (or "tell" Visual Basic) that you are setting up a variable with this word.

How to add number of days in postgresql datetime

For me I had to put the whole interval in single quotes not just the value of the interval.

select id,  
   title,
   created_at + interval '1 day' * claim_window as deadline from projects   

Instead of

select id,  
   title,
   created_at + interval '1' day * claim_window as deadline from projects   

Postgres Date/Time Functions

How to adjust text font size to fit textview

I had this pain in my projects for soooo long until I found this library:

compile 'me.grantland:autofittextview:0.2.+'

You just need to add the xml by your needs and it's done. For example:

<me.grantland.widget.AutofitTextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:singleLine="true"
android:maxLines="2"
android:textSize="40sp"
autofit:minTextSize="16sp"
/>

How to concatenate strings in django templates?

Use with:

{% with "shop/"|add:shop_name|add:"/base.html" as template %}
{% include template %}
{% endwith %}

Python, creating objects

class Student(object):
    name = ""
    age = 0
    major = ""

    # The class "constructor" - It's actually an initializer 
    def __init__(self, name, age, major):
        self.name = name
        self.age = age
        self.major = major

def make_student(name, age, major):
    student = Student(name, age, major)
    return student

Note that even though one of the principles in Python's philosophy is "there should be one—and preferably only one—obvious way to do it", there are still multiple ways to do this. You can also use the two following snippets of code to take advantage of Python's dynamic capabilities:

class Student(object):
    name = ""
    age = 0
    major = ""

def make_student(name, age, major):
    student = Student()
    student.name = name
    student.age = age
    student.major = major
    # Note: I didn't need to create a variable in the class definition before doing this.
    student.gpa = float(4.0)
    return student

I prefer the former, but there are instances where the latter can be useful – one being when working with document databases like MongoDB.

How to format LocalDate to string?

Could be short as:

LocalDate.now().format(DateTimeFormatter.ofPattern("dd/MM/yyyy"));

How to use Git Revert

Use git revert like so:

git revert <insert bad commit hash here>

git revert creates a new commit with the changes that are rolled back. git reset erases your git history instead of making a new commit.

The steps after are the same as any other commit.

Are there .NET implementation of TLS 1.2?

Just download this registry key and run it. It will add the necessary key to the .NET framework registry. You can have more info at this link. Search for 'Option 2' in '.NET 4.5 to 4.5.2'.

The reg file appends the following to the Registry:

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\.NETFramework\v4.0.30319]
"SchUseStrongCrypto"=dword:00000001

This is the part of the page that is useful in case it goes broken :

" .. enable TLS 1.2 by default without modifying the source code by setting the SchUseStrongCrypto DWORD value in the following two registry keys to 1, creating them if they don't exist: "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft.NETFramework\v4.0.30319" and "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft.NETFramework\v4.0.30319". Although the version number in those registry keys is 4.0.30319, the .NET 4.5, 4.5.1, and 4.5.2 frameworks also use these values. Those registry keys, however, will enable TLS 1.2 by default in all installed .NET 4.0, 4.5, 4.5.1, and 4.5.2 applications on that system. It is thus advisable to test this change before deploying it to your production servers. This is also available as a registry import file. These registry values, however, will not affect .NET applications that set the System.Net.ServicePointManager.SecurityProtocol value. "

ValidateAntiForgeryToken purpose, explanation and example

MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.

It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form, or by simply programmatically triggering a form when the page loads.

The feature doesn't prevent any other type of data forgery or tampering based attacks.

To use it, decorate the action method or controller with the ValidateAntiForgeryToken attribute and place a call to @Html.AntiForgeryToken() in the forms posting to the method.

Laravel Eloquent Join vs Inner Join?

Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.

You could build it like this:

<?php

Schema::create('feeds', function($table) {
    $table->increments('id');
    $table->timestamps();
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->morphs('target'); 
});

Build the feed model like so:

<?php

class Feed extends Eloquent
{
    protected $fillable = ['user_id', 'target_type', 'target_id'];

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function target()
    {
        return $this->morphTo();
    }
}

Then keep it up to date with something like:

<?php

Vote::created(function(Vote $vote) {
    $target_type = 'Vote';
    $target_id   = $vote->id;
    $user_id     = $vote->user_id;

    Feed::create(compact('target_type', 'target_id', 'user_id'));
});

You could make the above much more generic/robust—this is just for demonstration purposes.

At this point, your feed items are really easy to retrieve all at once:

<?php

Feed::whereIn('user_id', $my_friend_ids)
    ->with('user', 'target')
    ->orderBy('created_at', 'desc')
    ->get();

Android Horizontal RecyclerView scroll Direction

//in fragment page: 

 recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity(), HORIZONTAL,true));

//this worked for me but before that please import :

implementation 'com.android.support:recyclerview-v7:28.0.0'

How to get WordPress post featured image URL

Use:

<?php 
    $image_src = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail_size');

    $feature_image_url = $image_src[0]; 
?>

You can change the thumbnail_size value as per your required size.

Can't update data-attribute value

If we wanted to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:

JavaScript

<script>
// 'Getting' data-attributes using getAttribute
var plant = document.getElementById('strawberry-plant');
var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'

// 'Setting' data-attributes using setAttribute
plant.setAttribute('data-fruit','7'); // Pesky birds
</script>

Through jQuery

// Fetching data
var fruitCount = $(this).data('fruit');

// Above does not work in firefox. So use below to get attribute value.
var fruitCount = $(this).attr('data-fruit');

// Assigning data
$(this).data('fruit','7');

// But when you get the value again, it will return old value. 
// You have to set it as below to update value. Then you will get updated value.
$(this).attr('data-fruit','7'); 

Read this documentation for vanilla js or this documentation for jquery

adding multiple event listeners to one element

Semi-related, but this is for initializing one unique event listener specific per element.

You can use the slider to show the values in realtime, or check the console. On the <input> element I have a attr tag called data-whatever, so you can customize that data if you want to.

_x000D_
_x000D_
sliders = document.querySelectorAll("input");_x000D_
sliders.forEach(item=> {_x000D_
  item.addEventListener('input', (e) => {_x000D_
    console.log(`${item.getAttribute("data-whatever")} is this value: ${e.target.value}`);_x000D_
    item.nextElementSibling.textContent = e.target.value;_x000D_
  });_x000D_
})
_x000D_
.wrapper {_x000D_
  display: flex;_x000D_
}_x000D_
span {_x000D_
  padding-right: 30px;_x000D_
  margin-left: 5px;_x000D_
}_x000D_
* {_x000D_
  font-size: 12px_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <input type="range" min="1" data-whatever="size" max="800" value="50" id="sliderSize">_x000D_
  <em>50</em>_x000D_
  <span>Size</span>_x000D_
  <br>_x000D_
  <input type="range" min="1" data-whatever="OriginY" max="800" value="50" id="sliderOriginY">_x000D_
  <em>50</em>_x000D_
  <span>OriginY</span>_x000D_
  <br>_x000D_
  <input type="range" min="1" data-whatever="OriginX" max="800" value="50" id="sliderOriginX">_x000D_
  <em>50</em>_x000D_
  <span>OriginX</span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Android ADB doesn't see device

On Windows it is most probably that the device drivers are not installed properly.

First, install Google USB Driver from Android SDK Manager.

Then, go to Start, right-click on My Computer, select Properties and go to Device Manager on the left. Locate you device under Other Devices (Unknown devices, USB Devices). Right-click on it and select Properties. Navigate to Driver tab. Select Update Driver and then Browse my computer for driver software. Choose %ANDROID_SDK_HOME%\extras\google\usb_driver directory. Windows should find and install drivers there. Then run adb kill-server. Next time you do adb devices the device should be in the list.

mysql count group by having

SELECT COUNT(*) 
FROM   (SELECT COUNT(*) 
        FROM   movies 
        GROUP  BY id 
        HAVING COUNT(genre) = 4) t

Transpose a range in VBA

You do not need to do this. Here is how to create a co-variance method:

http://www.youtube.com/watch?v=RqAfC4JXd4A

Alternatively you can use statistical analysis package that Excel has.

Object of class stdClass could not be converted to string

try this

return $query->result_array();

XML shape drawable not rendering desired color

I had a similar problem and found that if you remove the size definition, it works for some reason.

Remove:

<size
    android:width="60dp"
    android:height="40dp" />

from the shape.

Let me know if this works!

Where can I find my Facebook application id and secret key?

I had a hard time finding where it is so here the image depicting it in 2019.  the location of app secret and app id in 2019.

How to search a list of tuples in Python

[i for i, v in enumerate(L) if v[0] == 53]

Programmatically relaunch/recreate an activity?

Also depending on your situation, you may need getActivity().recreate(); instead of just recreate().

For example, you should use it if you are doing recreate() in the class which has been created inside class of activity.

How to read HDF5 files in Python

Reading the file

import h5py

f = h5py.File(file_name, mode)

Studying the structure of the file by printing what HDF5 groups are present

for key in f.keys():
    print(key) #Names of the groups in HDF5 file.

Extracting the data

#Get the HDF5 group
group = f[key]

#Checkout what keys are inside that group.
for key in group.keys():
    print(key)

data = group[some_key_inside_the_group].value
#Do whatever you want with data

#After you are done
f.close()

How to ping multiple servers and return IP address and Hostnames using batch script?

This works for spanish operation system.

Script accepts two parameters:

  • a file with the list of IP or domains
  • output file

script.bat listofurls.txt output.txt

@echo off
setlocal enabledelayedexpansion
set OUTPUT_FILE=%2
>nul copy nul %OUTPUT_FILE%
for /f %%i in (%1) do (
    set SERVER_ADDRESS=No se pudo resolver el host
    for /f "tokens=1,2,3,4,5" %%v in ('ping -a -n 1 %%i ^&^& echo SERVER_IS_UP') 
    do (
        if %%v==Haciendo set SERVER_ADDRESS=%%z
        if %%v==Respuesta set SERVER_ADDRESS=%%x
        if %%v==SERVER_IS_UP (set SERVER_STATE=UP) else (set SERVER_STATE=DOWN)
    )
    echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE! >>%OUTPUT_FILE%
    echo %%i [!SERVER_ADDRESS::=!] is !SERVER_STATE!
)

Is a LINQ statement faster than a 'foreach' loop?

Why should LINQ be faster? It also uses loops internally.

Most of the times, LINQ will be a bit slower because it introduces overhead. Do not use LINQ if you care much about performance. Use LINQ because you want shorter better readable and maintainable code.

Is there a way to make AngularJS load partials in the beginning and not at when needed?

I just use eco to do the job for me. eco is supported by Sprockets by default. It's a shorthand for Embedded Coffeescript which takes a eco file and compile into a Javascript template file, and the file will be treated like any other js files you have in your assets folder.

All you need to do is to create a template with extension .jst.eco and write some html code in there, and rails will automatically compile and serve the file with the assets pipeline, and the way to access the template is really easy: JST['path/to/file']({var: value}); where path/to/file is based on the logical path, so if you have file in /assets/javascript/path/file.jst.eco, you can access the template at JST['path/file']()

To make it work with angularjs, you can pass it into the template attribute instead of templateDir, and it will start working magically!

Phone Number Validation MVC

Or you can use JQuery - just add your input field to the class "phone" and put this in your script section:

$(".phone").keyup(function () {
        $(this).val($(this).val().replace(/^(\d{3})(\d{3})(\d)+$/, "($1)$2-$3"));

There is no error message but you can see that the phone number is not correctly formatted until you have entered all ten digits.

Read an Excel file directly from a R script

EDIT 2015-October: As others have commented here the openxlsx and readxl packages are by far faster than the xlsx package and actually manage to open larger Excel files (>1500 rows & > 120 columns). @MichaelChirico demonstrates that readxl is better when speed is preferred and openxlsx replaces the functionality provided by the xlsx package. If you are looking for a package to read, write, and modify Excel files in 2015, pick the openxlsx instead of xlsx.

Pre-2015: I have used xlsxpackage. It changed my workflow with Excel and R. No more annoying pop-ups asking, if I am sure that I want to save my Excel sheet in .txt format. The package also writes Excel files.

However, I find read.xlsx function slow, when opening large Excel files. read.xlsx2 function is considerably faster, but does not quess the vector class of data.frame columns. You have to use colClasses command to specify desired column classes, if you use read.xlsx2 function. Here is a practical example:

read.xlsx("filename.xlsx", 1) reads your file and makes the data.frame column classes nearly useful, but is very slow for large data sets. Works also for .xls files.

read.xlsx2("filename.xlsx", 1) is faster, but you will have to define column classes manually. A shortcut is to run the command twice (see the example below). character specification converts your columns to factors. Use Dateand POSIXct options for time.

coln <- function(x){y <- rbind(seq(1,ncol(x))); colnames(y) <- colnames(x)
rownames(y) <- "col.number"; return(y)} # A function to see column numbers

data <- read.xlsx2("filename.xlsx", 1) # Open the file 

coln(data)    # Check the column numbers you want to have as factors

x <- 3 # Say you want columns 1-3 as factors, the rest numeric

data <- read.xlsx2("filename.xlsx", 1, colClasses= c(rep("character", x),
rep("numeric", ncol(data)-x+1)))

Django: Redirect to previous page after login

I encountered the same problem. This solution allows me to keep using the generic login view:

urlpatterns += patterns('django.views.generic.simple',
    (r'^accounts/profile/$', 'redirect_to', {'url': 'generic_account_url'}),
)

PHP: Return all dates between two dates in an array

<?
print_r(getDatesFromRange( '2010-10-01', '2010-10-05' ));

function getDatesFromRange($startDate, $endDate)
{
    $return = array($startDate);
    $start = $startDate;
    $i=1;
    if (strtotime($startDate) < strtotime($endDate))
    {
       while (strtotime($start) < strtotime($endDate))
        {
            $start = date('Y-m-d', strtotime($startDate.'+'.$i.' days'));
            $return[] = $start;
            $i++;
        }
    }

    return $return;
}

Sorting dropdown alphabetically in AngularJS

You should be able to use filter: orderBy

orderBy can accept a third option for the reverse flag.

<select ng-option="item.name for item in items | orderBy:'name':true"></select>

Here item is sorted by 'name' property in a reversed order. The 2nd argument can be any order function, so you can sort in any rule.

@see http://docs.angularjs.org/api/ng.filter:orderBy

Change the image source on rollover using jQuery

$('img').mouseover(function(){
  var newSrc = $(this).attr("src").replace("image.gif", "imageover.gif");
  $(this).attr("src", newSrc); 
});
$('img').mouseout(function(){
  var newSrc = $(this).attr("src").replace("imageover.gif", "image.gif");
  $(this).attr("src", newSrc); 
});

Convert integer to class Date

as.character() would be the general way rather than use paste() for its side effect

> v <- 20081101
> date <- as.Date(as.character(v), format = "%Y%m%d")
> date
[1] "2008-11-01"

(I presume this is a simple example and something like this:

v <- "20081101"

isn't possible?)

AES Encrypt and Decrypt

I was using CommonCrypto to generate Hash through the code of MihaelIsaev/HMAC.swift from Easy to use Swift implementation of CommonCrypto HMAC. This implementation is without using Bridging-Header, with creation of Module file.

Now to use AESEncrypt and Decrypt, I directly added the functions inside "extension String {" in HAMC.swift.

func aesEncrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
    if let keyData = key.dataUsingEncoding(NSUTF8StringEncoding),
        data = self.dataUsingEncoding(NSUTF8StringEncoding),
        cryptData    = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) {

            let keyLength              = size_t(kCCKeySizeAES128)
            let operation: CCOperation = UInt32(kCCEncrypt)
            let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
            let options:   CCOptions   = UInt32(options)

            var numBytesEncrypted :size_t = 0

            let cryptStatus = CCCrypt(operation,
                algoritm,
                options,
                keyData.bytes, keyLength,
                iv,
                data.bytes, data.length,
                cryptData.mutableBytes, cryptData.length,
                &numBytesEncrypted)

            if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                cryptData.length = Int(numBytesEncrypted)
                let base64cryptString = cryptData.base64EncodedStringWithOptions(.Encoding64CharacterLineLength)
                return base64cryptString
            }
            else {
                return nil
            }
    }
    return nil
}

func aesDecrypt(key:String, iv:String, options:Int = kCCOptionPKCS7Padding) -> String? {
    if let keyData = key.dataUsingEncoding(NSUTF8StringEncoding),
        data = NSData(base64EncodedString: self, options: .IgnoreUnknownCharacters),
        cryptData    = NSMutableData(length: Int((data.length)) + kCCBlockSizeAES128) {

            let keyLength              = size_t(kCCKeySizeAES128)
            let operation: CCOperation = UInt32(kCCDecrypt)
            let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
            let options:   CCOptions   = UInt32(options)

            var numBytesEncrypted :size_t = 0

            let cryptStatus = CCCrypt(operation,
                algoritm,
                options,
                keyData.bytes, keyLength,
                iv,
                data.bytes, data.length,
                cryptData.mutableBytes, cryptData.length,
                &numBytesEncrypted)

            if UInt32(cryptStatus) == UInt32(kCCSuccess) {
                cryptData.length = Int(numBytesEncrypted)
                let unencryptedMessage = String(data: cryptData, encoding:NSUTF8StringEncoding)
                return unencryptedMessage
            }
            else {
                return nil
            }
    }
    return nil
}

The functions were taken from RNCryptor. It was an easy addition in the hashing functions and in one single file "HMAC.swift", without using Bridging-header. I hope this will be useful for developers in swift requiring Hashing and AES Encryption/Decryption.

Example of using the AESDecrypt as under.

 let iv = "AA-salt-BBCCDD--" // should be of 16 characters.
 //here we are convert nsdata to String
 let encryptedString = String(data: dataFromURL, encoding: NSUTF8StringEncoding)
 //now we are decrypting
 if let decryptedString = encryptedString?.aesDecrypt("12345678901234567890123456789012", iv: iv) // 32 char pass key
 {                    
      // Your decryptedString
 }

Windows Batch Files: if else

An alternative would be to set a variable, and check whether it is defined:

SET ARG=%1
IF DEFINED ARG (echo "It is defined: %1") ELSE (echo "%%1 is not defined")

Unfortunately, using %1 directly with DEFINED doesn't work.

Angular ui-grid dynamically calculate height of the grid

UPDATE:

The HTML was requested so I've pasted it below.

<div ui-grid="gridOptions" class="my-grid"></div>

ORIGINAL:

We were able to adequately solve this problem by using responsive CSS (@media) that sets the height and width based on screen real estate. Something like (and clearly you can add more based on your needs):

@media (min-width: 1024px) {
  .my-grid {
    width: 772px;
  }
}

@media (min-width: 1280px) {
  .my-grid {
    width: 972px;
  }
}

@media (min-height: 768px) {
  .my-grid {
    height: 480px;
  }
}

@media (min-height: 900px) {
  .my-grid {
    height: 615px;
  }
}

The best part about this solution is that we need no resize event handling to monitor for grid size changes. It just works.

How do I encode and decode a base64 string?

I'm sharing my implementation with some neat features:

  • uses Extension Methods for Encoding class. Rationale is that someone may need to support different types of encodings (not only UTF8).
  • Another improvement is failing gracefully with null result for null entry - it's very useful in real life scenarios and supports equivalence for X=decode(encode(X)).

Remark: Remember that to use Extension Method you have to (!) import the namespace with using keyword (in this case using MyApplication.Helpers.Encoding).

Code:

namespace MyApplication.Helpers.Encoding
{
    public static class EncodingForBase64
    {
        public static string EncodeBase64(this System.Text.Encoding encoding, string text)
        {
            if (text == null)
            {
                return null;
            }

            byte[] textAsBytes = encoding.GetBytes(text);
            return System.Convert.ToBase64String(textAsBytes);
        }

        public static string DecodeBase64(this System.Text.Encoding encoding, string encodedText)
        {
            if (encodedText == null)
            {
                return null;
            }

            byte[] textAsBytes = System.Convert.FromBase64String(encodedText);
            return encoding.GetString(textAsBytes);
        }
    }
}

Usage example:

using MyApplication.Helpers.Encoding; // !!!

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Test1();
            Test2();
        }

        static void Test1()
        {
            string textEncoded = System.Text.Encoding.UTF8.EncodeBase64("test1...");
            System.Diagnostics.Debug.Assert(textEncoded == "dGVzdDEuLi4=");

            string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);
            System.Diagnostics.Debug.Assert(textDecoded == "test1...");
        }

        static void Test2()
        {
            string textEncoded = System.Text.Encoding.UTF8.EncodeBase64(null);
            System.Diagnostics.Debug.Assert(textEncoded == null);

            string textDecoded = System.Text.Encoding.UTF8.DecodeBase64(textEncoded);
            System.Diagnostics.Debug.Assert(textDecoded == null);
        }
    }
}

How to add MVC5 to Visual Studio 2013?

You can look into Windows installed folder from here of your pc path:

C:\Program Files (x86)\Microsoft ASP.NET

View of Opened file where showing installed MVC 3, MVC 4

enter image description here

What is the difference between HTTP and REST?

HTTP is an application protocol. REST is a set of rules, that when followed, enable you to build a distributed application that has a specific set of desirable constraints.

If you are looking for the most significant constraints of REST that distinguish a RESTful application from just any HTTP application, I would say the "self-description" constraint and the hypermedia constraint (aka Hypermedia as the Engine of Application State (HATEOAS)) are the most important.

The self-description constraint requires a RESTful request to be completely self descriptive in the users intent. This allows intermediaries (proxies and caches) to act on the message safely.

The HATEOAS constraint is about turning your application into a web of links where the client's current state is based on its place in that web. It is a tricky concept and requires more time to explain than I have right now.

How do I use select with date condition?

If you put in

SELECT * FROM Users WHERE RegistrationDate >= '1/20/2009' 

it will automatically convert the string '1/20/2009' into the DateTime format for a date of 1/20/2009 00:00:00. So by using >= you should get every user whose registration date is 1/20/2009 or more recent.

Edit: I put this in the comment section but I should probably link it here as well. This is an article detailing some more in depth ways of working with DateTime's in you queries: http://www.databasejournal.com/features/mssql/article.php/2209321/Working-with-SQL-Server-DateTime-Variables-Part-Three---Searching-for-Particular-Date-Values-and-Ranges.htm

How do I get formatted JSON in .NET using C#?

First I wanted to add comment under Duncan Smart post, but unfortunately I have not got enough reputation yet to leave comments. So I will try it here.

I just want to warn about side effects.

JsonTextReader internally parses json into typed JTokens and then serialises them back.

For example if your original JSON was

 { "double":0.00002, "date":"\/Date(1198908717056)\/"}

After prettify you get

{ 
    "double":2E-05,
    "date": "2007-12-29T06:11:57.056Z"
}

Of course both json string are equivalent and will deserialize to structurally equal objects, but if you need to preserve original string values, you need to take this into concideration

Preventing multiple clicks on button

Disable pointer events in the first line of your callback, and then resume them on the last line.

element.on('click', function() {
  element.css('pointer-events', 'none'); 
  //do all of your stuff
  element.css('pointer-events', 'auto');   
};

How to make a flat list out of list of lists?

Why do you use extend?

reduce(lambda x, y: x+y, l)

This should work fine.

Fix height of a table row in HTML Table

the bottom cell will grow as you enter more text ... setting the table width will help too

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
</head>
<body>
<table id="content" style="min-height:525px; height:525px; width:100%; border:0px; margin:0; padding:0; border-collapse:collapse;">
<tr><td style="height:10px; background-color:#900;">Upper</td></tr>
<tr><td style="min-height:515px; height:515px; background-color:#909;">lower<br/>
</td></tr>
</table>
</body>
</html>

How to add a new row to datagridview programmatically

Lets say you have a datagridview that is not bound to a dataset and you want to programmatically populate new rows...

Here's how you do it.

// Create a new row first as it will include the columns you've created at design-time.

int rowId = dataGridView1.Rows.Add();

// Grab the new row!
DataGridViewRow row = dataGridView1.Rows[rowId];

// Add the data
row.Cells["Column1"].Value = "Value1";
row.Cells["Column2"].Value = "Value2";

// And that's it! Quick and painless... :o)

Select a Dictionary<T1, T2> with LINQ

var dictionary = (from x in y 
                  select new SomeClass
                  {
                      prop1 = value1,
                      prop2 = value2
                  }
                  ).ToDictionary(item => item.prop1);

That's assuming that SomeClass.prop1 is the desired Key for the dictionary.

Sql Server equivalent of a COUNTIF aggregate function

I had to use COUNTIF() in my case as part of my SELECT columns AND to mimic a % of the number of times each item appeared in my results.

So I used this...

SELECT COL1, COL2, ... ETC
       (1 / SELECT a.vcount 
            FROM (SELECT vm2.visit_id, count(*) AS vcount 
                  FROM dbo.visitmanifests AS vm2 
                  WHERE vm2.inactive = 0 AND vm2.visit_id = vm.Visit_ID 
                  GROUP BY vm2.visit_id) AS a)) AS [No of Visits],
       COL xyz
FROM etc etc

Of course you will need to format the result according to your display requirements.

Does List<T> guarantee insertion order?

As Bevan said, but keep in mind, that the list-index is 0-based. If you want to move an element to the front of the list, you have to insert it at index 0 (not 1 as shown in your example).

C - freeing structs

Because you defined the struct as consisting of char arrays, the two strings are the structure and freeing the struct is sufficient, nor is there a way to free the struct but keep the arrays. For that case you would want to do something like struct { char *firstName, *lastName; }, but then you need to allocate memory for the names separately and handle the question of when to free that memory.

Aside: Is there a reason you want to keep the names after the struct has been freed?

Get an object attribute

Use getattr if you have an attribute in string form:

>>> class User(object):
       name = 'John'

>>> u = User()
>>> param = 'name'
>>> getattr(u, param)
'John'

Otherwise use the dot .:

>>> class User(object):
       name = 'John'

>>> u = User()
>>> u.name
'John'

Difference between Activity and FragmentActivity

A FragmentActivity is a subclass of Activity that was built for the Android Support Package.

The FragmentActivity class adds a couple new methods to ensure compatibility with older versions of Android, but other than that, there really isn't much of a difference between the two. Just make sure you change all calls to getLoaderManager() and getFragmentManager() to getSupportLoaderManager() and getSupportFragmentManager() respectively.

Split an NSString to access one particular piece

Its working fine

NSString *dateString = @"10/10/2010";//Date 
NSArray* dateArray = [dateString componentsSeparatedByString: @"/"];
NSString* dayString = [dateArray objectAtIndex: 0];

Why use prefixes on member variables in C++ classes

You have to be careful with using a leading underscore. A leading underscore before a capital letter in a word is reserved. For example:

_Foo

_L

are all reserved words while

_foo

_l

are not. There are other situations where leading underscores before lowercase letters are not allowed. In my specific case, I found the _L happened to be reserved by Visual C++ 2005 and the clash created some unexpected results.

I am on the fence about how useful it is to mark up local variables.

Here is a link about which identifiers are reserved: What are the rules about using an underscore in a C++ identifier?

How to Use -confirm in PowerShell

Here is the documentation from Microsoft on how to request confirmations in a cmdlet. The examples are in C#, but you can do everything shown in PowerShell as well.

First add the CmdletBinding attribute to your function and set SupportsShouldProcess to true. Then you can reference the ShouldProcess and ShouldContinue methods of the $PSCmdlet variable.

Here is an example:

function Start-Work {
    <#
    .SYNOPSIS Does some work
    .PARAMETER Force
        Perform the operation without prompting for confirmation
    #>
    [CmdletBinding(SupportsShouldProcess=$true)]
    param(
        # This switch allows the user to override the prompt for confirmation
        [switch]$Force
    )
    begin { }
    process {
        if ($PSCmdlet.ShouldProcess('Target')) {
            if (-not ($Force -or $PSCmdlet.ShouldContinue('Do you want to continue?', 'Caption'))) {
                return # user replied no
            }

            # Do work
        }

    }
    end { }
}

jQuery: Selecting by class and input type

You should use the class name like this

$(document).ready(function(){
    $('input.addCheck').prop('checked',true);
});

Try Using this a live demo

How do I allow HTTPS for Apache on localhost?

It's actually quite easy, assuming you have an openssl installation handy. (What platform are you on?)

Assuming you're on linux/solaris/mac os/x, Van's Apache SSL/TLS mini-HOWTO has an excellent walkthrough that I won't reproduce here.

However, the executive summary is that you have to create a self-signed certificate. Since you're running apache for localhost presumably for development (i.e. not a public web server), you'll know that you can trust the self-signed certificate and can ignore the warnings that your browser will throw at you.

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

This problem can also come up when you don't have your constructor immediately call super.

So this will work:

  public Employee(String name, String number, Date date)
  {
    super(....)
  }

But this won't:

  public Employee(String name, String number, Date date)
  {
    // an example of *any* code running before you call super.
    if (number < 5)
    {
       number++;
    }

    super(....)
  }

The reason the 2nd example fails is because java is trying to implicitely call

super(name,number,date)

as the first line in your constructor.... So java doesn't see that you've got a call to super going on later in the constructor. It essentially tries to do this:

  public Employee(String name, String number, Date date)
  {
    super(name, number, date);

    if (number < 5)
    {
       number++;
    }

    super(....)
  }

So the solution is pretty easy... Just don't put code before your super call ;-) If you need to initialize something before the call to super, do it in another constructor, and then call the old constructor... Like in this example pulled from this StackOverflow post:

public class Foo
{
    private int x;

    public Foo()
    {
        this(1);
    }

    public Foo(int x)
    {
        this.x = x;
    }
}

HTML text input field with currency symbol

You can wrap your input field into a span, which you position:relative;. Then you add with :before content:"€" your currency symbol and make it position:absolute. Working JSFiddle

HTML

<span class="input-symbol-euro">
    <input type="text" />
</span>

CSS

.input-symbol-euro {
    position: relative;
}
.input-symbol-euro input {
    padding-left:18px;
}
.input-symbol-euro:before {
    position: absolute;
    top: 0;
    content:"€";
    left: 5px;
}

Update If you want to put the euro symbol either on the left or the right side of the text box. Working JSFiddle

HTML

<span class="input-euro left">
    <input type="text" />
</span>
<span class="input-euro right">
    <input type="text" />
</span>

CSS

 .input-euro {
     position: relative;
 }
 .input-euro.left input {
     padding-left:18px;
 }
 .input-euro.right input {
     padding-right:18px;
     text-align:end; 
 }

 .input-euro:before {
     position: absolute;
     top: 0;
     content:"€";
 }
 .input-euro.left:before {
     left: 5px;
 }
 .input-euro.right:before {
     right: 5px;
 }

Regex pattern inside SQL Replace function?

You can use PATINDEX to find the first index of the pattern (string's) occurrence. Then use STUFF to stuff another string into the pattern(string) matched.

Loop through each row. Replace each illegal characters with what you want. In your case replace non numeric with blank. The inner loop is if you have more than one illegal character in a current cell that of the loop.

DECLARE @counter int

SET @counter = 0

WHILE(@counter < (SELECT MAX(ID_COLUMN) FROM Table))
BEGIN  

    WHILE 1 = 1
    BEGIN
        DECLARE @RetVal varchar(50)

        SET @RetVal =  (SELECT Column = STUFF(Column, PATINDEX('%[^0-9.]%', Column),1, '')
        FROM Table
        WHERE ID_COLUMN = @counter)

        IF(@RetVal IS NOT NULL)       
          UPDATE Table SET
          Column = @RetVal
          WHERE ID_COLUMN = @counter
        ELSE
            break
    END

    SET @counter = @counter + 1
END

Caution: This is slow though! Having a varchar column may impact. So using LTRIM RTRIM may help a bit. Regardless, it is slow.

Credit goes to this StackOverFlow answer.

EDIT Credit also goes to @srutzky

Edit (by @Tmdean) Instead of doing one row at a time, this answer can be adapted to a more set-based solution. It still iterates the max of the number of non-numeric characters in a single row, so it's not ideal, but I think it should be acceptable in most situations.

WHILE 1 = 1 BEGIN
    WITH q AS
        (SELECT ID_Column, PATINDEX('%[^0-9.]%', Column) AS n
        FROM Table)
    UPDATE Table
    SET Column = STUFF(Column, q.n, 1, '')
    FROM q
    WHERE Table.ID_Column = q.ID_Column AND q.n != 0;

    IF @@ROWCOUNT = 0 BREAK;
END;

You can also improve efficiency quite a lot if you maintain a bit column in the table that indicates whether the field has been scrubbed yet. (NULL represents "Unknown" in my example and should be the column default.)

DECLARE @done bit = 0;
WHILE @done = 0 BEGIN
    WITH q AS
        (SELECT ID_Column, PATINDEX('%[^0-9.]%', Column) AS n
        FROM Table
        WHERE COALESCE(Scrubbed_Column, 0) = 0)
    UPDATE Table
    SET Column = STUFF(Column, q.n, 1, ''),
        Scrubbed_Column = 0
    FROM q
    WHERE Table.ID_Column = q.ID_Column AND q.n != 0;

    IF @@ROWCOUNT = 0 SET @done = 1;

    -- if Scrubbed_Column is still NULL, then the PATINDEX
    -- must have given 0
    UPDATE table
    SET Scrubbed_Column = CASE
        WHEN Scrubbed_Column IS NULL THEN 1
        ELSE NULLIF(Scrubbed_Column, 0)
    END;
END;

If you don't want to change your schema, this is easy to adapt to store intermediate results in a table valued variable which gets applied to the actual table at the end.

addClass - can add multiple classes on same div?

You can do

$('.page-address-edit').addClass('test1 test2');

More here:

More than one class may be added at a time, separated by a space, to the set of matched elements, like so:

$("p").addClass("myClass yourClass");

How to set a default Value of a UIPickerView

I too had this problem. But apparently there is an issue of the order of method calls. You must call:

[self.picker selectRow:2 inComponent:0 animated:YES];

after calling

[self.view addSubview:self.picker];

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

How can I add raw data body to an axios request?

Here is my solution:

axios({
  method: "POST",
  url: "https://URL.com/api/services/fetchQuizList",
  headers: {
    "x-access-key": data,
    "x-access-token": token,
  },
  data: {
    quiz_name: quizname,
  },
})
.then(res => {
  console.log("res", res.data.message);
})
.catch(err => {
  console.log("error in request", err);
});

This should help

Remove all whitespace in a string

To remove only spaces use str.replace:

sentence = sentence.replace(' ', '')

To remove all whitespace characters (space, tab, newline, and so on) you can use split then join:

sentence = ''.join(sentence.split())

or a regular expression:

import re
pattern = re.compile(r'\s+')
sentence = re.sub(pattern, '', sentence)

If you want to only remove whitespace from the beginning and end you can use strip:

sentence = sentence.strip()

You can also use lstrip to remove whitespace only from the beginning of the string, and rstrip to remove whitespace from the end of the string.

Seaborn plots not showing up

Plots created using seaborn need to be displayed like ordinary matplotlib plots. This can be done using the

plt.show()

function from matplotlib.

Originally I posted the solution to use the already imported matplotlib object from seaborn (sns.plt.show()) however this is considered to be a bad practice. Therefore, simply directly import the matplotlib.pyplot module and show your plots with

import matplotlib.pyplot as plt
plt.show()

If the IPython notebook is used the inline backend can be invoked to remove the necessity of calling show after each plot. The respective magic is

%matplotlib inline

what is the size of an enum type data in C++?

Because it's the size of an instance of the type - presumably enum values are stored as (32-bit / 4-byte) ints here.

Declaring multiple variables in JavaScript

ECMAScript 2015 introduced destructuring assignment which works pretty nice:

[a, b] = [1, 2]

a will equal 1 and b will equal 2.

Reporting Services export to Excel with Multiple Worksheets

On the group press F4 and look for the page name, on the properties and name your page this should solve your problem

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

if after adding the C:\Program Files\Java\jdk1.8.0_92\bin in PATH variable in environment variables the eclipse gave the same error

check eclipse configuration settings file that found in eclipse folder, you must see the same jdk path you have in C:\program Files

enter image description here

I hope it help.

How to correctly close a feature branch in Mercurial?

It is strange, that no one yet has suggested the most robust way of closing a feature branches... You can just combine merge commit with --close-branch flag (i.e. commit modified files and close the branch simultaneously):

hg up feature-x
hg merge default
hg ci -m "Merge feature-x and close branch" --close-branch
hg branch default -f

So, that is all. No one extra head on revgraph. No extra commit.

Unable to specify the compiler with CMake

I had the same issue. And in my case the fix was pretty simple. The trick is to simply add the ".exe" to your compilers path. So, instead of :

SET(CMAKE_C_COMPILER C:/MinGW/bin/gcc)

It should be

SET(CMAKE_C_COMPILER C:/MinGW/bin/gcc.exe)

The same applies for g++.

Given final block not properly padded

depending on the cryptography algorithm you are using, you may have to add some padding bytes at the end before encrypting a byte array so that the length of the byte array is multiple of the block size:

Specifically in your case the padding schema you chose is PKCS5 which is described here: http://www.rsa.com/products/bsafe/documentation/cryptoj35html/doc/dev_guide/group_CJ_SYM__PAD.html

(I assume you have the issue when you try to encrypt)

You can choose your padding schema when you instantiate the Cipher object. Supported values depend on the security provider you are using.

By the way are you sure you want to use a symmetric encryption mechanism to encrypt passwords? Wouldn't be a one way hash better? If you really need to be able to decrypt passwords, DES is quite a weak solution, you may be interested in using something stronger like AES if you need to stay with a symmetric algorithm.

How can I export Excel files using JavaScript?

I recommend you to generate an open format XML Excel file, is much more flexible than CSV.
Read Generating an Excel file in ASP.NET for more info

How to get json response using system.net.webrequest in c#?

You need to explicitly ask for the content type.

Add this line:

 request.ContentType = "application/json; charset=utf-8";
At the appropriate place

Unit Testing: DateTime.Now

We were using a static SystemTime object, but ran into problems running parallel unit tests. I attempted to use Henk van Boeijen's solution but had problems across spawned asynchronous threads, ended up using using AsyncLocal in a manner similar to this below:

public static class Clock
{
    private static Func<DateTime> _utcNow = () => DateTime.UtcNow;

    static AsyncLocal<Func<DateTime>> _override = new AsyncLocal<Func<DateTime>>();

    public static DateTime UtcNow => (_override.Value ?? _utcNow)();

    public static void Set(Func<DateTime> func)
    {
        _override.Value = func;
    }

    public static void Reset()
    {
        _override.Value = null;
    }
}

Sourced from https://gist.github.com/CraftyFella/42f459f7687b0b8b268fc311e6b4af08

Ruby optional parameters

Recently I found a way around this. I wanted to create a method in the array class with an optional parameter, to keep or discard elements in the array.

The way I simulated this was by passing an array as the parameter, and then checking if the value at that index was nil or not.

class Array
  def ascii_to_text(params)
    param_len = params.length
    if param_len > 3 or param_len < 2 then raise "Invalid number of arguments #{param_len} for 2 || 3." end
    bottom  = params[0]
    top     = params[1]
    keep    = params[2]
    if keep.nil? == false
      if keep == 1
        self.map{|x| if x >= bottom and x <= top then x = x.chr else x = x.to_s end}
      else
        raise "Invalid option #{keep} at argument position 3 in #{p params}, must be 1 or nil"
      end
    else
      self.map{|x| if x >= bottom and x <= top then x = x.chr end}.compact
    end
  end
end

Trying out our class method with different parameters:

array = [1, 2, 97, 98, 99]
p array.ascii_to_text([32, 126, 1]) # Convert all ASCII values of 32-126 to their chr value otherwise keep it the same (That's what the optional 1 is for)

output: ["1", "2", "a", "b", "c"]

Okay, cool that works as planned. Now let's check and see what happens if we don't pass in the the third parameter option (1) in the array.

array = [1, 2, 97, 98, 99]
p array.ascii_to_text([32, 126]) # Convert all ASCII values of 32-126 to their chr value else remove it (1 isn't a parameter option)

output: ["a", "b", "c"]

As you can see, the third option in the array has been removed, thus initiating a different section in the method and removing all ASCII values that are not in our range (32-126)

Alternatively, we could had issued the value as nil in the parameters. Which would look similar to the following code block:

def ascii_to_text(top, bottom, keep = nil)
  if keep.nil?
    self.map{|x| if x >= bottom and x <= top then x = x.chr end}.compact
  else
    self.map{|x| if x >= bottom and x <= top then x = x.chr else x = x.to_s end}
end

Can I force a page break in HTML printing?

I was struggling this for some time, it never worked.

In the end, the solution was to put a style element in the head.

The page-break-after can't be in a linked CSS file, it must be in the HTML itself.

Eclipse add Tomcat 7 blank server name

I had same issue before: the server name was not appearing in server while configuring with eclipse

I tried all the solutions which are provided over here, but they didn't work for me.

I resolved it, by simply following these simple tips

Step1: Windows --> Preferences --> Server --> Run time Environments --> Add --> select the tomcat version which was unavailable before --> next --> browse the location of your server with same version

Step2: go to servers and select your server version --> next --> Finish

Issue resolved!!! :)

Pointer to 2D arrays in C

int *pointer[280]; //Creates 280 pointers of type int.

In 32 bit os, 4 bytes for each pointer. so 4 * 280 = 1120 bytes.

int (*pointer)[100][280]; // Creates only one pointer which is used to point an array of [100][280] ints.

Here only 4 bytes.

Coming to your question, int (*pointer)[280]; and int (*pointer)[100][280]; are different though it points to same 2D array of [100][280].

Because if int (*pointer)[280]; is incremented, then it will points to next 1D array, but where as int (*pointer)[100][280]; crosses the whole 2D array and points to next byte. Accessing that byte may cause problem if that memory doen't belongs to your process.

Return number of rows affected by UPDATE statements

CREATE PROCEDURE UpdateTables
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;
    DECLARE @RowCount1 INTEGER
    DECLARE @RowCount2 INTEGER
    DECLARE @RowCount3 INTEGER
    DECLARE @RowCount4 INTEGER

    UPDATE Table1 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount1 = @@ROWCOUNT
    UPDATE Table2 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount2 = @@ROWCOUNT
    UPDATE Table3 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount3 = @@ROWCOUNT
    UPDATE Table4 Set Column = 0 WHERE Column IS NULL
    SELECT @RowCount4 = @@ROWCOUNT

    SELECT @RowCount1 AS Table1, @RowCount2 AS Table2, @RowCount3 AS Table3, @RowCount4 AS Table4
END

How to debug an apache virtual host configuration?

First check out config files for syntax errors with apachectl configtest and then look into apache error logs.

Any way to make a WPF textblock selectable?

Use a TextBox with these settings instead to make it read only and to look like a TextBlock control.

<TextBox Background="Transparent"
         BorderThickness="0"
         Text="{Binding Text, Mode=OneWay}"
         IsReadOnly="True"
         TextWrapping="Wrap" />

Swift: Display HTML data in a label or textView

Swift 5

extension UIColor {
    var hexString: String {
        let components = cgColor.components
        let r: CGFloat = components?[0] ?? 0.0
        let g: CGFloat = components?[1] ?? 0.0
        let b: CGFloat = components?[2] ?? 0.0

        let hexString = String(format: "#%02lX%02lX%02lX", lroundf(Float(r * 255)), lroundf(Float(g * 255)),
                               lroundf(Float(b * 255)))

        return hexString
    }
}
extension String {
    func htmlAttributed(family: String?, size: CGFloat, color: UIColor) -> NSAttributedString? {
        do {
            let htmlCSSString = "<style>" +
                "html *" +
                "{" +
                "font-size: \(size)pt !important;" +
                "color: #\(color.hexString) !important;" +
                "font-family: \(family ?? "Helvetica"), Helvetica !important;" +
            "}</style> \(self)"

            guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
                return nil
            }

            return try NSAttributedString(data: data,
                                          options: [.documentType: NSAttributedString.DocumentType.html,
                                                    .characterEncoding: String.Encoding.utf8.rawValue],
                                          documentAttributes: nil)
        } catch {
            print("error: ", error)
            return nil
        }
    }
}

And final you can create UILabel:

func createHtmlLabel(with html: String) -> UILabel {
    let htmlMock = """
    <b>hello</b>, <i>world</i>
    """

    let descriprionLabel = UILabel()
    descriprionLabel.attributedText = htmlMock.htmlAttributed(family: "YourFontFamily", size: 15, color: .red)

    return descriprionLabel
}

Result:

enter image description here

See tutorial:

https://medium.com/@valv0/a-swift-extension-for-string-and-html-8cfb7477a510

How do I fix the npm UNMET PEER DEPENDENCY warning?

You will get this warning if you are using npm v6 or before. After npm v7.0, npm development team has stated that they will automatically install peer dependencies, all together. Therefore, now you don't want to install your peer dependencies manually.

You can install npm v7.0 using this command,

npm install -g npm@7

Learn more about npm v7.0 from this blog post, published by the Github Blog.

How to Sign an Already Compiled Apk

create a key using

keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

then sign the apk using :

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore my_application.apk alias_name

check here for more info

SQL Server Regular expressions in T-SQL

If anybody is interested in using regex with CLR here is a solution. The function below (C# .net 4.5) returns a 1 if the pattern is matched and a 0 if the pattern is not matched. I use it to tag lines in sub queries. The SQLfunction attribute tells sql server that this method is the actual UDF that SQL server will use. Save the file as a dll in a place where you can access it from management studio.

// default using statements above
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Text.RegularExpressions;

namespace CLR_Functions
{   
    public class myFunctions
    {
        [SqlFunction]
        public static SqlInt16 RegexContain(SqlString text, SqlString pattern)
        {            
            SqlInt16 returnVal = 0;
            try
            {
                string myText = text.ToString();
                string myPattern = pattern.ToString();
                MatchCollection mc = Regex.Matches(myText, myPattern);
                if (mc.Count > 0)
                {
                    returnVal = 1;
                }
            }
            catch
            {
                returnVal = 0;
            }

            return returnVal;
        }
    }
}

In management studio import the dll file via programability -- assemblies -- new assembly

Then run this query:

CREATE FUNCTION RegexContain(@text NVARCHAR(50), @pattern NVARCHAR(50))
RETURNS smallint 
AS
EXTERNAL NAME CLR_Functions.[CLR_Functions.myFunctions].RegexContain

Then you should have complete access to the function via the database you stored the assembly in.

Then use in queries like so:

SELECT * 
FROM 
(
    SELECT
        DailyLog.Date,
        DailyLog.Researcher,
        DailyLog.team,
        DailyLog.field,
        DailyLog.EntityID,
        DailyLog.[From],
        DailyLog.[To],
        dbo.RegexContain(Researcher, '[\p{L}\s]+') as 'is null values'
    FROM [DailyOps].[dbo].[DailyLog]
) AS a
WHERE a.[is null values] = 0

How can I conditionally import an ES6 module?

No, you can't!

However, having bumped into that issue should make you rethink on how you organize your code.

Before ES6 modules, we had CommonJS modules which used the require() syntax. These modules were "dynamic", meaning that we could import new modules based on conditions in our code. - source: https://bitsofco.de/what-is-tree-shaking/

I guess one of the reasons they dropped that support on ES6 onward is the fact that compiling it would be very difficult or impossible.

Strange Jackson exception being thrown when serializing Hibernate object

It's not ideal, but you could disable Jackson's auto-discovery of JSON properties, using @JsonAutoDetect at the class level. This would prevent it from trying to handle the Javassist stuff (and failing).

This means that you then have to annotate each getter manually (with @JsonProperty), but that's not necessarily a bad thing, since it keeps things explicit.

Drawing circles with System.Drawing

With this code you can easily draw a circle... C# is great and easy my friend

public partial class Form1 : Form
{


public Form1()
    {
        InitializeComponent();
    }

  private void button1_Click(object sender, EventArgs e)
    {
        Graphics myGraphics = base.CreateGraphics();
        Pen myPen = new Pen(Color.Red);
        SolidBrush mySolidBrush = new SolidBrush(Color.Red);
        myGraphics.DrawEllipse(myPen, 50, 50, 150, 150);
    }
 }

Warning: X may be used uninitialized in this function

When you use Vector *one you are merely creating a pointer to the structure but there is no memory allocated to it.

Simply use one = (Vector *)malloc(sizeof(Vector)); to declare memory and instantiate it.

Sass Nesting for :hover does not work

For concatenating selectors together when nesting, you need to use the parent selector (&):

.class {
    margin:20px;
    &:hover {
        color:yellow;
    }
}

How do I kill this tomcat process in Terminal?

As others already noted, you have seen the grep process. If you want to restrict the output to tomcat itself, you have two alternatives

  • wrap the first searched character in a character class

    ps -ef | grep '[t]omcat'
    

    This searches for tomcat too, but misses the grep [t]omcat entry, because it isn't matched by [t]omcat.

  • use a custom output format with ps

    ps -e -o pid,comm | grep tomcat
    

    This shows only the pid and the name of the process without the process arguments. So, grep is listed as grep and not as grep tomcat.

print highest value in dict with key

The clue is to work with the dict's items (i.e. key-value pair tuples). Then by using the second element of the item as the max key (as opposed to the dict key) you can easily extract the highest value and its associated key.

 mydict = {'A':4,'B':10,'C':0,'D':87}
>>> max(mydict.items(), key=lambda k: k[1])
('D', 87)
>>> min(mydict.items(), key=lambda k: k[1])
('C', 0)

Use async await with Array.map

Solution below to process all elements of the array in parallel, asynchronously AND preserve the order:

const arr = [1, 2, 3, 4, 5, 6, 7, 8];
const randomDelay = () => new Promise(resolve => setTimeout(resolve, Math.random() * 1000));

const calc = async n => {
  await randomDelay();
  return n * 2;
};

const asyncFunc = async () => {
  const unresolvedPromises = arr.map(n => calc(n));
  const results = await Promise.all(unresolvedPromises);
};

asyncFunc();

Also codepen.

Notice we only "await" for Promise.all. We call calc without "await" multiple times, and we collect an array of unresolved promises right away. Then Promise.all waits for resolution of all of them and returns an array with the resolved values in order.

How to add line break for UILabel?

In my case also \n was not working, I fixed issue by keeping number of lines to 0 and copied and pasted the text with new line itself for example instead of Hello \n World i pasted

Hello

World

in the interface builder.

LINQ Contains Case Insensitive

Use String.Equals Method

public IQueryable<FACILITY_ITEM> GetFacilityItemRootByDescription(string description)
{
    return this.ObjectContext.FACILITY_ITEM
           .Where(fi => fi.DESCRIPTION
           .Equals(description, StringComparison.OrdinalIgnoreCase));
}

Combine two (or more) PDF's

I know a lot of people have recommended PDF Sharp, however it doesn't look like that project has been updated since june of 2008. Further, source isn't available.

Personally, I've been playing with iTextSharp which has been pretty easy to work with.

How to set full calendar to a specific start date when it's initialized for the 1st time?

You should use the options 'year', 'month', and 'date' when initializing to specify the initial date value used by fullcalendar:

$('#calendar').fullCalendar({
 year: 2012,
 month: 4,
 date: 25
});  // This will initialize for May 25th, 2012.

See the function setYMD(date,y,m,d) in the fullcalendar.js file; note that the JavaScript setMonth, setDate, and setFullYear functions are used, so your month value needs to be 0-based (Jan is 0).

UPDATE: As others have noted in the comments, the correct way now (V3 as of writing this edit) is to initialize the defaultDate property to a value that is

anything the Moment constructor accepts, including an ISO8601 date string like "2014-02-01"

as it uses Moment.js. Documentation here.

Updated example:

$('#calendar').fullCalendar({
    defaultDate: "2012-05-25"
});  // This will initialize for May 25th, 2012.

Attempt to present UIViewController on UIViewController whose view is not in the window hierarchy

Where are you calling this method from? I had an issue where I was attempting to present a modal view controller within the viewDidLoad method. The solution for me was to move this call to the viewDidAppear: method.

My presumption is that the view controller's view is not in the window's view hierarchy at the point that it has been loaded (when the viewDidLoad message is sent), but it is in the window hierarchy after it has been presented (when the viewDidAppear: message is sent).


Caution

If you do make a call to presentViewController:animated:completion: in the viewDidAppear: you may run into an issue whereby the modal view controller is always being presented whenever the view controller's view appears (which makes sense!) and so the modal view controller being presented will never go away...

Maybe this isn't the best place to present the modal view controller, or perhaps some additional state needs to be kept which allows the presenting view controller to decide whether or not it should present the modal view controller immediately.

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

It's really simple, just download the latest toolkit from Codeplex and add the extracted AjaxControlToolkit.dll to your toolbox in Visual Studio by right clicking the toolbox and selecting 'choose items'. You will then have the controls in your Visual STudio toolbox and using them is just a matter of dragging and dropping them onto your form, of course don't forget to add a asp:ScriptManager to every page that uses controls from the toolkit, or optionally include it in your master page only and your content pages will inherit the script manager.

What is the difference between up-casting and down-casting with respect to class variable

Maybe this table helps. Calling the callme() method of class Parent or class Child. As a principle:

UPCASTING --> Hiding

DOWNCASTING --> Revealing

enter image description here

enter image description here

enter image description here

HttpContext.Current.Session is null when routing requests

None of these solutions worked for me. I added the following method into global.asax.cs then Session was not null:

protected void Application_PostAuthorizeRequest()
{
    HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}

Failed to load AppCompat ActionBar with unknown error in android studio

I also had this problem with implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'.

The solution for me was to go File -> Invalidate Caches / Restart -> Invalidate -> Close Project -> Remove project from project window -> Open Project (from project window).

How to set max width of an image in CSS

Try this

 div#ImageContainer { width: 600px; }
 #ImageContainer img{ max-width: 600px}

Create hyperlink to another sheet

This is the code I use for creating an index sheet.

Sub CreateIndexSheet()
    Dim wSheet As Worksheet
    ActiveWorkbook.Sheets.Add(Before:=Worksheets(1)).Name = "Contents" 'Call whatever you like
    Range("A1").Select
    Application.ScreenUpdating = False 'Prevents seeing all the flashing as it updates the sheet
    For Each wSheet In Worksheets
        ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="", SubAddress:="'" & wSheet.Name & "'" & "!A1", TextToDisplay:=wSheet.Name
        ActiveCell.Offset(1, 0).Select 'Moves down a row
    Next
    Range("A1").EntireColumn.AutoFit
    Range("A1").EntireRow.Delete 'Remove content sheet from content list
    Application.ScreenUpdating = True
End Sub

c++ bool question

Yes that is correct. "Boolean variables only have two possible values: true (1) and false (0)." cpp tutorial on boolean values

Extract Google Drive zip from Google colab notebook

in my idea, you must go to a certain path for example:

from google.colab import drive drive.mount('/content/drive/') cd drive/MyDrive/f/

then :

!apt install unzip !unzip zip_folder.zip -d unzip_folder enter image description here

HttpServletRequest get JSON POST data

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

request.getParameter("cmd");

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

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

BufferedReader reader = request.getReader();

Json post processing example (uses org.json package )

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

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

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

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

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

The gdi32 library is already installed on your computer, few programs will run without it. Your compiler will (if installed properly) normally come with an import library, which is what the linker uses to make a binding between your program and the file in the system. (In the unlikely case that your compiler does not come with import libraries for the system libs, you will need to download the Microsoft Windows Platform SDK.)

To link with gdi32:

enter image description here

This will reliably work with MinGW-gcc for all system libraries (it should work if you use any other compiler too, but I can't talk about things I've not tried). You can also write the library's full name, but writing libgdi32.a has no advantage over gdi32 other than being more type work.
If it does not work for some reason, you may have to provide a different name (for example the library is named gdi32.lib for MSVC).

For libraries in some odd locations or project subfolders, you will need to provide a proper pathname (click on the "..." button for a file select dialog).

.ps1 cannot be loaded because the execution of scripts is disabled on this system

I had a similar issue and noted that the default cmd on Windows Server 2012 was running the x64 one.

For Windows 7, Windows 8, Windows Server 2008 R2 or Windows Server 2012, run the following commands as Administrator:

x86

Open C:\Windows\SysWOW64\cmd.exe Run the command: powershell Set-ExecutionPolicy RemoteSigned

x64

Open C:\Windows\system32\cmd.exe Run the command powershell Set-ExecutionPolicy RemoteSigned

You can check mode using

In CMD: echo %PROCESSOR_ARCHITECTURE% In Powershell: [Environment]::Is64BitProcess

I hope this help you.

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

make clean removes any intermediate or output files from your source / build tree. However, it only affects the source / build tree; it does not touch the rest of the filesystem and so will not remove previously installed software.

If you're lucky, running make uninstall will work. It's up to the library's authors to provide that, however; some authors provide an uninstall target, others don't.

If you're not lucky, you'll have to manually uninstall it. Running make -n install can be helpful, since it will show the steps that the software would take to install itself but won't actually do anything. You can then manually reverse those steps.

How to show first commit by 'git log'?

I found that:

git log --reverse

shows commits from start.

Replace non-ASCII characters with a single space

When we use the ascii() it escapes the non-ascii characters and it doesn't change ascii characters correctly. So my main thought is, it doesn't change the ASCII characters, so I am iterating through the string and checking if the character is changed. If it changed then replacing it with the replacer, what you give.
For example: ' '(a single space) or '?' (with a question mark).

def remove(x, replacer):

     for i in x:
        if f"'{i}'" == ascii(i):
            pass
        else:
            x=x.replace(i,replacer)
     return x
remove('hái',' ')

Result: "h i" (with single space between).

Syntax : remove(str,non_ascii_replacer)
str = Here you will give the string you want to work with.
non_ascii_replacer = Here you will give the replacer which you want to replace all the non ASCII characters with.

Search for a particular string in Oracle clob column

Below code can be used to search a particular string in Oracle clob column

select *  
from RLOS_BINARY_BP
where dbms_lob.instr(DED_ENQ_XML,'2003960067') > 0;

where RLOS_BINARY_BP is table name and DED_ENQ_XML is column name (with datatype as CLOB) of Oracle database.

How do I check if the mouse is over an element in jQuery?

I see timeouts used for this a lot, but in the context of an event, can't you look at coordinates, like this?:

function areXYInside(e){  
        var w=e.target.offsetWidth;
        var h=e.target.offsetHeight;
        var x=e.offsetX;
        var y=e.offsetY;
        return !(x<0 || x>=w || y<0 || y>=h);
}

Depending on context, you may need to make sure (this==e.target) before calling areXYInside(e).

fyi- I'm looking at using this approach inside a dragLeave handler, in order to confirm that the dragLeave event wasn't triggered by going into a child element. If you don't somehow check that you're still inside the parent element, you might mistakenly take action that's meant only for when you truly leave the parent.

EDIT: this is a nice idea, but does not work consistently enough. Perhaps with some small tweaks.

How do I abort the execution of a Python script?

You can either use:

import sys
sys.exit(...)

or:

raise SystemExit(...)

The optional parameter can be an exit code or an error message. Both methods are identical. I used to prefer sys.exit, but I've lately switched to raising SystemExit, because it seems to stand out better among the rest of the code (due to the raise keyword).

Formula to check if string is empty in Crystal Reports

If IsNull({TABLE.FIELD1}) then "NULL" +',' + {TABLE.FIELD2} else {TABLE.FIELD1} + ', ' + {TABLE.FIELD2}

Here I put NULL as string to display the string value NULL in place of the null value in the data field. Hope you understand.

Oracle: not a valid month

1.

To_Date(To_Char(MaxDate, 'DD/MM/YYYY')) = REP_DATE

is causing the issue. when you use to_date without the time format, oracle will use the current sessions NLS format to convert, which in your case might not be "DD/MM/YYYY". Check this...

SQL> select sysdate from dual;

SYSDATE
---------
26-SEP-12

Which means my session's setting is DD-Mon-YY

SQL> select to_char(sysdate,'MM/DD/YYYY') from dual;

TO_CHAR(SY
----------
09/26/2012


SQL> select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual;
select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual
               *
ERROR at line 1:
ORA-01843: not a valid month

SQL> select to_date(to_char(sysdate,'MM/DD/YYYY'),'MM/DD/YYYY') from dual;

TO_DATE(T
---------
26-SEP-12

2.

More importantly, Why are you converting to char and then to date, instead of directly comparing

MaxDate = REP_DATE

If you want to ignore the time component in MaxDate before comparision, you should use..

trunc(MaxDate ) = rep_date

instead.

==Update : based on updated question.

Rep_Date = 01/04/2009 Rep_Time = 01/01/1753 13:00:00

I think the problem is more complex. if rep_time is intended to be only time, then you cannot store it in the database as a date. It would have to be a string or date to time interval or numerically as seconds (thanks to Alex, see this) . If possible, I would suggest using one column rep_date that has both the date and time and compare it to the max date column directly.

If it is a running system and you have no control over repdate, you could try this.

trunc(rep_date) = trunc(maxdate) and 
to_char(rep_date,'HH24:MI:SS') = to_char(maxdate,'HH24:MI:SS')

Either way, the time is being stored incorrectly (as you can tell from the year 1753) and there could be other issues going forward.

How to do multiline shell script in Ansible

https://support.ansible.com/hc/en-us/articles/201957837-How-do-I-split-an-action-into-a-multi-line-format-

mentions YAML line continuations.

As an example (tried with ansible 2.0.0.2):

---
- hosts: all
  tasks:
    - name: multiline shell command
      shell: >
        ls --color
        /home
      register: stdout

    - name: debug output
      debug: msg={{ stdout }}

The shell command is collapsed into a single line, as in ls --color /home

How to scroll to an element inside a div?

There are two facts :

1) Component scrollIntoView is not supported by safari.

2) JS framework jQuery can do the job like this:

parent = 'some parent div has css position==="fixed"' || 'html, body';

$(parent).animate({scrollTop: $(child).offset().top}, duration)

System.Net.WebException: The operation has timed out

It means what it says. The operation took too long to complete.

BTW, look at WebRequest.Timeout and you'll see that you've set your timeout for 1/5 second.

How to justify a single flexbox item (override justify-content)

For those situations where width of the items you do want to flex-end is known, you can set their flex to "0 0 ##px" and set the item you want to flex-start with flex:1

This will cause the pseudo flex-start item to fill the container, just format it to text-align:left or whatever.

Can I specify multiple users for myself in .gitconfig?

Or you can add following information in your local .git/config file

[user]  
    name = Your Name
    email = [email protected]

Chrome desktop notification example

Check the design and API specification (it's still a draft) or check the source from (page no longer available) for a simple example: It's mainly a call to window.webkitNotifications.createNotification.

If you want a more robust example (you're trying to create your own Google Chrome's extension, and would like to know how to deal with permissions, local storage and such), check out Gmail Notifier Extension: download the crx file instead of installing it, unzip it and read its source code.

How do I return a string from a regex match in python?

Considering there might be several img tags I would recommend re.findall:

import re

with open("sample.txt", 'r') as f_in, open('writetest.txt', 'w') as f_out:
    for line in f_in:
        for img in re.findall('<img[^>]+>', line):
            print >> f_out, "yo it's a {}".format(img)

Select folder dialog WPF

Add The Windows API Code Pack-Shell to your project

using Microsoft.WindowsAPICodePack.Dialogs;

...

var dialog = new CommonOpenFileDialog();
dialog.IsFolderPicker = true;
CommonFileDialogResult result = dialog.ShowDialog();

Failed to load the JNI shared Library (JDK)

I have experienced all of the Eclipse errors and this is one of them. The problem is Eclipse 64-bit version. Download the 32-bit version and launch it.

Fastest way of finding differences between two files in unix?

You could try..

comm -13 <(sort file1) <(sort file2) > file3

or

grep -Fxvf file1 file2 > file3

or

diff file1 file2 | grep "<" | sed 's/^<//g'  > file3

or

join -v 2 <(sort file1) <(sort file2) > file3

How to generate xsd from wsdl

Once I found an xsd link on the top of the wsdl. Like this wsdl example from the web, you can see a link xsd1. The server has to be running to see it.

<?xml version="1.0"?>
<definitions name="StockQuote"
             targetNamespace="http://example.com/stockquote.wsdl"
             xmlns:tns="http://example.com/stockquote.wsdl"
             xmlns:xsd1="http://example.com/stockquote.xsd"
             xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
             xmlns="http://schemas.xmlsoap.org/wsdl/">

Formatting numbers (decimal places, thousands separators, etc) with CSS

The CSS working group has publish a Draft on Content Formatting in 2008. But nothing new right now.

iOS 7: UITableView shows under status bar

I found the easiest way to do this, especially if you're adding your table view inside of tab bar is to first add a view and then add the table view inside that view. This gives you the top margin guides you're looking for.

enter image description here

AngularJS passing data to $http.get request

You can pass params directly to $http.get() The following works fine

$http.get(user.details_path, {
    params: { user_id: user.id }
});

nvm keeps "forgetting" node in new terminal session

run this after you installed any version,

n=$(which node);n=${n%/bin/node}; chmod -R 755 $n/bin/*; sudo cp -r $n/{bin,lib,share} /usr/local

This command is copying whatever version of node you have active via nvm into the /usr/local/ directory and setting the permissions so that all users can access them.

How to delete multiple rows in SQL where id = (x to y)

You can use BETWEEN:

DELETE FROM table
where id between 163 and 265

PHP compare time

Simple way to compare time is :

$time = date('H:i:s',strtotime("11 PM"));
if($time < date('H:i:s')){
     // your code
}

How to deploy a war file in JBoss AS 7?

Just copy war file to standalone/deployments/ folder, it should deploy it automatically. It'll also create your_app_name.deployed file, when your application is deployed. Also be sure that you start server with bin/standalone.sh script.

How to keep a Python script output window open?

You can just write

input()

at the end of your code

therefore when you run you script it will wait for you to enter something

{ENTER for example}

TypeError: string indices must be integers, not str // working with dict

Actually I think that more general approach to loop through dictionary is to use iteritems():

# get tuples of term, courses
for term, term_courses in courses.iteritems():
    # get tuples of course number, info
    for course, info in term_courses.iteritems():
        # loop through info
        for k, v in info.iteritems():
            print k, v

output:

assistant Peter C.
prereq cs101
...
name Programming a Robotic Car
teacher Sebastian

Or, as Matthias mentioned in comments, if you don't need keys, you can just use itervalues():

for term_courses in courses.itervalues():
    for info in term_courses.itervalues():
        for k, v in info.iteritems():
            print k, v

How do I install cURL on cygwin?

I just ran into this.

If you're not seeing curl in the list (see ibaralf's screenshot), then you may have out-of-date cygwin sources. In one of the screens in cygwin's setup.exe wizard, you have the option to "Install from Internet" or "Install from Local Directory". If you have the "Install from Local Directory" option enabled, then you may not see curl in the list. Switch to "Install from Internet" and select a mirror and then you should see curl.

IllegalArgumentException or NullPointerException for a null parameter?

If it's a "setter", or somewhere I'm getting a member to use later, I tend to use IllegalArgumentException.

If it's something I'm going to use (dereference) right now in the method, I throw a NullPointerException proactively. I like this better than letting the runtime do it, because I can provide a helpful message (seems like the runtime could do this too, but that's a rant for another day).

If I'm overriding a method, I use whatever the overridden method uses.

Share link on Google+

<meta property="og:title" content="Ali Umair"/>
<meta property="og:description" content="Ali UMair is a web developer"/><meta property="og:image" content="../image" />

<a target="_blank" href="https://plus.google.com/share?url=<? echo urlencode('http://www..'); ?>"><img src="../gplus-black_icon.png" alt="" /></a>

this code will work with image text and description please put meta into head tag

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

The key difference: NSMutableDictionary can be modified in place, NSDictionary cannot. This is true for all the other NSMutable* classes in Cocoa. NSMutableDictionary is a subclass of NSDictionary, so everything you can do with NSDictionary you can do with both. However, NSMutableDictionary also adds complementary methods to modify things in place, such as the method setObject:forKey:.

You can convert between the two like this:

NSMutableDictionary *mutable = [[dict mutableCopy] autorelease];
NSDictionary *dict = [[mutable copy] autorelease]; 

Presumably you want to store data by writing it to a file. NSDictionary has a method to do this (which also works with NSMutableDictionary):

BOOL success = [dict writeToFile:@"/file/path" atomically:YES];

To read a dictionary from a file, there's a corresponding method:

NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:@"/file/path"];

If you want to read the file as an NSMutableDictionary, simply use:

NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithContentsOfFile:@"/file/path"];

How to access JSON decoded array in PHP

$data = json_decode(...);
$firstId = $data[0]["id"];
$secondSeatNo = $data[1]["seat_no"];

Just like this :)

Select multiple columns by labels in pandas

Name- or Label-Based (using regular expression syntax)

df.filter(regex='[A-CEG-I]')   # does NOT depend on the column order

Note that any regular expression is allowed here, so this approach can be very general. E.g. if you wanted all columns starting with a capital or lowercase "A" you could use: df.filter(regex='^[Aa]')

Location-Based (depends on column order)

df[ list(df.loc[:,'A':'C']) + ['E'] + list(df.loc[:,'G':'I']) ]

Note that unlike the label-based method, this only works if your columns are alphabetically sorted. This is not necessarily a problem, however. For example, if your columns go ['A','C','B'], then you could replace 'A':'C' above with 'A':'B'.

The Long Way

And for completeness, you always have the option shown by @Magdalena of simply listing each column individually, although it could be much more verbose as the number of columns increases:

df[['A','B','C','E','G','H','I']]   # does NOT depend on the column order

Results for any of the above methods

          A         B         C         E         G         H         I
0 -0.814688 -1.060864 -0.008088  2.697203 -0.763874  1.793213 -0.019520
1  0.549824  0.269340  0.405570 -0.406695 -0.536304 -1.231051  0.058018
2  0.879230 -0.666814  1.305835  0.167621 -1.100355  0.391133  0.317467

Building a fat jar using maven

An alternative is to use the maven shade plugin to build an uber-jar.

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version> Your Version Here </version>
    <configuration>
            <!-- put your configurations here -->
    </configuration>
    <executions>
            <execution>
                    <phase>package</phase>
                    <goals>
                            <goal>shade</goal>
                    </goals>
            </execution>
    </executions>
</plugin>

ElasticSearch - Return Unique Values

if you want to get the first document for each language field unique value, you can do this:

{
 "query": {
    "match_all": {
    }
  },
  "collapse": {
    "field": "language.keyword",
    "inner_hits": {
    "name": "latest",
      "size": 1
    }
  }
}

Subscripts in plots in R

See ?expression

plot(1:10,main=expression("This is a subscript "[2]))

enter image description here

How to check whether an array is empty using PHP?

if you are to check the array content you may use:

$arr = array();

if(!empty($arr)){
  echo "not empty";
}
else 
{
  echo "empty";
}

see here: http://codepad.org/EORE4k7v

How to do scanf for single char in C

Provides a space before %c conversion specifier so that compiler will ignore white spaces. The program may be written as below:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char ch;
    printf("Enter one char");
    scanf(" %c", &ch); /*Space is given before %c*/
    printf("%c\n",ch);
return 0;
}

How do you get the path to the Laravel Storage folder?

For Laravel 5.x, use $storage_path = storage_path().

From the Laravel 5.0 docs:

storage_path

Get the fully qualified path to the storage directory.

Note also that, for Laravel 5.1 and above, per the Laravel 5.1 docs:

You may also use the storage_path function to generate a fully qualified path to a given file relative to the storage directory:

$path = storage_path('app/file.txt');

How to add items to a combobox in a form in excel VBA?

The method I prefer assigns an array of data to the combobox. Click on the body of your userform and change the "Click" event to "Initialize". Now the combobox will fill upon the initializing of the userform. I hope this helps.

Sub UserForm_Initialize()
  ComboBox1.List = Array("1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010")
End Sub

How to parse a JSON string to an array using Jackson

I sorted this problem by verifying the json on JSONLint.com and then using Jackson. Below is the code for the same.

 Main Class:-

String jsonStr = "[{\r\n" + "       \"name\": \"John\",\r\n" + "        \"city\": \"Berlin\",\r\n"
                + "         \"cars\": [\r\n" + "            \"FIAT\",\r\n" + "          \"Toyata\"\r\n"
                + "     ],\r\n" + "     \"job\": \"Teacher\"\r\n" + "   },\r\n" + " {\r\n"
                + "     \"name\": \"Mark\",\r\n" + "        \"city\": \"Oslo\",\r\n" + "        \"cars\": [\r\n"
                + "         \"VW\",\r\n" + "            \"Toyata\"\r\n" + "     ],\r\n"
                + "     \"job\": \"Doctor\"\r\n" + "    }\r\n" + "]";

        ObjectMapper mapper = new ObjectMapper();

        MyPojo jsonObj[] = mapper.readValue(jsonStr, MyPojo[].class);

        for (MyPojo itr : jsonObj) {

            System.out.println("Val of getName is: " + itr.getName());
            System.out.println("Val of getCity is: " + itr.getCity());
            System.out.println("Val of getJob is: " + itr.getJob());
            System.out.println("Val of getCars is: " + itr.getCars() + "\n");

        }

POJO:

public class MyPojo {

private List<String> cars = new ArrayList<String>();

private String name;

private String job;

private String city;

public List<String> getCars() {
    return cars;
}

public void setCars(List<String> cars) {
    this.cars = cars;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getJob() {
    return job;
}

public void setJob(String job) {
    this.job = job;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
} }

  RESULT:-
         Val of getName is: John
         Val of getCity is: Berlin
         Val of getJob is: Teacher
         Val of getCars is: [FIAT, Toyata]

          Val of getName is: Mark
          Val of getCity is: Oslo
          Val of getJob is: Doctor
          Val of getCars is: [VW, Toyata]

Add line break to ::after or ::before pseudo-element content

The content property states:

Authors may include newlines in the generated content by writing the "\A" escape sequence in one of the strings after the 'content' property. This inserted line break is still subject to the 'white-space' property. See "Strings" and "Characters and case" for more information on the "\A" escape sequence.

So you can use:

#headerAgentInfoDetailsPhone:after {
  content:"Office: XXXXX \A Mobile: YYYYY ";
  white-space: pre; /* or pre-wrap */
}

http://jsfiddle.net/XkNxs/

When escaping arbitrary strings, however, it's advisable to use \00000a instead of \A, because any number or [a-f] character followed by the new line may give unpredictable results:

function addTextToStyle(id, text) {
  return `#${id}::after { content: "${text.replace(/"/g, '\\"').replace(/\n/g, '\\00000a')} }"`;
}

How to fix the height of a <div> element?

You can also use min-height and max-height. It was very useful for me

Simple CSS Animation Loop – Fading In & Out "Loading" Text

To make more than one element fade in/out sequentially such as 5 elements fade each 4s,

1- make unique animation for each element with animation-duration equal to [ 4s (duration for each element) * 5 (number of elements) ] = 20s

animation-name: anim1 , anim2, anim3 ... 
animation-duration : 20s, 20s, 20s ... 

2- get animation keyframe for each element.

100% (keyframes percentage) / 5 (elements) = 20% (frame for each element)

3- define starting and ending point for each animation:

each animation has 20% frame length and @keyframes percentage always starts from 0%, so first animation will start from 0% and end in his frame(20%), and each next animation will starts from previous animation ending point and end when it reach his frame (+20% ),

@keyframes animation1 { 0% {}, 20% {}}
@keyframes animation2 { 20% {}, 40% {}}
@keyframes animation3 { 40% {}, 60% {}}
and so on

now we need to make each animation fade in from 0 to 1 opacity and fade out from 1 to 0,

so we will add another 2 points (steps) for each animation after starting and before ending point to handle the full opacity(1)

enter image description here

http://codepen.io/El-Oz/pen/WwPPZQ

.slide1 {
    animation: fadeInOut1 24s ease reverse forwards infinite
}

.slide2 {
    animation: fadeInOut2 24s ease reverse forwards infinite
}

.slide3 {
    animation: fadeInOut3 24s ease reverse forwards infinite
}

.slide4 {
    animation: fadeInOut4 24s ease reverse forwards infinite
}

.slide5 {
    animation: fadeInOut5 24s ease reverse forwards infinite
}

.slide6 {
    animation: fadeInOut6 24s ease reverse forwards infinite
}

@keyframes fadeInOut1 {
    0% { opacity: 0 }
    1% { opacity: 1 }
    14% {opacity: 1 }
    16% { opacity: 0 }
}

@keyframes fadeInOut2 {
    0% { opacity: 0 }
    14% {opacity: 0 }
    16% { opacity: 1 }
    30% { opacity: 1 }
    33% { opacity: 0 }
}

@keyframes fadeInOut3 {
    0% { opacity: 0 }
    30% {opacity: 0 }
    33% {opacity: 1 }
    46% { opacity: 1 }
    48% { opacity: 0 }
}

@keyframes fadeInOut4 {
    0% { opacity: 0 }
    46% { opacity: 0 }
    48% { opacity: 1 }
    64% { opacity: 1 }
    65% { opacity: 0 }
}

@keyframes fadeInOut5 {
    0% { opacity: 0 }
    64% { opacity: 0 }
    66% { opacity: 1 }
    80% { opacity: 1 }
    83% { opacity: 0 }
}

@keyframes fadeInOut6 {
    80% { opacity: 0 }
    83% { opacity: 1 }
    99% { opacity: 1 }
    100% { opacity: 0 }
}

Which variable size to use (db, dw, dd) with x86 assembly?

Quick review,

  • DB - Define Byte. 8 bits
  • DW - Define Word. Generally 2 bytes on a typical x86 32-bit system
  • DD - Define double word. Generally 4 bytes on a typical x86 32-bit system

From x86 assembly tutorial,

The pop instruction removes the 4-byte data element from the top of the hardware-supported stack into the specified operand (i.e. register or memory location). It first moves the 4 bytes located at memory location [SP] into the specified register or memory location, and then increments SP by 4.

Your num is 1 byte. Try declaring it with DD so that it becomes 4 bytes and matches with pop semantics.

bash: Bad Substitution

The default shell (/bin/sh) under Ubuntu points to dash, not bash.

me@pc:~$ readlink -f $(which sh)
/bin/dash

So if you chmod +x your_script_file.sh and then run it with ./your_script_file.sh, or if you run it with bash your_script_file.sh, it should work fine.

Running it with sh your_script_file.sh will not work because the hashbang line will be ignored and the script will be interpreted by dash, which does not support that string substitution syntax.

Send and receive messages through NSNotificationCenter in Objective-C?

if you're using NSNotificationCenter for updating your view, don't forget to send it from the main thread by calling dispatch_async:

dispatch_async(dispatch_get_main_queue(),^{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"my_notification" object:nil];
});

Using an integer as a key in an associative array in JavaScript

As people say, JavaScript will convert a string of number to integer, so it is not possible to use directly on an associative array, but objects will work for you in similar way I think.

You can create your object:

var object = {};

And add the values as array works:

object[1] = value;
object[2] = value;

This will give you:

{
  '1': value,
  '2': value
}

After that you can access it like an array in other languages getting the key:

for(key in object)
{
   value = object[key] ;
}

I have tested and works.

Correct MIME Type for favicon.ico?

When you're serving an .ico file to be used as a favicon, it doesn't matter. All major browsers recognize both mime types correctly. So you could put:

<!-- IE -->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<!-- other browsers -->
<link rel="icon" type="image/x-icon" href="favicon.ico" />

or the same with image/vnd.microsoft.icon, and it will work with all browsers.

Note: There is no IANA specification for the MIME-type image/x-icon, so it does appear that it is a little more unofficial than image/vnd.microsoft.icon.

The only case in which there is a difference is if you were trying to use an .ico file in an <img> tag (which is pretty unusual). Based on previous testing, some browsers would only display .ico files as images when they were served with the MIME-type image/x-icon. More recent tests show: Chromium, Firefox and Edge are fine with both content types, IE11 is not. If you can, just avoid using ico files as images, use png.

How to specify a multi-line shell variable?

read does not export the variable (which is a good thing most of the time). Here's an alternative which can be exported in one command, can preserve or discard linefeeds, and allows mixing of quoting-styles as needed. Works for bash and zsh.

oneLine=$(printf %s \
    a   \
    " b "   \
    $'\tc\t'    \
    'd '    \
)
multiLine=$(printf '%s\n' \
    a   \
    " b "   \
    $'\tc\t'    \
    'd '    \
)

I admit the need for quoting makes this ugly for SQL, but it answers the (more generally expressed) question in the title.

I use it like this

export LS_COLORS=$(printf %s    \
    ':*rc=36:*.ini=36:*.inf=36:*.cfg=36:*~=33:*.bak=33:*$=33'   \
    ...
    ':bd=40;33;1:cd=40;33;1:or=1;31:mi=31:ex=00')

in a file sourced from both my .bashrc and .zshrc.

WooCommerce - get category for product page

I literally striped out this line of code from content-single-popup.php located in woocommerce folder in my theme directory.

global $product; 
echo $product->get_categories( ', ', ' ' . _n( ' ', '  ', $cat_count, 'woocommerce' ) . ' ', ' ' );

Since my theme that I am working on has integrated woocommerce in it, this was my solution.

How do I link to Google Maps with a particular longitude and latitude?

To open the google maps app in android:-

geo:<lat>,<lng>?z=<zoom>

open app with marker for give location:-

geo:<lat>,<lng>?q=<lat>,<lng>(Label,Name)

open google map in ios:-

comgooglemaps://?q=<lat>,<lng>

open google maps in browser with following parameters:-

http://maps.google.com/maps?z=12&t=m&q=<lat>,<lng>
  • z is the zoom level (1-21)
  • t is the map type ("m" map, "k" satellite, "h" hybrid, "p" terrain, "e" GoogleEarth)
  • q is the search query

The ScriptManager must appear before any controls that need it

If you are using microsoft ajax on your page you need the script manager control added to your master page or the page that needs it. It Manages ASP.NET Ajax script libraries and script files, partial-page rendering, and client proxy class generation for Web and application services

<asp:ScriptManager ID="ScriptManger1" runat="Server">
</asp:ScriptManager>

The full usage

<asp:ScriptManager
    AllowCustomErrorsRedirect="True|False"
    AsyncPostBackErrorMessage="string"
    AsyncPostBackTimeout="integer"
    AuthenticationService-Path="uri"
    EnablePageMethods="True|False"
    EnablePartialRendering="True|False"
    EnableScriptGlobalization="True|False"
    EnableScriptLocalization="True|False"
    EnableTheming="True|False"
    EnableViewState="True|False"
    ID="string"
    LoadScriptsBeforeUI="True|False"
    OnAsyncPostBackError="AsyncPostBackError event handler"
    OnDataBinding="DataBinding event handler"
    OnDisposed="Disposed event handler"
    OnInit="Init event handler"
    OnLoad="Load event handler"
    OnPreRender="PreRender event handler"
    OnResolveScriptReference="ResolveScriptReference event handler"
    OnUnload="Unload event handler"
    ProfileService-LoadProperties="string"
    ProfileService-Path="uri"
    RoleService-LoadRoles="True|False"
    RoleService-Path="uri"
    runat="server"
    ScriptMode="Auto|Inherit|Debug|Release"
    ScriptPath="string"
    SkinID="string"
    SupportsPartialRendering="True|False"
    Visible="True|False">
        <AuthenticationService
            Path="uri" />
        <ProfileService
            LoadProperties="string"
            Path="uri" />
        <RoleService
            LoadRoles="True|False"
            Path="uri" />
        <Scripts>
            <asp:ScriptReference
                Assembly="string"
                IgnoreScriptPath="True|False"
                Name="string"
                NotifyScriptLoaded="True|False"
                Path="string"
                ResourceUICultures="string"
                ScriptMode="Auto|Debug|Inherit|Release" />
        </Scripts>
        <Services>
            <asp:ServiceReference
                InlineScript="True|False"
                Path="string" />
        </Services>
</asp:ScriptManager>

HTML/Javascript Button Click Counter

Through this code, you can get click count on a button.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Button</title>
    <link rel="stylesheet" type="text/css" href="css/button.css">
</head>
<body>
    <script src="js/button.js" type="text/javascript"></script>

    <button id="btn" class="btnst" onclick="myFunction()">0</button>
</body>
</html>
 ----------JAVASCRIPT----------
let count = 0;
function myFunction() {
  count+=1;
  document.getElementById("btn").innerHTML = count;

 }

How do I pass a datetime value as a URI parameter in asp.net mvc?

Split out the Year, Month, Day Hours and Mins

routes.MapRoute(
            "MyNewRoute",
            "{controller}/{action}/{Year}/{Month}/{Days}/{Hours}/{Mins}",
            new { controller="YourControllerName", action="YourActionName"}
        );

Use a cascading If Statement to Build up the datetime from the parameters passed into the Action

    ' Build up the date from the passed url or use the current date
    Dim tCurrentDate As DateTime = Nothing
    If Year.HasValue Then
        If Month.HasValue Then
            If Day.HasValue Then
                tCurrentDate = New Date(Year, Month, Day)
            Else
                tCurrentDate = New Date(Year, Month, 1)
            End If
        Else
            tCurrentDate = New Date(Year, 1, 1)
        End If
    Else
        tCurrentDate = StartOfThisWeek(Date.Now)
    End If

(Apologies for the vb.net but you get the idea :P)

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

This happens when saving an object when Hibernate thinks it needs to save an object that is associated with the one you are saving.

I had this problem and did not want to save changes to the referenced object so I wanted the cascade type to be NONE.

The trick is to ensure that the ID and VERSION in the referenced object is set so that Hibernate does not think that the referenced object is a new object that needs saving. This worked for me.

Look through all of the relationships in the class you are saving to work out the associated objects (and the associated objects of the associated objects) and ensure that the ID and VERSION is set in all objects of the object tree.

python 2 instead of python 3 as the (temporary) default python?

You could use alias python="/usr/bin/python2.7":

bash-3.2$ alias
bash-3.2$ python
Python 2.7.6 (v2.7.6:3a1db0d2747e, Nov 10 2013, 00:42:54) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> ^D
bash-3.2$ alias python="/usr/bin/python3.3"
bash-3.2$ python
Python 3.3.3 (v3.3.3:c3896275c0f6, Nov 16 2013, 23:39:35) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> 

Get value of multiselect box using jQuery or pure JS

var data=[];
var $el=$("#my-select");
$el.find('option:selected').each(function(){
    data.push({value:$(this).val(),text:$(this).text()});
});
console.log(data)

How do you print in Sublime Text 2

UPDATE 2016: Somewhere between July 2015 and January 2016 the printing feature request that I wrote about in 2014 was removed. The original answer is below, with the relevant links changed to the latest working versions in the Web Archive:

Original 2014 Answer

Printing in Sublime Text is a feature that has been requested for about 4 years (as of 2014), with 1600+ supporting votes and 160+ comments in the discussion below. For something around 6000 feature requests this is in the top 5.

See the original, still open, feature request:

enter image description here

Judging from the feature request (still open with no official answer) it seems unlikely that printing will ever get implemented in version 3 (as others have suggested) or in any version at all.

The discussion below this feature request may give some insight on why printing is not supported and whether or not it has a chance to get supported in the future.

Maybe if more people vote or comment it will change in the future. (See Update 2016 below for an up-to-date list of feature requests)

Some workarounds were suggested, the most popular advices were to use some other editor for printing (eg. Brackets, Atom, gedit, Notepad++) or to use some 3rd party plugins that reportedly don't work well or at all.

In general there is a strong opposition to adding printing as a native feature of Sublime Text which for such a universal functionality among text editors seems surprising, but may nevertheless shed some light on this issue.

Meanwhile, there are many free editors that can print (in fact I cannot think of a single one that couldn't) so it is easy to use some other editor whenever a need for printing arises.

Update 2016

Since the feature request described above was removed (please comment if anyone knows why) here is an up-to-date list of some other places to find more info about printing in Sublime Text:

Since the original feature request #25170 was removed, you should vote and comment in the other feature requests about printing instead.