Programs & Examples On #Resolution

Questions about image resolution.

jQuery Screen Resolution Height Adjustment

Another example for vertically and horizontally centered div or any object(s):

 var obj = $("#divID");
 var halfsc = $(window).height()/2;
 var halfh = $(obj).height() / 2; 

 var halfscrn = screen.width/2;
 var halfobj =$(obj).width() / 2; 

 var goRight =  halfscrn - halfobj ;
 var goBottom = halfsc - halfh;

 $(obj).css({marginLeft: goRight }).css({marginTop: goBottom });

Recommended website resolution (width and height)?

I just took a sampling of screen resolutions from all of the client sites I have access to, this includes more then 20 sites in more then 8 industries here are the results:
alt text http://unkwndesign.com/so/percentScreenResolutions.png
Based on this I would say makes sure it looks good on 1024x768 as that is the majority here by a long shot. Also don't worry about the height as much, however try to avoid making most pages more then 1-2 printed pages at your default font size, most people wont read a page that long, and if a user installs a toolbar that takes up vertical space, my personal preference is that it's their problem, but I don't think it's to big of a deal.

*note the percentage adds up to 100.05% because of rounding.

How do I get monitor resolution in Python?

On Windows:

from win32api import GetSystemMetrics

print("Width =", GetSystemMetrics(0))
print("Height =", GetSystemMetrics(1))

If you are working with high resolution screen, make sure your python interpreter is HIGHDPIAWARE.

Based on this post.

Getting the screen resolution using PHP

Here is the Javascript Code: (index.php)

<script>
    var xhttp = new XMLHttpRequest();  
    xhttp.open("POST", "/sqldb.php", true);
    xhttp.send("screensize=",screen.width,screen.height);
</script>

Here is the PHP Code: (sqldb.php)

$data = $_POST['screensize'];
$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$statement = $pdo->prepare("UPDATE users SET screen= :screen WHERE id = $userid");
$statement->execute(array('screen' => $data));

I hope that you know how to get the $userid from the Session, and for that you need an Database with the Table called users, and an Table inside users called screen ;=) Regards KSP

Image resolution for new iPhone 6 and 6+, @3x support added?

UPDATE:

New link for the icons image size by apple.

https://developer.apple.com/ios/human-interface-guidelines/graphics/image-size-and-resolution/

enter image description here


Yes it's True here it is Apple provide Official documentation regarding icon's or image size

enter image description here

you have to set images for iPhone6 and iPhone6+

For iPhone 6:

750 x 1334 (@2x) for portrait

1334 x 750 (@2x) for landscape

For iPhone 6 Plus:

1242 x 2208 (@3x) for portrait

2208 x 1242 (@3x) for landscape

For more info regarding Images and it's resolution this is best ever helpful post

For setting images size for controls you can set 1x @2x and @3x like following:

enter image description here

Hide div if screen is smaller than a certain width

Is your logic not round the wrong way in that example, you have it hiding when the screen is bigger than 1024. Reverse the cases, make the none in to a block and vice versa.

Set background image according to screen resolution

Pure CSS approaches that work very well are discussed here. Two techniques are examined in particular and I personally prefer the second as it not CSS3 dependent, which suits my own needs better.

If most/all of your traffic has a CSS3 capable browser, the first method is quicker and cleaner to implement (copy/pasted by Mr. Zoidberg in another answer here for convenience, though I'd visit the source for further background on why it works).

An alternative method to CSS is to use the JavaScript library jQuery to detect resolution changes and adjust the image size accordingly. This article covers the jQuery technique and provides a live demo.

Supersized is a dedicated JavaScript library designed for static full screen images as well as full sized slideshows.

A good tip for full-screen images is to scale them with a correct ratio beforehand. I normally aim for a size of 1500x1000 when using supersized.js or 1680x1050 for other methods, setting the jpg quality for photographs to between 60-80% resulting in a file size in the region of 100kb or less if possible without compromising quality too much.

How can I get screen resolution in java?

You can get the screen size with the Toolkit.getScreenSize() method.

Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
double width = screenSize.getWidth();
double height = screenSize.getHeight();

On a multi-monitor configuration you should use this :

GraphicsDevice gd = GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
int width = gd.getDisplayMode().getWidth();
int height = gd.getDisplayMode().getHeight();

If you want to get the screen resolution in DPI you'll have to use the getScreenResolution() method on Toolkit.


Resources :

Converting pixels to dp

For Xamarin.Android

float DpToPixel(float dp)
{
    var resources = Context.Resources;
    var metrics = resources.DisplayMetrics;
    return dp * ((float)metrics.DensityDpi / (int)DisplayMetricsDensity.Default);
}

Making this a non-static is necessary when you're making a custom renderer

Android ImageButton with a selected state?

ToggleImageButton which implements Checkable interface and supports OnCheckedChangeListener and android:checked xml attribute:

public class ToggleImageButton extends ImageButton implements Checkable {
    private OnCheckedChangeListener onCheckedChangeListener;

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

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

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

    private void setChecked(AttributeSet attrs) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ToggleImageButton);
        setChecked(a.getBoolean(R.styleable.ToggleImageButton_android_checked, false));
        a.recycle();
    }

    @Override
    public boolean isChecked() {
        return isSelected();
    }

    @Override
    public void setChecked(boolean checked) {
        setSelected(checked);

        if (onCheckedChangeListener != null) {
            onCheckedChangeListener.onCheckedChanged(this, checked);
        }
    }

    @Override
    public void toggle() {
        setChecked(!isChecked());
    }

    @Override
    public boolean performClick() {
        toggle();
        return super.performClick();
    }

    public OnCheckedChangeListener getOnCheckedChangeListener() {
        return onCheckedChangeListener;
    }

    public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
        this.onCheckedChangeListener = onCheckedChangeListener;
    }

    public static interface OnCheckedChangeListener {
        public void onCheckedChanged(ToggleImageButton buttonView, boolean isChecked);
    }
}

res/values/attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ToggleImageButton">
        <attr name="android:checked" />
    </declare-styleable>
</resources>

Copy and Paste a set range in the next empty row

Be careful with the "Range(...)" without first qualifying a Worksheet because it will use the currently Active worksheet to make the copy from. It's best to fully qualify both sheets. Please give this a shot (please change "Sheet1" with the copy worksheet):

EDIT: edited for pasting values only based on comments below.

Private Sub CommandButton1_Click()
  Application.ScreenUpdating = False
  Dim copySheet As Worksheet
  Dim pasteSheet As Worksheet

  Set copySheet = Worksheets("Sheet1")
  Set pasteSheet = Worksheets("Sheet2")

  copySheet.Range("A3:E3").Copy
  pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
  Application.CutCopyMode = False
  Application.ScreenUpdating = True
End Sub

How to Change color of Button in Android when Clicked?

One approach is to create an XML file like this in drawable, called whatever.xml:

<?xml version="1.0" encoding="utf-8"?> 
  <selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_focused="true"
        android:state_pressed="true"
        android:drawable="@drawable/bgalt" />

    <item
        android:state_focused="false"
        android:state_pressed="true"
        android:drawable="@drawable/bgalt" />

    <item android:drawable="@drawable/bgnorm" />
</selector>

bgalt and bgnormare PNG images in drawable.

If you create the buttons programatically in your activity, you can set the background with:

final Button b = new Button (MyClass.this);
b.setBackgroundDrawable(getResources().getDrawable(R.drawable.whatever));

If you set your buttons' style with an XML, you would do something like:

<Button
  android:id="@+id/mybutton"
  android:background="@drawable/watever" />

And finally a link to a tutorial. Hope this helps.

Array of Matrices in MATLAB

If all of the matrices are going to be the same size (i.e. 500x800), then you can just make a 3D array:

nUnknown;  % The number of unknown arrays
myArray = zeros(500,800,nUnknown);

To access one array, you would use the following syntax:

subMatrix = myArray(:,:,3);  % Gets the third matrix

You can add more matrices to myArray in a couple of ways:

myArray = cat(3,myArray,zeros(500,800));
% OR
myArray(:,:,nUnknown+1) = zeros(500,800);

If each matrix is not going to be the same size, you would need to use cell arrays like Hosam suggested.

EDIT: I missed the part about running out of memory. I'm guessing your nUnknown is fairly large. You may have to switch the data type of the matrices (single or even a uintXX type if you are using integers). You can do this in the call to zeros:

myArray = zeros(500,800,nUnknown,'single');

How to see top processes sorted by actual memory usage?

use quick tip using top command in linux/unix

$ top

and then hit Shift+m (i.e. write a capital M).

From man top

SORTING of task window
  For compatibility, this top supports most of the former top sort keys.
  Since this is primarily a service to former top users, these commands do
  not appear on any help screen.
    command   sorted-field                  supported
      A         start time (non-display)      No
      M         %MEM                          Yes
      N         PID                           Yes
      P         %CPU                          Yes
      T         TIME+                         Yes

Or alternatively: hit Shift + f , then choose the display to order by memory usage by hitting key n then press Enter. You will see active process ordered by memory usage

How can I read input from the console using the Scanner class in Java?

import java.util.*;

class Ss
{
    int id, salary;
    String name;

   void Ss(int id, int salary, String name)
    {
        this.id = id;
        this.salary = salary;
        this.name = name;
    }

    void display()
    {
        System.out.println("The id of employee:" + id);
        System.out.println("The name of employye:" + name);
        System.out.println("The salary of employee:" + salary);
    }
}

class employee
{
    public static void main(String args[])
    {
        Scanner sc = new Scanner(System.in);

        Ss s = new Ss(sc.nextInt(), sc.nextInt(), sc.nextLine());
        s.display();
    }
}

'typeid' versus 'typeof' in C++

typeid can operate at runtime, and return an object describing the run time type of the object, which must be a pointer to an object of a class with virtual methods in order for RTTI (run-time type information) to be stored in the class. It can also give the compile time type of an expression or a type name, if not given a pointer to a class with run-time type information.

typeof is a GNU extension, and gives you the type of any expression at compile time. This can be useful, for instance, in declaring temporary variables in macros that may be used on multiple types. In C++, you would usually use templates instead.

How to edit Docker container files from the host?

If you think your volume is a "network drive", it will be easier. To edit the file located in this drive, you just need to turn on another machine and connect to this network drive, then edit the file like normal.

How to do that purely with docker (without FTP/SSH ...)?

  1. Run a container that has an editor (VI, Emacs). Search Docker hub for "alpine vim"

Example:

docker run -d --name shared_vim_editor \
 -v <your_volume>:/home/developer/workspace \
jare/vim-bundle:latest
  1. Run the interactive command:

docker exec -it -u root shared_vim_editor /bin/bash

Hope this helps.

Standard deviation of a list

Using python, here are few methods:

import statistics as st

n = int(input())
data = list(map(int, input().split()))

Approach1 - using a function

stdev = st.pstdev(data)

Approach2: calculate variance and take square root of it

variance = st.pvariance(data)
devia = math.sqrt(variance)

Approach3: using basic math

mean = sum(data)/n
variance = sum([((x - mean) ** 2) for x in X]) / n
stddev = variance ** 0.5

print("{0:0.1f}".format(stddev))

Note:

  • variance calculates variance of sample population
  • pvariance calculates variance of entire population
  • similar differences between stdev and pstdev

How can we convert an integer to string in AngularJs

.toString() is available, or just add "" to the end of the int

var x = 3,
    toString = x.toString(),
    toConcat = x + "";

Angular is simply JavaScript at the core.

How to validate an OAuth 2.0 access token for a resource server?

OAuth v2 specs indicates:

Access token attributes and the methods used to access protected resources are beyond the scope of this specification and are defined by companion specifications.

My Authorisation Server has a webservice (SOAP) endpoint that allows the Resource Server to know whether the access_token is valid.

How do you query for "is not null" in Mongo?

db.<collectionName>.find({"IMAGE URL":{"$exists":"true"}, "IMAGE URL": {$ne: null}})

What is the proper way to check and uncheck a checkbox in HTML5?

You can refer to this page at w3schools but basically you could use any of:

<input checked>
<input checked="checked">
<input checked="">

Html/PHP - Form - Input as array

Simply add [] to those names like

 <input type="text" class="form-control" placeholder="Titel" name="levels[level][]">
 <input type="text" class="form-control" placeholder="Titel" name="levels[build_time][]">

Take that template and then you can add those even using a loop.

Then you can add those dynamically as much as you want, without having to provide an index. PHP will pick them up just like your expected scenario example.

Edit

Sorry I had braces in the wrong place, which would make every new value as a new array element. Use the updated code now and this will give you the following array structure

levels > level (Array)
levels > build_time (Array)

Same index on both sub arrays will give you your pair. For example

echo $levels["level"][5];
echo $levels["build_time"][5];

Android: How do bluetooth UUIDs work?

In Bluetooth, all objects are identified by UUIDs. These include services, characteristics and many other things. Bluetooth maintains a database of assigned numbers for standard objects, and assigns sub-ranges for vendors (that have paid enough for a reservation). You can view this list here:

https://www.bluetooth.com/specifications/assigned-numbers/

If you are implementing a standard service (e.g. a serial port, keyboard, headset, etc.) then you should use that service's standard UUID - that will allow you to be interoperable with devices that you didn't develop.

If you are implementing a custom service, then you should generate unique UUIDs, in order to make sure incompatible third-party devices don't try to use your service thinking it is something else. The easiest way is to generate random ones and then hard-code the result in your application (and use the same UUIDs in the devices that will connect to your service, of course).

Python creating a dictionary of lists

You can use setdefault:

d = dict()
a = ['1', '2']
for i in a:
    for j in range(int(i), int(i) + 2): 
        d.setdefault(j, []).append(i)

print d  # prints {1: ['1'], 2: ['1', '2'], 3: ['2']}

The rather oddly-named setdefault function says "Get the value with this key, or if that key isn't there, add this value and then return it."

As others have rightly pointed out, defaultdict is a better and more modern choice. setdefault is still useful in older versions of Python (prior to 2.5).

Java Replacing multiple different substring in a string at once (or in the most efficient way)

Algorithm

One of the most efficient ways to replace matching strings (without regular expressions) is to use the Aho-Corasick algorithm with a performant Trie (pronounced "try"), fast hashing algorithm, and efficient collections implementation.

Simple Code

A simple solution leverages Apache's StringUtils.replaceEach as follows:

  private String testStringUtils(
    final String text, final Map<String, String> definitions ) {
    final String[] keys = keys( definitions );
    final String[] values = values( definitions );

    return StringUtils.replaceEach( text, keys, values );
  }

This slows down on large texts.

Fast Code

Bor's implementation of the Aho-Corasick algorithm introduces a bit more complexity that becomes an implementation detail by using a façade with the same method signature:

  private String testBorAhoCorasick(
    final String text, final Map<String, String> definitions ) {
    // Create a buffer sufficiently large that re-allocations are minimized.
    final StringBuilder sb = new StringBuilder( text.length() << 1 );

    final TrieBuilder builder = Trie.builder();
    builder.onlyWholeWords();
    builder.removeOverlaps();

    final String[] keys = keys( definitions );

    for( final String key : keys ) {
      builder.addKeyword( key );
    }

    final Trie trie = builder.build();
    final Collection<Emit> emits = trie.parseText( text );

    int prevIndex = 0;

    for( final Emit emit : emits ) {
      final int matchIndex = emit.getStart();

      sb.append( text.substring( prevIndex, matchIndex ) );
      sb.append( definitions.get( emit.getKeyword() ) );
      prevIndex = emit.getEnd() + 1;
    }

    // Add the remainder of the string (contains no more matches).
    sb.append( text.substring( prevIndex ) );

    return sb.toString();
  }

Benchmarks

For the benchmarks, the buffer was created using randomNumeric as follows:

  private final static int TEXT_SIZE = 1000;
  private final static int MATCHES_DIVISOR = 10;

  private final static StringBuilder SOURCE
    = new StringBuilder( randomNumeric( TEXT_SIZE ) );

Where MATCHES_DIVISOR dictates the number of variables to inject:

  private void injectVariables( final Map<String, String> definitions ) {
    for( int i = (SOURCE.length() / MATCHES_DIVISOR) + 1; i > 0; i-- ) {
      final int r = current().nextInt( 1, SOURCE.length() );
      SOURCE.insert( r, randomKey( definitions ) );
    }
  }

The benchmark code itself (JMH seemed overkill):

long duration = System.nanoTime();
final String result = testBorAhoCorasick( text, definitions );
duration = System.nanoTime() - duration;
System.out.println( elapsed( duration ) );

1,000,000 : 1,000

A simple micro-benchmark with 1,000,000 characters and 1,000 randomly-placed strings to replace.

  • testStringUtils: 25 seconds, 25533 millis
  • testBorAhoCorasick: 0 seconds, 68 millis

No contest.

10,000 : 1,000

Using 10,000 characters and 1,000 matching strings to replace:

  • testStringUtils: 1 seconds, 1402 millis
  • testBorAhoCorasick: 0 seconds, 37 millis

The divide closes.

1,000 : 10

Using 1,000 characters and 10 matching strings to replace:

  • testStringUtils: 0 seconds, 7 millis
  • testBorAhoCorasick: 0 seconds, 19 millis

For short strings, the overhead of setting up Aho-Corasick eclipses the brute-force approach by StringUtils.replaceEach.

A hybrid approach based on text length is possible, to get the best of both implementations.

Implementations

Consider comparing other implementations for text longer than 1 MB, including:

Papers

Papers and information relating to the algorithm:

Java, reading a file from current directory?

None of the above answer works for me. Here is what works for me.

Let's say your class name is Foo.java, to access to the myFile.txt in the same folder as Foo.java, use this code:

URL path = Foo.class.getResource("myFile.txt");
File f = new File(path.getFile());
reader = new BufferedReader(new FileReader(f));

Convert string into Date type on Python

>>> from datetime import datetime
>>> year, month, day = map(int, my_date.split('-'))
>>> date_object = datetime(year, month, day)

Apache Name Virtual Host with SSL

You MUST add below part to enable NameVirtualHost functionality with given IP.

NameVirtualHost IP_Address:443

How to fix "set SameSite cookie to none" warning?

I'm also in a "trial and error" for that, but this answer from Google Chrome Labs' Github helped me a little. I defined it into my main file and it worked - well, for only one third-party domain. Still making tests, but I'm eager to update this answer with a better solution :)

EDIT: I'm using PHP 7.4 now, and this syntax is working good (Sept 2020):

$cookie_options = array(
  'expires' => time() + 60*60*24*30,
  'path' => '/',
  'domain' => '.domain.com', // leading dot for compatibility or use subdomain
  'secure' => true, // or false
  'httponly' => false, // or false
  'samesite' => 'None' // None || Lax || Strict
);

setcookie('cors-cookie', 'my-site-cookie', $cookie_options);

If you have PHP 7.2 or lower (as Robert's answered below):

setcookie('key', 'value', time()+(7*24*3600), "/; SameSite=None; Secure");

If your host is already updated to PHP 7.3, you can use (thanks to Mahn's comment):

setcookie('cookieName', 'cookieValue', [
  'expires' => time()+(7*24*3600,
  'path' => '/',
  'domain' => 'domain.com',
  'samesite' => 'None',
  'secure' => true,
  'httponly' => true
]);

Another thing you can try to check the cookies, is to enable the flag below, which—in their own words—"will add console warning messages for every single cookie potentially affected by this change":

chrome://flags/#cookie-deprecation-messages

See the whole code at: https://github.com/GoogleChromeLabs/samesite-examples/blob/master/php.md, they have the code for same-site-cookies too.

Resizing Images in VB.NET

Don't know much VB.NET syntax but here's and idea

Dim source As New Bitmap("C:\image.png") 
Dim target As New Bitmap(size.Width, size.Height, PixelFormat.Format24bppRgb)

Using graphics As Graphics = Graphics.FromImage(target)
    graphics.DrawImage(source, new Size(48, 48)) 
End Using

SameSite warning Chrome 77

If you are testing on localhost and you have no control of the response headers, you can disable it with a chrome flag.

Visit the url and disable it: chrome://flags/#same-site-by-default-cookies SameSite by default cookies screenshot

I need to disable it because Chrome Canary just started enforcing this rule as of approximately V 82.0.4078.2 and now it's not setting these cookies.

Note: I only turn this flag on in Chrome Canary that I use for development. It's best not to turn the flag on for everyday Chrome browsing for the same reasons that google is introducing it.

Javascript onHover event

I don't think you need/want the timeout.

onhover (hover) would be defined as the time period while "over" something. IMHO

onmouseover = start...

onmouseout = ...end

For the record I've done some stuff with this to "fake" the hover event in IE6. It was rather expensive and in the end I ditched it in favor of performance.

Assigning the output of a command to a variable

If you want to do it with multiline/multiple command/s then you can do this:

output=$( bash <<EOF
#multiline/multiple command/s
EOF
)

Or:

output=$(
#multiline/multiple command/s
)

Example:

#!/bin/bash
output="$( bash <<EOF
echo first
echo second
echo third
EOF
)"
echo "$output"

Output:

first
second
third

Entry point for Java applications: main(), init(), or run()?

The main() method is the entry point for a Java application. run() is typically used for new threads or tasks.

Where have you been writing a run() method, what kind of application are you writing (e.g. Swing, AWT, console etc) and what's your development environment?

Notepad++ - How can I replace blank lines

  1. Press Ctrl+H (Replace)

  2. Select Extended from SearchMode

  3. Put \r\n\r\n in Find What

  4. Put \r\n in ReplaceWith

  5. Click on Replace All

Replace multiple line breaks

How to make String.Contains case insensitive?

You can use:

if (myString1.IndexOf("AbC", StringComparison.OrdinalIgnoreCase) >=0) {
    //...
}

This works with any .NET version.

Proxy with urllib2

You have to install a ProxyHandler

urllib2.install_opener(
    urllib2.build_opener(
        urllib2.ProxyHandler({'http': '127.0.0.1'})
    )
)
urllib2.urlopen('http://www.google.com')

How does HttpContext.Current.User.Identity.Name know which usernames exist?

Also check that

<modules>
      <remove name="FormsAuthentication"/>
</modules>

If you found anything like this just remove:

<remove name="FormsAuthentication"/>

Line from web.config and here you go it will work fine I have tested it.

How do you determine what SQL Tables have an identity column programmatically

In SQL 2005:

select object_name(object_id), name
from sys.columns
where is_identity = 1

Ruby on Rails: Clear a cached page

rake tmp:cache:clear might be what you're looking for.

Equivalent VB keyword for 'break'

In both Visual Basic 6.0 and VB.NET you would use:

  • Exit For to break from For loop
  • Wend to break from While loop
  • Exit Do to break from Do loop

depending on the loop type. See Exit Statements for more details.

Finding local IP addresses using Python's stdlib

import socket
socket.gethostbyname(socket.getfqdn())

Change a Nullable column to NOT NULL with Default Value

Try this

ALTER TABLE table_name ALTER COLUMN col_name data_type NOT NULL;

Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager

This seems to be a bug in the newly added support for nested fragments. Basically, the child FragmentManager ends up with a broken internal state when it is detached from the activity. A short-term workaround that fixed it for me is to add the following to onDetach() of every Fragment which you call getChildFragmentManager() on:

@Override
public void onDetach() {
    super.onDetach();

    try {
        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
        childFragmentManager.setAccessible(true);
        childFragmentManager.set(this, null);

    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

getApplicationContext() - Returns the context for all activities running in application.

getBaseContext() - If you want to access Context from another context within application you can access.

getContext() - Returns the context view only current running activity.

How to fix a locale setting warning from Perl

Adding the following to /etc/environment fixed the problem for me on Debian and Ubuntu (of course, modify to match the locale you want to use):

LANGUAGE=en_US.UTF-8
LC_ALL=en_US.UTF-8
LANG=en_US.UTF-8
LC_CTYPE=en_US.UTF-8

Width equal to content

just use display: table; on your case.

Bootstrap navbar Active State not working

Bootstrap 4 requires you to target the li item for active classes. In order to do that you have to find the parent of the a. The 'hitbox' of the a is as big as the li but due to bubbeling of event in JS it will give you back the a event. So you have to manually add it to its parent.

  //set active navigation after click
  $(".nav-link").on("click", (event) => {
    $(".navbar-nav").find(".active").removeClass('active');
    $(event.target).parent().addClass('active');
  });

How to express a One-To-Many relationship in Django

In Django, a one-to-many relationship is called ForeignKey. It only works in one direction, however, so rather than having a number attribute of class Dude you will need

class Dude(models.Model):
    ...

class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude)

Many models can have a ForeignKey to one other model, so it would be valid to have a second attribute of PhoneNumber such that

class Business(models.Model):
    ...
class Dude(models.Model):
    ...
class PhoneNumber(models.Model):
    dude = models.ForeignKey(Dude)
    business = models.ForeignKey(Business)

You can access the PhoneNumbers for a Dude object d with d.phonenumber_set.objects.all(), and then do similarly for a Business object.

CSS:Defining Styles for input elements inside a div

You can define style rules which only apply to specific elements inside your div with id divContainer like this:

#divContainer input { ... }
#divContainer input[type="radio"] { ... }
#divContainer input[type="text"] { ... }
/* etc */

How to get the absolute path to the public_html folder?

Out of curiosity, why don't you just use the url for the said folder?

http://www.mysite.com/images

Assuming that the folder never changes location, that would be the easiest way to do it.

Composer killed while updating

Unfortuantely composer requires a lot of RAM & processing power. Here are a few things that I did, which combined, made the process bearable. This was on my cloud playpen env.

  1. You may be simply running out of RAM. Enable swap: https://www.digitalocean.com/community/search?q=add+swap (note: I think best practice is to add a seperate partition. Digitalocean's guide is appropriate for their environment)
  2. service mysql stop (kill your DB/mem-hog services to free some RAM - don't forget to start it again!)
  3. use a secondary terminal session running top to watch memory/swap consumption until process is complete.
  4. composer.phar update --prefer-dist -vvv (verbose output [still hangs at some points when working] and use distro zip files). Maybe try a --dry-run too?
  5. Composer is apparently know to run slower in older versions of PHP (e.g. 5.3x). It was still slow in 5.5.9 for me...

HTML Input Box - Disable

<input type="text" required="true" value="" readonly="true">

This will make a text box in readonly mode, might be helpful in generating passwords and datepickers.

How to convert DataSet to DataTable

DataSet is collection of DataTables.... you can get the datatable from DataSet as below.

//here ds is dataset
DatTable dt = ds.Table[0]; /// table of dataset

How to join entries in a set into one string?

The join is called on the string:

print ", ".join(set_3)

Send message to specific client with socket.io and node.js

Whatever version we are using if we just console.log() the "io" object that we use in our server side nodejs code, [e.g. io.on('connection', function(socket) {...});], we can see that "io" is just an json object and there are many child objects where the socket id and socket objects are stored.

I am using socket.io version 1.3.5, btw.

If we look in the io object, it contains,

 sockets:
  { name: '/',
    server: [Circular],
    sockets: [ [Object], [Object] ],
    connected:
     { B5AC9w0sYmOGWe4fAAAA: [Object],
       'hWzf97fmU-TIwwzWAAAB': [Object] },

here we can see the socketids "B5AC9w0sYmOGWe4fAAAA" etc. So, we can do,

io.sockets.connected[socketid].emit();

Again, on further inspection we can see segments like,

 eio:
  { clients:
     { B5AC9w0sYmOGWe4fAAAA: [Object],
       'hWzf97fmU-TIwwzWAAAB': [Object] },

So, we can retrieve a socket from here by doing

io.eio.clients[socketid].emit();

Also, under engine we have,

engine:
 { clients:
    { B5AC9w0sYmOGWe4fAAAA: [Object],
      'hWzf97fmU-TIwwzWAAAB': [Object] },

So, we can also write,

io.engine.clients[socketid].emit();

So, I guess we can achieve our goal in any of the 3 ways I listed above,

  1. io.sockets.connected[socketid].emit(); OR
  2. io.eio.clients[socketid].emit(); OR
  3. io.engine.clients[socketid].emit();

Troubleshooting BadImageFormatException

You can also get this exception when your application target .NET Framework 4.5 (for example) and you have the following app.config :

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <startup>
    <supportedRuntime version="v2.0.50727" />
    <supportedRuntime version="v4.0" />
  </startup>
</configuration>

When trying to launch the debug of the application you will get the BadImageFormatException.

Removing the line declaring the v2.0 version will clear the error.

I had this issue recently when I tried to change the target platform from an old .NET 2.0 project to .NET 4.5.

Resolving a Git conflict with binary files

mipadi's answer didn't quite work for me, I needed to do this :

git checkout --ours path/to/file.bin

or, to keep the version being merged in:

git checkout --theirs path/to/file.bin

then

git add path/to/file.bin

And then I was able to do "git mergetool" again and continue onto the next conflict.

Java converting Image to BufferedImage

If you are getting back a sun.awt.image.ToolkitImage, you can cast the Image to that, and then use getBufferedImage() to get the BufferedImage.

So instead of your last line of code where you are casting you would just do:

BufferedImage buffered = ((ToolkitImage) image).getBufferedImage();

How to check not in array element

$array1 = "Orange";
$array2 = array("Apple","Grapes","Orange","Pineapple");
if(in_array($array1,$array2)){
    echo $array1.' exists in array2';
}else{
    echo $array1.'does not exists in array2';
}

Setting std=c99 flag in GCC

How about alias gcc99= gcc -std=c99?

How can I generate a unique ID in Python?

This will work very quickly but will not generate random values but monotonously increasing ones (for a given thread).

import threading

_uid = threading.local()
def genuid():
    if getattr(_uid, "uid", None) is None:
        _uid.tid = threading.current_thread().ident
        _uid.uid = 0
    _uid.uid += 1
    return (_uid.tid, _uid.uid)

It is thread safe and working with tuples may have benefit as opposed to strings (shorter if anything). If you do not need thread safety feel free remove the threading bits (in stead of threading.local, use object() and remove tid altogether).

Hope that helps.

NuGet Package Restore Not Working

For others who stumble onto this post, read this.

NuGet 2.7+ introduced us to Automatic Package Restore. This is considered to be a much better approach for most applications as it does not tamper with the MSBuild process. Less headaches.

Some links to get you started:

Get first letter of a string from column

Cast the dtype of the col to str and you can perform vectorised slicing calling str:

In [29]:
df['new_col'] = df['First'].astype(str).str[0]
df

Out[29]:
   First  Second new_col
0    123     234       1
1     22    4353       2
2     32     355       3
3    453     453       4
4     45     345       4
5    453     453       4
6     56      56       5

if you need to you can cast the dtype back again calling astype(int) on the column

Display a message in Visual Studio's output window when not debug mode?

The results are not in the Output window but in the Test Results Detail (TestResult Pane at the bottom, right click on on Test Results and go to TestResultDetails).

This works with Debug.WriteLine and Console.WriteLine.

How do I view the SQL generated by the Entity Framework?

EF Core 5.0

This loooong-awaited feature is available in EF Core 5.0! This is from the weekly status updates:

var query = context.Set<Customer>().Where(c => c.City == city);
Console.WriteLine(query.ToQueryString())

results in this output when using the SQL Server database provider:

DECLARE p0 nvarchar(4000) = N'London';

SELECT [c].[CustomerID], [c].[Address], [c].[City], [c].[CompanyName],
[c].[ContactName], [c].[ContactTitle], [c].[Country], [c].[Fax], [c].[Phone],
[c].[PostalCode], [c].[Region]
FROM [Customers] AS [c]
WHERE [c].[City] = @__city_0

Notice that declarations for parameters of the correct type are also included in the output. This allows copy/pasting to SQL Server Management Studio, or similar tools, such that the query can be executed for debugging/analysis.

woohoo!!!

How to get a string after a specific substring?

You can use the package called substring. Just install using the command pip install substring. You can get the substring by just mentioning the start and end characters/indices.

For example:

import substring
s = substring.substringByChar("abcdefghijklmnop", startChar="d", endChar="n")
print(s)

Output:

# s = defghijklmn

Get user's current location

<?php
$query = @unserialize (file_get_contents('http://ip-api.com/php/'));
if ($query && $query['status'] == 'success') {
echo 'Hey user from ' . $query['country'] . ', ' . $query['city'] . '!';
}
foreach ($query as $data) {
    echo $data . "<br>";
}
?>

Try this code using this source. it works!

Get host domain from URL?

 var url = Regex.Match(url, @"(http:|https:)\/\/(.*?)\/");

INPUT = "https://stackoverflow.com/questions/";

OUTPUT = "https://stackoverflow.com/";

An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code

It means somewhere in your chain of calls, you tried to access a Property or call a method on an object that was null.

Given your statement:

img1.ImageUrl = ConfigurationManager
                    .AppSettings
                    .Get("Url")
                    .Replace("###", randomString) 
                + Server.UrlEncode(
                      ((System.Web.UI.MobileControls.Form)Page
                      .FindControl("mobileForm"))
                      .Title);

I'm guessing either the call to AppSettings.Get("Url") is returning null because the value isn't found or the call to Page.FindControl("mobileForm") is returning null because the control isn't found.

You could easily break this out into multiple statements to solve the problem:

var configUrl = ConfigurationManager.AppSettings.Get("Url");
var mobileFormControl = Page.FindControl("mobileForm")
                            as System.Web.UI.MobileControls.Form;

if(configUrl != null && mobileFormControl != null)
{
    img1.ImageUrl = configUrl.Replace("###", randomString) + mobileControl.Title;
}

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

if you get Software Update server issue: enter image description here

use with sudo:

sudo xcode-select --install

Postgres: check if array field contains value?

Instead of IN we can use ANY with arrays casted to enum array, for example:

create type example_enum as enum (
  'ENUM1', 'ENUM2'
);

create table example_table (
  id integer,
  enum_field example_enum
);

select 
  * 
from 
  example_table t
where
  t.enum_field = any(array['ENUM1', 'ENUM2']::example_enum[]);

Or we can still use 'IN' clause, but first, we should 'unnest' it:

select 
  * 
from 
  example_table t
where
  t.enum_field in (select unnest(array['ENUM1', 'ENUM2']::example_enum[]));

Example: https://www.db-fiddle.com/f/LaUNi42HVuL2WufxQyEiC/0

Google Maps API v3: Can I setZoom after fitBounds?

I saw many incorrect or too complicated solutions, so decided to post a working, elegant solution.

The reason setZoom() doesn't work as you expect is that fitBounds() is asynchronous, so it gives no guarantee that it would immediately update the zoom, but your call to setZoom() relies on that.

What you might consider is setting the minZoom map option before calling fitBounds() and then clearing it after it completes (so that users can still zoom out manually if they want to):

var bounds = new google.maps.LatLngBounds();
// ... (extend bounds with all points you want to fit)

// Ensure the map does not get too zoomed out when fitting the bounds.
gmap.setOptions({minZoom: 6});
// Clear the minZoom only after the map fits the bounds (note that
// fitBounds() is asynchronous). The 'idle' event fires when the map
// becomes idle after panning or zooming.
google.maps.event.addListenerOnce(gmap, 'idle', function() {
  gmap.setOptions({minZoom: null});
});

gmap.fitBounds(bounds);

In addition, if you want to also limit the max zoom, you can apply the same trick with the maxZoom property.

See the MapOptions docs.

What is the difference between json.dump() and json.dumps() in python?

The functions with an s take string parameters. The others take file streams.

"unexpected token import" in Nodejs5 and babel?

It may be that you're running uncompiled files. Let's start clean!

In your work directory create:

  • Two folders. One for precompiled es2015 code. The other for babel's output. We'll name them "src" and "lib" respectively.
  • A package.json file with the following object:

    { 
      "scripts": {
          "transpile-es2015": "babel src -d lib"
      },
      "devDependencies": {
          "babel-cli": "^6.18.0",
          "babel-preset-latest": "^6.16.0"
      }
    }
    
  • A file named ".babelrc" with the following instructions: {"presets": ["latest"]}

  • Lastly, write test code in your src/index.js file. In your case: import co from 'co'.

Through your console:

  • Install your packages: npm install
  • Transpile your source directory to your output directory with the -d (aka --out-dir) flag as, already, specified in our package.json: npm run transpile-es2015
  • Run your code from the output directory! node lib/index.js

How do I unload (reload) a Python module?

reload(module), but only if it's completely stand-alone. If anything else has a reference to the module (or any object belonging to the module), then you'll get subtle and curious errors caused by the old code hanging around longer than you expected, and things like isinstance not working across different versions of the same code.

If you have one-way dependencies, you must also reload all modules that depend on the reloaded module to get rid of all the references to the old code. And then reload modules that depend on the reloaded modules, recursively.

If you have circular dependencies, which is very common for example when you are dealing with reloading a package, you must unload all the modules in the group in one go. You can't do this with reload() because it will re-import each module before its dependencies have been refreshed, allowing old references to creep into new modules.

The only way to do it in this case is to hack sys.modules, which is kind of unsupported. You'd have to go through and delete each sys.modules entry you wanted to be reloaded on next import, and also delete entries whose values are None to deal with an implementation issue to do with caching failed relative imports. It's not terribly nice but as long as you have a fully self-contained set of dependencies that doesn't leave references outside its codebase, it's workable.

It's probably best to restart the server. :-)

How can I correctly format currency using jquery?

Expanding upon Melu's answer you can do this to functionalize the code and handle negative amounts.

Sample Output:
$5.23
-$5.23

function formatCurrency(total) {
    var neg = false;
    if(total < 0) {
        neg = true;
        total = Math.abs(total);
    }
    return (neg ? "-$" : '$') + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString();
}

How to return JSon object

First of all, there's no such thing as a JSON object. What you've got in your question is a JavaScript object literal (see here for a great discussion on the difference). Here's how you would go about serializing what you've got to JSON though:

I would use an anonymous type filled with your results type:

string json = JsonConvert.SerializeObject(new
{
    results = new List<Result>()
    {
        new Result { id = 1, value = "ABC", info = "ABC" },
        new Result { id = 2, value = "JKL", info = "JKL" }
    }
});

Also, note that the generated JSON has result items with ids of type Number instead of strings. I doubt this will be a problem, but it would be easy enough to change the type of id to string in the C#.

I'd also tweak your results type and get rid of the backing fields:

public class Result
{
    public int id { get ;set; }
    public string value { get; set; }
    public string info { get; set; }
}

Furthermore, classes conventionally are PascalCased and not camelCased.

Here's the generated JSON from the code above:

{
  "results": [
    {
      "id": 1,
      "value": "ABC",
      "info": "ABC"
    },
    {
      "id": 2,
      "value": "JKL",
      "info": "JKL"
    }
  ]
}

Convert JsonObject to String

you can use

JsonObject.getString("msg"); 

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

Take nth column in a text file

If you are using structured data, this has the added benefit of not invoking an extra shell process to run tr and/or cut or something. ...

(Of course, you will want to guard against bad inputs with conditionals and sane alternatives.)

...
while read line ; 
do 
    lineCols=( $line ) ;
    echo "${lineCols[0]}"
    echo "${lineCols[1]}"
done < $myFQFileToRead ; 
...

There are No resources that can be added or removed from the server

The issue is incompatible web application version with the targeted server. So project facets needs to be changed. In most of the cases the "Dynamic Web Module" property. This should be the value of the servlet-api version supported by the server.

In my case,

I tried changing the web_app value in web.xml. It did not worked.

I tried changing the project facet by right clicking on project properties(as mentioned above), did not work.

What worked is: Changing "version" value as in jst.web to right version from

org.eclipse.wst.common.project.facet.core.xml file. This file is present in the .setting folder under your project root directory.

You may also look at this

Use JAXB to create Object from XML String

If you want to parse using InputStreams

public Object xmlToObject(String xmlDataString) {
        Object converted = null;
        try {
        
            JAXBContext jc = JAXBContext.newInstance(Response.class);
        
            Unmarshaller unmarshaller = jc.createUnmarshaller();
            InputStream stream = new ByteArrayInputStream(xmlDataString.getBytes(StandardCharsets.UTF_8));
            
            converted = unmarshaller.unmarshal(stream);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return converted;
    }

Are 2 dimensional Lists possible in c#?

Well you certainly can use a List<List<string>> where you'd then write:

List<string> track = new List<string>();
track.Add("2349");
track.Add("The Prime Time of Your Life");
// etc
matrix.Add(track);

But why would you do that instead of building your own class to represent a track, with Track ID, Name, Artist, Album, Play Count and Skip Count properties? Then just have a List<Track>.

Detecting when the 'back' button is pressed on a navbar

First Method

- (void)didMoveToParentViewController:(UIViewController *)parent
{
    if (![parent isEqual:self.parentViewController]) {
         NSLog(@"Back pressed");
    }
}

Second Method

-(void) viewWillDisappear:(BOOL)animated {
    if ([self.navigationController.viewControllers indexOfObject:self]==NSNotFound) {
       // back button was pressed.  We know this is true because self is no longer
       // in the navigation stack.  
    }
    [super viewWillDisappear:animated];
}

Copy multiple files from one directory to another from Linux shell

Try this simpler one,

cp /home/ankur/folder/file{1,2} /home/ankur/dest

If you want to copy all the 10 files then run this command,

 cp ~/Desktop/{xyz,file{1,2},next,files,which,are,not,similer} foo-bar

Checking images for similarity with OpenCV

A little bit off topic but useful is the pythonic numpy approach. Its robust and fast but just does compare pixels and not the objects or data the picture contains (and it requires images of same size and shape):

A very simple and fast approach to do this without openCV and any library for computer vision is to norm the picture arrays by

import numpy as np
picture1 = np.random.rand(100,100)
picture2 = np.random.rand(100,100)
picture1_norm = picture1/np.sqrt(np.sum(picture1**2))
picture2_norm = picture2/np.sqrt(np.sum(picture2**2))

After defining both normed pictures (or matrices) you can just sum over the multiplication of the pictures you like to compare:

1) If you compare similar pictures the sum will return 1:

In[1]: np.sum(picture1_norm**2)
Out[1]: 1.0

2) If they aren't similar, you'll get a value between 0 and 1 (a percentage if you multiply by 100):

In[2]: np.sum(picture2_norm*picture1_norm)
Out[2]: 0.75389941124629822

Please notice that if you have colored pictures you have to do this in all 3 dimensions or just compare a greyscaled version. I often have to compare huge amounts of pictures with arbitrary content and that's a really fast way to do so.

How do I drop table variables in SQL-Server? Should I even do this?

But you all forgot to mention, that if a variable table is used within a loop it will need emptying (delete @table) prior to loading with data again within a loop.

Change UITableView height dynamically

I found adding constraint programmatically much easier than in storyboard.

    var leadingMargin = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.LeadingMargin, relatedBy: NSLayoutRelation.Equal, toItem: self.mView, attribute: NSLayoutAttribute.LeadingMargin, multiplier: 1, constant: 0.0)

    var trailingMargin = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.TrailingMargin, relatedBy: NSLayoutRelation.Equal, toItem: mView, attribute: NSLayoutAttribute.TrailingMargin, multiplier: 1, constant: 0.0)

    var height = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: screenSize.height - 55)

    var bottom = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.BottomMargin, relatedBy: NSLayoutRelation.Equal, toItem: self.mView, attribute: NSLayoutAttribute.BottomMargin, multiplier: 1, constant: screenSize.height - 200)

    var top = NSLayoutConstraint(item: self.tableView, attribute: NSLayoutAttribute.TopMargin, relatedBy: NSLayoutRelation.Equal, toItem: self.mView, attribute: NSLayoutAttribute.TopMargin, multiplier: 1, constant: 250)

    self.view.addConstraint(leadingMargin)
    self.view.addConstraint(trailingMargin)
    self.view.addConstraint(height)
    self.view.addConstraint(bottom)
    self.view.addConstraint(top)

Variable not accessible when initialized outside function

My guess is that the system-status element is declared after the variable declaration is run. Thus, at the time the variable is declared, it is actually being set to null?

You should declare it only, then assign its value from an onLoad handler instead, because then you will be sure that it has properly initialized (loaded) the element in question.

You could also try putting the script at the bottom of the page (or at least somewhere after the system-status element is declared) but it's not guaranteed to always work.

Eclipse: The declared package does not match the expected package

Move your problem *.java files to other folder.

Click 'src' item and press "F5".

Red crosses will dissaperar.

Return your *.java files to "package path", click 'src' item and press "F5".

All should be ok.

Is log(n!) = T(n·log(n))?

Thanks, I found your answers convincing but in my case, I must use the T properties:

log(n!) = T(n·log n) =>  log(n!) = O(n log n) and log(n!) = O(n log n)

to verify the problem I found this web, where you have all the process explained: http://www.mcs.sdsmt.edu/ecorwin/cs372/handouts/theta_n_factorial.htm

Setting width of spreadsheet cell using PHPExcel

It's a subtle difference, but this works fine for me:

$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);

Notice, the difference between getColumnDimensionByColumn and getColumnDimension

Also, I'm not even setting AutoSize and it works fine.

Adding git branch on the Bash command prompt

I have tried a small script in python that goes in a bin folder.... 'gitprompt' file

#!/usr/bin/env python
import subprocess, os
s = os.path.join(os.getcwd(), '.git')
def cut(cmd):
    ret=''
    half=0
    record = False
    for c in cmd:
        if c == "\n":
            if not (record):
                pass
            else:
                break
        if (record) and c!="\n":
            ret = ret + c
        if c=='*':
            half=0.5
        if c==' ':
            if half == 0.5:
                half = 1
        if half == 1:
            record = True
    return ret
if (os.path.isdir(s)):
    out = subprocess.check_output("git branch",shell=True)
    print cut(out)
else:
    print "-"

Make it executable and stuff

Then adjust the bash prompt accordingly like :

\u:\w--[$(gitprompt)] \$ 

Extension methods must be defined in a non-generic static class

Extension method should be inside a static class. So please add your extension method inside a static class.

so for example it should be like this

public static class myclass
    {
        public static Byte[] ToByteArray(this Stream stream)
        {
            Int32 length = stream.Length > Int32.MaxValue ? Int32.MaxValue : Convert.ToInt32(stream.Length);
            Byte[] buffer = new Byte[length];
            stream.Read(buffer, 0, length);
            return buffer;
        }

    }

CSS submit button weird rendering on iPad/iPhone

Add this code into the css file:

input {
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
}

This will help.

Difference between using bean id and name in Spring configuration file

Both id and name are bean identifiers in Spring IOC container/ApplicationContecxt. The id attribute lets you specify exactly one id but using name attribute you can give alias name to that bean.

You can check the spring doc here.

onNewIntent() lifecycle and registered listeners

onNewIntent() is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate(). From activities lifecycle point of view it's therefore needed to call onPause() before onNewIntent(). I suggest you to rewrite your activity to not use these listeners inside of onNewIntent(). For example most of the time my onNewIntent() methods simply looks like this:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // getIntent() should always return the most recent
    setIntent(intent);
}

With all setup logic happening in onResume() by utilizing getIntent().

Checkout multiple git repos into same Jenkins workspace

Jenkins: Multiple SCM - deprecated. GIT Plugin - doesn't work for multiple repos.

Scripting / pipeline as code - is the way to go.

What is the difference between getText() and getAttribute() in Selenium WebDriver?

  <input attr1='a' attr2='b' attr3='c'>foo</input>

getAttribute(attr1) you get 'a'

getAttribute(attr2) you get 'b'

getAttribute(attr3) you get 'c'

getText() with no parameter you can only get 'foo'

How to add header to a dataset in R?

this should work out,

      kable(dt) %>%
      kable_styling("striped") %>%
      add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2, "Group 3" = 2))
#OR
kable(dt) %>%
  kable_styling(c("striped", "bordered")) %>%
  add_header_above(c(" ", "Group 1" = 2, "Group 2" = 2, "Group 3" = 2)) %>%
  add_header_above(c(" ", "Group 4" = 4, "Group 5" = 2)) %>%
  add_header_above(c(" ", "Group 6" = 6))

for more you can check the link

Visual Studio Error: (407: Proxy Authentication Required)

Using IDE configuration:

  1. Open Visual Studio 2012, click on Tools from the file menu bar and then click Options,

  2. From the Options window, expand the Source Control option, click on Plug-in Selection and make sure that the Current source control plug-in is set to Visual Studio Team Foundation Server.

  3. Next, click on the Visual Studio Team Foundation Server option under Source Control and perform the following steps: Check Use proxy server for file downloads. Enter the host name of your preferred Team Foundation Server 2010 Proxy server. Set the port to 443. Check Use SSL encryption (https) to connect.

  4. Click the OK button.

Using exe.config:

Modify the devenv.exe.config where IDE executable is like this:

<system.net> 
  <defaultProxy>  
   <proxy proxyaddress=”http://proxy:3128”
     bypassonlocal=”True” autoDetect=”True” /> 
   <bypasslist> 
   <add address=”http://URL”/>  
  </bypasslist> 
 </defaultProxy> 

Declare your proxy at proxyaddress and remember bypasslist urls and ip addresses will be excluded from proxy traffic.

Then restart visual studio to update changes.

NSString property: copy or retain?

Surely putting 'copy' on a property declaration flies in the face of using an object-oriented environment where objects on the heap are passed by reference - one of the benefits you get here is that, when changing an object, all references to that object see the latest changes. A lot of languages supply 'ref' or similar keywords to allow value types (i.e. structures on the stack) to benefit from the same behaviour. Personally, I'd use copy sparingly, and if I felt that a property value should be protected from changes made to the object it was assigned from, I could call that object's copy method during the assignment, e.g.:

p.name = [someName copy];

Of course, when designing the object that contains that property, only you will know whether the design benefits from a pattern where assignments take copies - Cocoawithlove.com has the following to say:

"You should use a copy accessor when the setter parameter may be mutable but you can't have the internal state of a property changing without warning" - so the judgement as to whether you can stand the value to change unexpectedly is all your own. Imagine this scenario:

//person object has details of an individual you're assigning to a contact list.

Contact *contact = [[[Contact alloc] init] autorelease];
contact.name = person.name;

//person changes name
[[person name] setString:@"new name"];
//now both person.name and contact.name are in sync.

In this case, without using copy, our contact object takes the new value automatically; if we did use it, though, we'd have to manually make sure that changes were detected and synced. In this case, retain semantics might be desirable; in another, copy might be more appropriate.

How to get selected value of a dropdown menu in ReactJS

Using React Functional Components:

const [option,setOption] = useState()

function handleChange(event){
    setOption(event.target.value)
}

<select name='option' onChange={handleChange}>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
</select>

EXCEL Multiple Ranges - need different answers for each range

Nested if's in Excel Are ugly:

=If(G2 < 1, .1, IF(G2 < 5,.15,if(G2 < 15,.2,if(G2 < 30,.5,if(G2 < 100,.1,1.3)))))

That should cover it.

what does "dead beef" mean?

It is also used for debugging purposes.

Here is a handy list of some of these values:

http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Magic_debug_values

Is it possible to disable scrolling on a ViewPager

Here's an answer in Kotlin and androidX

import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.viewpager.widget.ViewPager

class DeactivatedViewPager @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : ViewPager(context, attrs) {

    var isPagingEnabled = true

    override fun onTouchEvent(ev: MotionEvent?): Boolean {
        return isPagingEnabled && super.onTouchEvent(ev)
    }

    override fun onInterceptTouchEvent(ev: MotionEvent?): Boolean {
        return isPagingEnabled && super.onInterceptTouchEvent(ev)
    }
}

How to auto generate migrations with Sequelize CLI from Sequelize models?

Another solution is to put data definition into a separate file.

The idea is to write data common for both model and migration into a separate file, then require it in both the migration and the model. Then in the model we can add validations, while the migration is already good to go.

In order to not clutter this post with tons of code i wrote a GitHub gist.

See it here: https://gist.github.com/igorvolnyi/f7989fc64006941a7d7a1a9d5e61be47

How to apply `git diff` patch without Git installed?

git diff > patchfile

and

patch -p1 < patchfile

work but as many people noticed in comments and other answers patch does not understand adds, deletes and renames. There is no option but git apply patchfile if you need handle file adds, deletes and renames.


EDIT December 2015

Latest versions of patch command (2.7, released in September 2012) support most features of the "diff --git" format, including renames and copies, permission changes, and symlink diffs (but not yet binary diffs) (release announcement).

So provided one uses current/latest version of patch there is no need to use git to be able to apply its diff as a patch.

How can I make my own event in C#?

You can declare an event with the following code:

public event EventHandler MyOwnEvent;

A custom delegate type instead of EventHandler can be used if needed.

You can find detailed information/tutorials on the use of events in .NET in the article Events Tutorial (MSDN).

What is the difference between using constructor vs getInitialState in React / React Native?

The two approaches are not interchangeable. You should initialize state in the constructor when using ES6 classes, and define the getInitialState method when using React.createClass.

See the official React doc on the subject of ES6 classes.

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { /* initial state */ };
  }
}

is equivalent to

var MyComponent = React.createClass({
  getInitialState() {
    return { /* initial state */ };
  },
});

Notepad++ incrementally replace

I was looking for the same feature today but couldn't do this in Notepad++. However, we have TextPad to our rescue. It worked for me.

In TextPad's replace dialog, turn on regex; then you could try replacing

<row id="1"/>

by

<row id="\i"/>

Have a look at this link for further amazing replace features of TextPad - http://sublimetext.userecho.com/topic/106519-generate-a-sequence-of-numbers-increment-replace/

How to escape "&" in XML?

use &amp; in place of &

change to

<string name="magazine">Newspaper &amp; Magazines</string>

Run jar file in command prompt

If you dont have an entry point defined in your manifest invoking java -jar foo.jar will not work.

Use this command if you dont have a manifest or to run a different main class than the one specified in the manifest:

java -cp foo.jar full.package.name.ClassName

See also instructions on how to create a manifest with an entry point: https://docs.oracle.com/javase/tutorial/deployment/jar/appman.html

How to reliably open a file in the same directory as a Python script

On Python 3.4, the pathlib module was added, and the following code will reliably open a file in the same directory as the current script:

from pathlib import Path

p = Path(__file__).with_name('file.txt')
with p.open('r') as f:
    print(f.read())

You can also use parent.absolute() to get directory value as a string if needed:

p = Path(__file__)
dir_abs = p.parent.absolute()  # Will return the executable directory absolute path

Git error on commit after merge - fatal: cannot do a partial commit during a merge

git commit -am 'Conflicts resolved'

This worked for me. You can try this also.

dynamic_cast and static_cast in C++

There are no classes in C, so it's impossible to to write dynamic_cast in that language. C structures don't have methods (as a result, they don't have virtual methods), so there is nothing "dynamic" in it.

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

for others there are a solution for any API level , you can place a item on top of each other example :

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<!-- my firt item with 4 corners radius(8dp)
 -->
    <item>
        <shape>
            <solid
                android:angle="270.0"
                android:color="#3D689A" />

            <corners android:topLeftRadius="8dp" />
        </shape>
    </item>
<!-- my second item is on top right for a fake corner radius(0dp)
 -->
    <item
        android:bottom="30dp"
        android:left="50dp">
        <shape>
            <solid android:color="#5C83AF" />
        </shape>
    </item>
<!-- my third item is on bottom left for a fake corner radius(0dp)
 -->
    <item
        android:right="50dp"
        android:top="30dp">
        <shape>
            <solid android:color="#5C83AF" />
        </shape>
    </item>

</layer-list>

the result with light color to show you the three items :

enter image description here

the final result :

enter image description here

Best regards.

making matplotlib scatter plots from dataframes in Python's pandas

There is little to be added to Garrett's great answer, but pandas also has a scatter method. Using that, it's as easy as

df = pd.DataFrame(np.random.randn(10,2), columns=['col1','col2'])
df['col3'] = np.arange(len(df))**2 * 100 + 100
df.plot.scatter('col1', 'col2', df['col3'])

plotting sizes in col3 to col1-col2

How can I get column names from a table in SQL Server?

One other option which is arguably more intuitive is:

SELECT [name] 
FROM sys.columns 
WHERE object_id = OBJECT_ID('[yourSchemaType].[yourTableName]') 

This gives you all your column names in a single column. If you care about other metadata, you can change edit the SELECT STATEMENT TO SELECT *.

how to use substr() function in jquery?

If you want to extract from a tag then

$('.dep_buttons').text().substr(0,25)

With the mouseover event,

$(this).text($(this).text().substr(0, 25));

The above will extract the text of a tag, then extract again assign it back.

How to zip a file using cmd line?

Not exactly zipping, but you can compact files in Windows with the compact command:

compact /c /s:<directory or file>

And to uncompress:

compact /u /s:<directory or file>

NOTE: These commands only mark/unmark files or directories as compressed in the file system. They do not produces any kind of archive (like zip, 7zip, rar, etc.)

getResourceAsStream() vs FileInputStream

classname.getResourceAsStream() loads a file via the classloader of classname. If the class came from a jar file, that is where the resource will be loaded from.

FileInputStream is used to read a file from the filesystem.

How to drop columns using Rails migration

Clear & Simple Instructions for Rails 5 & 6

  • WARNING: You will lose data if you remove a column from your database. To proceed, see below:
  • Warning: the below instructions are for trivial migrations. For complex migrations with e.g. millions and millions of rows, you will have to account for the possibility of failures, you will also have to think about how to optimise your migrations so that they run swiftly, and the possibility that users will use your app while the migration process is occurring. If you have multiple databases, or if anything is remotely complicated, then don't blame me if anything goes wrong!

1. Create a migration

Run the following command in your terminal:

rails generate migration remove_fieldname_from_tablename fieldname:fieldtype

Note: the table name should be in plural form as per rails convention.

Example:

In my case I want to remove the accepted column (a boolean value) from the quotes table:

rails g migration RemoveAcceptedFromQuotes accepted:boolean

See the documentation re: a convention when adding/removing fields to a table:

There is a special syntactic shortcut to generate migrations that add fields to a table.

rails generate migration add_fieldname_to_tablename fieldname:fieldtype

2. Check the migration

# db/migrate/20190122035000_remove_accepted_from_quotes.rb
class RemoveAcceptedFromQuotes < ActiveRecord::Migration[5.2]
  # with rails 5.2 you don't need to add a separate "up" and "down" method.
  def change
    remove_column :quotes, :accepted, :boolean
  end
end

3. Run the migration

rake db:migrate or rails db:migrate (they're both the same)

....And then you're off to the races!

ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

As the error says your router link should match the existing routes configured

It should be just routerLink="/about"

How to print a single backslash?

You need to escape your backslash by preceding it with, yes, another backslash:

print("\\")

And for versions prior to Python 3:

print "\\"

The \ character is called an escape character, which interprets the character following it differently. For example, n by itself is simply a letter, but when you precede it with a backslash, it becomes \n, which is the newline character.

As you can probably guess, \ also needs to be escaped so it doesn't function like an escape character. You have to... escape the escape, essentially.

See the Python 3 documentation for string literals.

How can I use the HTML5 canvas element in IE?

You can try fxCanvas: https://code.google.com/p/fxcanvas/

It implements almost all Canvas API within flash shim.

CSS Pseudo-classes with inline styles

No, this is not possible. In documents that make use of CSS, an inline style attribute can only contain property declarations; the same set of statements that appears in each ruleset in a stylesheet. From the Style Attributes spec:

The value of the style attribute must match the syntax of the contents of a CSS declaration block (excluding the delimiting braces), whose formal grammar is given below in the terms and conventions of the CSS core grammar:

declaration-list
  : S* declaration? [ ';' S* declaration? ]*
  ;

Neither selectors (including pseudo-elements), nor at-rules, nor any other CSS construct are allowed.

Think of inline styles as the styles applied to some anonymous super-specific ID selector: those styles only apply to that one very element with the style attribute. (They take precedence over an ID selector in a stylesheet too, if that element has that ID.) Technically it doesn't work like that; this is just to help you understand why the attribute doesn't support pseudo-class or pseudo-element styles (it has more to do with how pseudo-classes and pseudo-elements provide abstractions of the document tree that can't be expressed in the document language).

Note that inline styles participate in the same cascade as selectors in rule sets, and take highest precedence in the cascade (!important notwithstanding). So they take precedence even over pseudo-class states. Allowing pseudo-classes or any other selectors in inline styles would possibly introduce a new cascade level, and with it a new set of complications.

Note also that very old revisions of the Style Attributes spec did originally propose allowing this, however it was scrapped, presumably for the reason given above, or because implementing it was not a viable option.

how to install gcc on windows 7 machine?

Download mingw-get and simply issue:

mingw-get install gcc.

See the Getting Started page.

Plot logarithmic axes with matplotlib in python

You simply need to use semilogy instead of plot:

from pylab import *
import matplotlib.pyplot  as pyplot
a = [ pow(10,i) for i in range(10) ]
fig = pyplot.figure()
ax = fig.add_subplot(2,1,1)

line, = ax.semilogy(a, color='blue', lw=2)
show()

How to check if element is visible after scrolling?

This method will return true if any part of the element is visible on the page. It worked better in my case and may help someone else.

function isOnScreen(element) {
  var elementOffsetTop = element.offset().top;
  var elementHeight = element.height();

  var screenScrollTop = $(window).scrollTop();
  var screenHeight = $(window).height();

  var scrollIsAboveElement = elementOffsetTop + elementHeight - screenScrollTop >= 0;
  var elementIsVisibleOnScreen = screenScrollTop + screenHeight - elementOffsetTop >= 0;

  return scrollIsAboveElement && elementIsVisibleOnScreen;
}

How to search for a part of a word with ElasticSearch

without changing your index mappings you could do a simple prefix query that will do partial searches like you are hoping for

ie.

{
  "query": { 
    "prefix" : { "name" : "Doe" }
  }
}

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-prefix-query.html

"Templates can be used only with field access, property access, single-dimension array index, or single-parameter custom indexer expressions" error

The ...For extension methods on the HtmlHelper (e.g., DisplayFor, TextBoxFor, ElementFor, etc...) take a property and nothing else. If you don't have a property, use the non-For method (e.g., Display, TextBox, Element, etc...).

The ...For extension methods provides a way of simplifying postback by naming the control after the property. This is why it takes an expression and not simply a value. If you are not interested in this postback facilitation then do not use the ...For methods at all.

Note: You should not be doing things like calling ToString inside the view. This should be done inside the view model. I realize that a lot of demo projects put domain objects straight into the view. In my experience, this rarely works because it assumes that you do not want any formatting on the data in the domain entity. Best practice is to create a view model that wraps the entity into something that can be directly consumed by the view. Most of the properties in this view model should be strings that are already formatted or data for which you have element or display templates created.

What would be the Unicode character for big bullet in the middle of the character?

If you are on Windows (Any Version)

Go to start -> then search character map

that's where you will find 1000s of characters with their Unicode in the advance view you can get more options that you can use for different encoding symbols.

How is the AND/OR operator represented as in Regular Expressions?

Not an expert in regex, but you can do ^((part1|part2)|(part1, part2))$. In words: "part 1 or part2 or both"

Error Message: Type or namespace definition, or end-of-file expected

  1. Make sure you have System.Web referenced
  2. Get rid of the two } at the end.

What is the significance of #pragma marks? Why do we need #pragma marks?

While searching for doc to point to about how pragma are directives for the compiler, I found this NSHipster article that does the job pretty well.

I hope you'll enjoy the reading

Filter Linq EXCEPT on properties

public static class ExceptByProperty
{
    public static List<T> ExceptBYProperty<T, TProperty>(this List<T> list, List<T> list2, Expression<Func<T, TProperty>> propertyLambda)
    {
        Type type = typeof(T);

        MemberExpression member = propertyLambda.Body as MemberExpression;

        if (member == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a method, not a property.",
                propertyLambda.ToString()));

        PropertyInfo propInfo = member.Member as PropertyInfo;
        if (propInfo == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a field, not a property.",
                propertyLambda.ToString()));

        if (type != propInfo.ReflectedType &&
            !type.IsSubclassOf(propInfo.ReflectedType))
            throw new ArgumentException(string.Format(
                "Expresion '{0}' refers to a property that is not from type {1}.",
                propertyLambda.ToString(),
                type));
        Func<T, TProperty> func = propertyLambda.Compile();
        var ids = list2.Select<T, TProperty>(x => func(x)).ToArray();
        return list.Where(i => !ids.Contains(((TProperty)propInfo.GetValue(i, null)))).ToList();
    }
}

public class testClass
{
    public int ID { get; set; }
    public string Name { get; set; }
}

For Test this:

        List<testClass> a = new List<testClass>();
        List<testClass> b = new List<testClass>();
        a.Add(new testClass() { ID = 1 });
        a.Add(new testClass() { ID = 2 });
        a.Add(new testClass() { ID = 3 });
        a.Add(new testClass() { ID = 4 });
        a.Add(new testClass() { ID = 5 });

        b.Add(new testClass() { ID = 3 });
        b.Add(new testClass() { ID = 5 });
        a.Select<testClass, int>(x => x.ID);

        var items = a.ExceptBYProperty(b, u => u.ID);

Android: How to change the ActionBar "Home" Icon to be something other than the app icon?

If you are using AppCompat, the only way to set the ActionBar icon on devices running Gingerbread (API 10) or below is by setting the android:icon attribute in every Activity in your manifest or setting the drawable programatically.

<manifest>
    <application>
        ...
        <activity android:name="com.your.ActivityName"
            ...
            android:icon="@drawable/ab_logo"/>
        ...
   </application>
</manifest>

Update: Be warned however that the application icon will be overridden if you set the android:icon attribute on the launch Activity. The only work around I know of is to have a splash or dummy Activity which then launches your main Activity.

SSH to AWS Instance without key pairs

AWS added a new feature to connect to instance without any open port, the AWS SSM Session Manager. https://aws.amazon.com/blogs/aws/new-session-manager/

I've created a neat SSH ProxyCommand script that temporary adds your public ssh key to target instance during connection to target instance. The nice thing about this is you will connect without the need to add the ssh(22) port to your security groups, because the ssh connection is tunneled through ssm session manager.

AWS SSM SSH ProxyComand -> https://gist.github.com/qoomon/fcf2c85194c55aee34b78ddcaa9e83a1

Matplotlib scatter plot legend

if you are using matplotlib version 3.1.1 or above, you can try:

import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

x = [1, 3, 4, 6, 7, 9]
y = [0, 0, 5, 8, 8, 8]
classes = ['A', 'B', 'C']
values = [0, 0, 1, 2, 2, 2]
colours = ListedColormap(['r','b','g'])
scatter = plt.scatter(x, y,c=values, cmap=colours)
plt.legend(handles=scatter.legend_elements()[0], labels=classes)

results2

How to plot a function curve in R

You mean like this?

> eq = function(x){x*x}
> plot(eq(1:1000), type='l')

Plot of eq over range 1:1000

(Or whatever range of values is relevant to your function)

Get screen width and height in Android

@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
  public static double getHeight() {
    DisplayMetrics displayMetrics = new DisplayMetrics();
    WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
    Display display = wm.getDefaultDisplay();
    display.getRealMetrics(displayMetrics);

    //int height = displayMetrics.heightPixels;
    //int width = displayMetrics.widthPixels;
    return displayMetrics.heightPixels;
  }

Using that method you can get screen height. if you want to get width change displayMetrics.heightPixels to displayMetrics.widthPixels.

And it also include required api Build version.

Limit characters displayed in span

You can use the CSS property max-width and use it with ch unit.
And, as this is a <span>, use a display: inline-block; (or block).

Here is an example:

<span style="
  display:inline-block;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 13ch;">
Lorem ipsum dolor sit amet
</span>

Which outputs:

Lorem ipsum...

_x000D_
_x000D_
<span style="_x000D_
  display:inline-block;_x000D_
  white-space: nowrap;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  max-width: 13ch;">_x000D_
Lorem ipsum dolor sit amet_x000D_
</span>
_x000D_
_x000D_
_x000D_

What are the uses of "using" in C#?

Things like this:

using (var conn = new SqlConnection("connection string"))
{
   conn.Open();

    // Execute SQL statement here on the connection you created
}

This SqlConnection will be closed without needing to explicitly call the .Close() function, and this will happen even if an exception is thrown, without the need for a try/catch/finally.

do-while loop in R

Pretty self explanatory.

repeat{
  statements...
  if(condition){
    break
  }
}

Or something like that I would think. To get the effect of the do while loop, simply check for your condition at the end of the group of statements.

How to get the ASCII value in JavaScript for the characters

Here is the example:

_x000D_
_x000D_
var charCode = "a".charCodeAt(0);_x000D_
console.log(charCode);
_x000D_
_x000D_
_x000D_

Or if you have longer strings:

_x000D_
_x000D_
var string = "Some string";_x000D_
_x000D_
for (var i = 0; i < string.length; i++) {_x000D_
  console.log(string.charCodeAt(i));_x000D_
}
_x000D_
_x000D_
_x000D_

String.charCodeAt(x) method will return ASCII character code at a given position.

error MSB6006: "cmd.exe" exited with code 1

I solved this. double click this error leads to behavior.

  1. open .vcxproj file of your project
  2. search for tag
  3. check carefully what's going inside this tag, the path is right? difference between debug and release, and fix it
  4. clean and rebuild

for my case. a miss match of debug and release mod kills my afternoon.

          <Command Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">copy ..\vc2005\%(Filename)%(Extension) ..\..\cvd\
</Command>
      <Command Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">copy ..\vc2005\%(Filename)%(Extension) ..\..\cvd\
</Command>
      <Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
      <Outputs Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
      <Command Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">copy ..\vc2005\%(Filename)%(Extension) ..\..\cvd\
</Command>
      <Command Condition="'$(Configuration)|$(Platform)'=='Release|x64'">copy %(Filename)%(Extension) ..\..\cvd\
</Command>
      <Outputs Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
      <Outputs Condition="'$(Configuration)|$(Platform)'=='Release|x64'">..\..\cvd\%(Filename)%(Extension);%(Outputs)</Outputs>
    </CustomBuild>

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

Liam's link looks great, but also check out pandas.Timedelta - looks like it plays nicely with NumPy's and Python's time deltas.

https://pandas.pydata.org/pandas-docs/stable/timedeltas.html

pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)

Set a button background image iPhone programmatically

Complete code:

+ (UIButton *)buttonWithTitle:(NSString *)title
                       target:(id)target
                     selector:(SEL)selector
                        frame:(CGRect)frame
                        image:(UIImage *)image
                 imagePressed:(UIImage *)imagePressed
                darkTextColor:(BOOL)darkTextColor
{
    UIButton *button = [[UIButton alloc] initWithFrame:frame];

    button.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;

    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];


    UIImage *newImage = [image stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
    [button setBackgroundImage:newImage forState:UIControlStateNormal];

    UIImage *newPressedImage = [imagePressed stretchableImageWithLeftCapWidth:12.0 topCapHeight:0.0];
    [button setBackgroundImage:newPressedImage forState:UIControlStateHighlighted];

    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];

    // in case the parent view draws with a custom color or gradient, use a transparent color
    button.backgroundColor = [UIColor clearColor];

    return button;
}

UIImage *buttonBackground = UIImage imageNamed:@"whiteButton.png";
UIImage *buttonBackgroundPressed = UIImage imageNamed:@"blueButton.png";

CGRect frame = CGRectMake(0.0, 0.0, kStdButtonWidth, kStdButtonHeight);

UIButton *button = [FinishedStatsView buttonWithTitle:title
                                               target:target
                                             selector:action
                                                frame:frame
                                                image:buttonBackground
                                         imagePressed:buttonBackgroundPressed
                                        darkTextColor:YES];

[self addSubview:button]; 

To set an image:

UIImage *buttonImage = [UIImage imageNamed:@"Home.png"];
[myButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:myButton];

To remove an image:

[button setBackgroundImage:nil forState:UIControlStateNormal];

How to use Tomcat 8 in Eclipse?

I follow Jason's step, but not works.

And then I find the WTP Update site http://download.eclipse.org/webtools/updates/.

Help -> Install new software -> Add > WTP:http://download.eclipse.org/webtools/updates/ -> OK

Then Help -> Check for update, just works, I don't know whether Jason's affect this .

Removing display of row names from data frame

If you want to format your table via kable, you can use row.names = F

kable(df, row.names = F)

phpMyAdmin - can't connect - invalid setings - ever since I added a root password - locked out

1) Go to your Xampp Root folder

For Ex : C:xampp/phpmyadmin/config.inc.php

2) In that find the following :

$cfg['servers'][$i]['password'] = '';

3) Here enter which password you set.

Ex : $cfg['servers'][$i]['password'] = '1234';

4) Then Save it and Restart your Xamp server.

Detecting touch screen devices with Javascript

return (('ontouchstart' in window)
      || (navigator.maxTouchPoints > 0)
      || (navigator.msMaxTouchPoints > 0));

Reason for using maxTouchPoints alongwith msMaxTouchPoints:

Microsoft has stated that starting with Internet Explorer 11, Microsoft vendor prefixed version of this property (msMaxTouchPoints) may be removed and recommends using maxTouchPoints instead.

Source : http://ctrlq.org/code/19616-detect-touch-screen-javascript

Angular: date filter adds timezone, how to output UTC?

Since version 1.3.0 AngularJS introduced extra filter parameter timezone, like following:

{{ date_expression | date : format : timezone}}

But in versions 1.3.x only supported timezone is UTC, which can be used as following:

{{ someDate | date: 'MMM d, y H:mm:ss' : 'UTC' }}

Since version 1.4.0-rc.0 AngularJS supports other timezones too. I was not testing all possible timezones, but here's for example how you can get date in Japan Standard Time (JSP, GMT +9):

{{ clock | date: 'MMM d, y H:mm:ss' : '+0900' }}

Here you can find documentation of AngularJS date filters.

NOTE: this is working only with Angular 1.x

Here's working example

How can I load storyboard programmatically from class?

The extension below will allow you to load a Storyboard and it's associated UIViewController. Example: If you have a UIViewController named ModalAlertViewController and a storyboard named "ModalAlert" e.g.

let vc: ModalAlertViewController = UIViewController.loadStoryboard("ModalAlert")

Will load both the Storyboard and UIViewController and vc will be of type ModalAlertViewController. Note Assumes that the storyboard's Storyboard ID has the same name as the storyboard and that the storyboard has been marked as Is Initial View Controller.

extension UIViewController {
    /// Loads a `UIViewController` of type `T` with storyboard. Assumes that the storyboards Storyboard ID has the same name as the storyboard and that the storyboard has been marked as Is Initial View Controller.
    /// - Parameter storyboardName: Name of the storyboard without .xib/nib suffix.
    static func loadStoryboard<T: UIViewController>(_ storyboardName: String) -> T? {
        let storyboard = UIStoryboard(name: storyboardName, bundle: nil)
        if let vc = storyboard.instantiateViewController(withIdentifier: storyboardName) as? T {
            vc.loadViewIfNeeded() // ensures vc.view is loaded before returning
            return vc
        }
        return nil
    }
}

converting date time to 24 hour format

Try this:

Date date=new Date("12/12/11 8:22:09 PM");    
System.out.println("Time in 24Hours ="+new SimpleDateFormat("HH:mm").format(date));

How to press/click the button using Selenium if the button does not have the Id?

For Next button you can use xpath or cssSelector as below:

xpath for Next button: //input[@value='Next']

cssPath for Next button: input[value=Next]

Read input numbers separated by spaces

I would recommend reading in the line into a string, then splitting it based on the spaces. For this, you can use the getline(...) function. The trick is having a dynamic sized data structure to hold the strings once it's split. Probably the easiest to use would be a vector.

#include <string>
#include <vector>
...
  string rawInput;
  vector<String> numbers;
  while( getline( cin, rawInput, ' ' ) )
  {
    numbers.push_back(rawInput);
  }

So say the input looks like this:

Enter a number, or numbers separated by a space, between 1 and 1000.
10 5 20 1 200 7

You will now have a vector, numbers, that contains the elements: {"10","5","20","1","200","7"}.

Note that these are still strings, so not useful in arithmetic. To convert them to integers, we use a combination of the STL function, atoi(...), and because atoi requires a c-string instead of a c++ style string, we use the string class' c_str() member function.

while(!numbers.empty())
{
  string temp = numbers.pop_back();//removes the last element from the string
  num = atoi( temp.c_str() ); //re-used your 'num' variable from your code

  ...//do stuff
}

Now there's some problems with this code. Yes, it runs, but it is kind of clunky, and it puts the numbers out in reverse order. Lets re-write it so that it is a little more compact:

#include <string>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
  num = atoi( rawInput.c_str() );
  ...//do your stuff
}

There's still lots of room for improvement with error handling (right now if you enter a non-number the program will crash), and there's infinitely more ways to actually handle the input to get it in a usable number form (the joys of programming!), but that should give you a comprehensive start. :)

Note: I had the reference pages as links, but I cannot post more than two since I have less than 15 posts :/

Edit: I was a little bit wrong about the atoi behavior; I confused it with Java's string->Integer conversions which throw a Not-A-Number exception when given a string that isn't a number, and then crashes the program if the exception isn't handled. atoi(), on the other hand, returns 0, which is not as helpful because what if 0 is the number they entered? Let's make use of the isdigit(...) function. An important thing to note here is that c++ style strings can be accessed like an array, meaning rawInput[0] is the first character in the string all the way up to rawInput[length - 1].

#include <string>
#include <ctype.h>
...
string rawInput;
cout << "Enter a number, or numbers separated by a space, between 1 and 1000." << endl;
while( getline( cin, rawInput, ' ') )
{
  bool isNum = true;
  for(int i = 0; i < rawInput.length() && isNum; ++i)
  {
    isNum = isdigit( rawInput[i]);
  }

  if(isNum)
  {
    num = atoi( rawInput.c_str() );
    ...//do your stuff
  }
  else
    cout << rawInput << " is not a number!" << endl;
}

The boolean (true/false or 1/0 respectively) is used as a flag for the for-loop, which steps through each character in the string and checks to see if it is a 0-9 digit. If any character in the string is not a digit, the loop will break during it's next execution when it gets to the condition "&& isNum" (assuming you've covered loops already). Then after the loop, isNum is used to determine whether to do your stuff, or to print the error message.

Excel how to find values in 1 column exist in the range of values in another

This is what you need:

 =NOT(ISERROR(MATCH(<cell in col A>,<column B>, 0)))  ## pseudo code

For the first cell of A, this would be:

 =NOT(ISERROR(MATCH(A2,$B$2:$B$5, 0)))

Enter formula (and drag down) as follows:

enter image description here

You will get:

enter image description here

Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'

Try to change this: <csrf /> to this : <csrf disabled="true"/>. It should disable csfr.

PHP new line break in emails

I know this is an old question but anyway it might help someone.

I tend to use PHP_EOL for this purposes (due to cross-platform compatibility).

echo "line 1".PHP_EOL."line 2".PHP_EOL;

If you're planning to show the result in a browser then you have to use "<br>".

EDIT: since your exact question is about emails, things are a bit different. For pure text emails see Brendan Bullen's accepted answer. For HTML emails you simply use HTML formatting.

Getting a POST variable

Use this for GET values:

Request.QueryString["key"]

And this for POST values

Request.Form["key"]

Also, this will work if you don't care whether it comes from GET or POST, or the HttpContext.Items collection:

Request["key"]

Another thing to note (if you need it) is you can check the type of request by using:

Request.RequestType

Which will be the verb used to access the page (usually GET or POST). Request.IsPostBack will usually work to check this, but only if the POST request includes the hidden fields added to the page by the ASP.NET framework.

How can I update NodeJS and NPM to the next versions?

Use n module from npm in order to upgrade node . n is a node helper package that installs or updates a given node.js version.

sudo npm cache clean -f
sudo npm install -g n
sudo n stable
sudo ln -sf /usr/local/n/versions/node/<VERSION>/bin/node /usr/bin/nodejs

NOTE that the default installation for nodejs is in the /usr/bin/nodejs and not /usr/bin/node

To upgrade to latest version (and not current stable) version, you can use

sudo n latest

To undo:

sudo apt-get install --reinstall nodejs-legacy     # fix /usr/bin/node
sudo n rm 6.0.0     # replace number with version of Node that was installed
sudo npm uninstall -g n

If you get the following error bash: /usr/bin/node: No such file or directory then the path you have entered at

sudo ln -sf /usr/local/n/versions/node/<VERSION>/bin/node /usr/bin/nodejs

if wrong. so make sure to check if the update nodejs has been installed at the above path and the version you are entered is correct.

I would advise strongly against doing this on a production instance. It can seriously mess stuff up with your global npm packages and your ability to install new one.

How do I create a GUI for a windows application using C++?

I have used wxWidgets for small project and I loved it. Qt is another good choice but for commercial use you would probably need to buy a licence. If you write in C++ don't use Win32 API as you will end up making it object oriented. This is not easy and time consuming. Also Win32 API has too many macros and feels over complicated for what it offers.

Spring MVC - Why not able to use @RequestBody and @RequestParam together

It happens because of not very straight forward Servlet specification. If you are working with a native HttpServletRequest implementation you cannot get both the URL encode body and the parameters. Spring does some workarounds, which make it even more strange and nontransparent.

In such cases Spring (version 3.2.4) re-renders a body for you using data from the getParameterMap() method. It mixes GET and POST parameters and breaks the parameter order. The class, which is responsible for the chaos is ServletServerHttpRequest. Unfortunately it cannot be replaced, but the class StringHttpMessageConverter can be.

The clean solution is unfortunately not simple:

  1. Replacing StringHttpMessageConverter. Copy/Overwrite the original class adjusting method readInternal().
  2. Wrapping HttpServletRequest overwriting getInputStream(), getReader() and getParameter*() methods.

In the method StringHttpMessageConverter#readInternal following code must be used:

    if (inputMessage instanceof ServletServerHttpRequest) {
        ServletServerHttpRequest oo = (ServletServerHttpRequest)inputMessage;
        input = oo.getServletRequest().getInputStream();
    } else {
        input = inputMessage.getBody();
    }

Then the converter must be registered in the context.

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true/false">
        <bean class="my-new-converter-class"/>
   </mvc:message-converters>
</mvc:annotation-driven>

The step two is described here: Http Servlet request lose params from POST body after read it once

Why .NET String is immutable?

  1. Instances of immutable types are inherently thread-safe, since no thread can modify it, the risk of a thread modifying it in a way that interferes with another is removed (the reference itself is a different matter).
  2. Similarly, the fact that aliasing can't produce changes (if x and y both refer to the same object a change to x entails a change to y) allows for considerable compiler optimisations.
  3. Memory-saving optimisations are also possible. Interning and atomising being the most obvious examples, though we can do other versions of the same principle. I once produced a memory saving of about half a GB by comparing immutable objects and replacing references to duplicates so that they all pointed to the same instance (time-consuming, but a minute's extra start-up to save a massive amount of memory was a performance win in the case in question). With mutable objects that can't be done.
  4. No side-effects can come from passing an immutable type as a method to a parameter unless it is out or ref (since that changes the reference, not the object). A programmer therefore knows that if string x = "abc" at the start of a method, and that doesn't change in the body of the method, then x == "abc" at the end of the method.
  5. Conceptually, the semantics are more like value types; in particular equality is based on state rather than identity. This means that "abc" == "ab" + "c". While this doesn't require immutability, the fact that a reference to such a string will always equal "abc" throughout its lifetime (which does require immutability) makes uses as keys where maintaining equality to previous values is vital, much easier to ensure correctness of (strings are indeed commonly used as keys).
  6. Conceptually, it can make more sense to be immutable. If we add a month onto Christmas, we haven't changed Christmas, we have produced a new date in late January. It makes sense therefore that Christmas.AddMonths(1) produces a new DateTime rather than changing a mutable one. (Another example, if I as a mutable object change my name, what has changed is which name I am using, "Jon" remains immutable and other Jons will be unaffected.
  7. Copying is fast and simple, to create a clone just return this. Since the copy can't be changed anyway, pretending something is its own copy is safe.
  8. [Edit, I'd forgotten this one]. Internal state can be safely shared between objects. For example, if you were implementing list which was backed by an array, a start index and a count, then the most expensive part of creating a sub-range would be copying the objects. However, if it was immutable then the sub-range object could reference the same array, with only the start index and count having to change, with a very considerable change to construction time.

In all, for objects which don't have undergoing change as part of their purpose, there can be many advantages in being immutable. The main disadvantage is in requiring extra constructions, though even here it's often overstated (remember, you have to do several appends before StringBuilder becomes more efficient than the equivalent series of concatenations, with their inherent construction).

It would be a disadvantage if mutability was part of the purpose of an object (who'd want to be modeled by an Employee object whose salary could never ever change) though sometimes even then it can be useful (in a many web and other stateless applications, code doing read operations is separate from that doing updates, and using different objects may be natural - I wouldn't make an object immutable and then force that pattern, but if I already had that pattern I might make my "read" objects immutable for the performance and correctness-guarantee gain).

Copy-on-write is a middle ground. Here the "real" class holds a reference to a "state" class. State classes are shared on copy operations, but if you change the state, a new copy of the state class is created. This is more often used with C++ than C#, which is why it's std:string enjoys some, but not all, of the advantages of immutable types, while remaining mutable.

How to pass parameters using ui-sref in ui-router to controller

I've created an example to show how to. Updated state definition would be:

  $stateProvider
    .state('home', {
      url: '/:foo?bar',
      views: {
        '': {
          templateUrl: 'tpl.home.html',
          controller: 'MainRootCtrl'

        },
        ...
      }

And this would be the controller:

.controller('MainRootCtrl', function($scope, $state, $stateParams) {
    //..
    var foo = $stateParams.foo; //getting fooVal
    var bar = $stateParams.bar; //getting barVal
    //..
    $scope.state = $state.current
    $scope.params = $stateParams; 
})

What we can see is that the state home now has url defined as:

url: '/:foo?bar',

which means, that the params in url are expected as

/fooVal?bar=barValue

These two links will correctly pass arguments into the controller:

<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})">
<a ui-sref="home({foo: 'fooVal2', bar: 'barVal2'})">

Also, the controller does consume $stateParams instead of $stateParam.

Link to doc:

You can check it here

params : {}

There is also new, more granular setting params : {}. As we've already seen, we can declare parameters as part of url. But with params : {} configuration - we can extend this definition or even introduce paramters which are not part of the url:

.state('other', {
    url: '/other/:foo?bar',
    params: { 
        // here we define default value for foo
        // we also set squash to false, to force injecting
        // even the default value into url
        foo: {
          value: 'defaultValue',
          squash: false,
        },
        // this parameter is now array
        // we can pass more items, and expect them as []
        bar : { 
          array : true,
        },
        // this param is not part of url
        // it could be passed with $state.go or ui-sref 
        hiddenParam: 'YES',
      },
    ...

Settings available for params are described in the documentation of the $stateProvider

Below is just an extract

  • value - {object|function=}: specifies the default value for this parameter. This implicitly sets this parameter as optional...
  • array - {boolean=}: (default: false) If true, the param value will be treated as an array of values.
  • squash - {bool|string=}: squash configures how a default parameter value is represented in the URL when the current parameter value is the same as the default value.

We can call these params this way:

// hidden param cannot be passed via url
<a href="#/other/fooVal?bar=1&amp;bar=2">
// default foo is skipped
<a ui-sref="other({bar: [4,5]})">

Check it in action here

C++ program converts fahrenheit to celsius

The answer has already been found although I would also like to share my answer:

int main(void)
{
using namespace std;

short tempC;
cout << "Please enter a Celsius value: ";
cin >> tempC;
double tempF = convert(tempC);
cout << tempC << " degrees Celsius is " << tempF << " degrees Fahrenheit." << endl;
cin.get();
cin.get();
return 0;

}

int convert(short nT)
{
return nT * 1.8 + 32;
}

This is a more proper way to do this; however, it is slightly more complex then what you were going for.

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

That's the error you get when a function makes too many recursive calls to itself. It might be doing this because the base case is never met (and therefore it gets stuck in an infinite loop) or just by making an large number of calls to itself. You could replace the recursive calls with while loops.

Understanding Bootstrap's clearfix class

The :before pseudo element isn't needed for the clearfix hack itself.

It's just an additional nice feature helping to prevent margin-collapsing of the first child element. Thus the top margin of an child block element of the "clearfixed" element is guaranteed to be positioned below the top border of the clearfixed element.

display:table is being used because display:block doesn't do the trick. Using display:block margins will collapse even with a :before element.

There is one caveat: if vertical-align:baseline is used in table cells with clearfixed <div> elements, Firefox won't align well. Then you might prefer using display:block despite loosing the anti-collapsing feature. In case of further interest read this article: Clearfix interfering with vertical-align.

VBA Excel Provide current Date in Text box

Set the value from code on showing the form, not in the design-timeProperties for the text box.

Private Sub UserForm_Activate()
    Me.txtDate.Value = Format(Date, "mm/dd/yy")
End Sub

Uninstall old versions of Ruby gems

# remove all old versions of the gem
gem cleanup rjb

# choose which ones you want to remove
gem uninstall rjb

# remove version 1.1.9 only
gem uninstall rjb --version 1.1.9

# remove all versions less than 1.3.4
gem uninstall rjb --version '<1.3.4'

Can my enums have friendly names?

I suppose that you want to show your enum values to the user, therefore, you want them to have some friendly name.

Here's my suggestion:

Use an enum type pattern. Although it takes some effort to implement, it is really worth it.

public class MyEnum
{  
    public static readonly MyEnum Enum1=new MyEnum("This will work",1);
    public static readonly MyEnum Enum2=new MyEnum("This.will.work.either",2);
    public static readonly MyEnum[] All=new []{Enum1,Enum2};
    private MyEnum(string name,int value)
    {
        Name=name;
        Value=value;
    }

    public string Name{get;set;}
    public int Value{get;set;}

    public override string ToString()
    {
        return Name;    
    }
}

Implement touch using Python?

"open(file_name, 'a').close()" did not work for me in Python 2.7 on Windows. "os.utime(file_name, None)" worked just fine.

Also, I had a need to recursively touch all files in a directory with a date older than some date. I created hte following based on ephemient's very helpful response.

def touch(file_name):
    # Update the modified timestamp of a file to now.
    if not os.path.exists(file_name):
        return
    try:
        os.utime(file_name, None)
    except Exception:
        open(file_name, 'a').close()

def midas_touch(root_path, older_than=dt.now(), pattern='**', recursive=False):
    '''
    midas_touch updates the modified timestamp of a file or files in a 
                directory (folder)

    Arguements:
        root_path (str): file name or folder name of file-like object to touch
        older_than (datetime): only touch files with datetime older than this 
                   datetime
        pattern (str): filter files with this pattern (ignored if root_path is
                a single file)
        recursive (boolean): search sub-diretories (ignored if root_path is a 
                  single file)
    '''
    # if root_path NOT exist, exit
    if not os.path.exists(root_path):
        return
    # if root_path DOES exist, continue.
    else:
        # if root_path is a directory, touch all files in root_path
        if os.path.isdir(root_path):
            # get a directory list (list of files in directory)
            dir_list=find_files(root_path, pattern='**', recursive=False)
            # loop through list of files
            for f in dir_list:
                # if the file modified date is older thatn older_than, touch the file
                if dt.fromtimestamp(os.path.getmtime(f)) < older_than:
                    touch(f)
                    print "Touched ", f
        # if root_path is a file, touch the file
        else:
            # if the file modified date is older thatn older_than, touch the file
            if dt.fromtimestamp(os.path.getmtime(f)) < older_than:
                touch(root_path)

String.replaceAll single backslashes with double backslashes

TLDR: use theString = theString.replace("\\", "\\\\"); instead.


Problem

replaceAll(target, replacement) uses regular expression (regex) syntax for target and partially for replacement.

Problem is that \ is special character in regex (it can be used like \d to represents digit) and in String literal (it can be used like "\n" to represent line separator or \" to escape double quote symbol which normally would represent end of string literal).

In both these cases to create \ symbol we can escape it (make it literal instead of special character) by placing additional \ before it (like we escape " in string literals via \").

So to target regex representing \ symbol will need to hold \\, and string literal representing such text will need to look like "\\\\".

So we escaped \ twice:

  • once in regex \\
  • once in String literal "\\\\" (each \ is represented as "\\").

In case of replacement \ is also special there. It allows us to escape other special character $ which via $x notation, allows us to use portion of data matched by regex and held by capturing group indexed as x, like "012".replaceAll("(\\d)", "$1$1") will match each digit, place it in capturing group 1 and $1$1 will replace it with its two copies (it will duplicate it) resulting in "001122".

So again, to let replacement represent \ literal we need to escape it with additional \ which means that:

  • replacement must hold two backslash characters \\
  • and String literal which represents \\ looks like "\\\\"

BUT since we want replacement to hold two backslashes we will need "\\\\\\\\" (each \ represented by one "\\\\").

So version with replaceAll can look like

replaceAll("\\\\", "\\\\\\\\");

Easier way

To make out life easier Java provides tools to automatically escape text into target and replacement parts. So now we can focus only on strings, and forget about regex syntax:

replaceAll(Pattern.quote(target), Matcher.quoteReplacement(replacement))

which in our case can look like

replaceAll(Pattern.quote("\\"), Matcher.quoteReplacement("\\\\"))

Even better

If we don't really need regex syntax support lets not involve replaceAll at all. Instead lets use replace. Both methods will replace all targets, but replace doesn't involve regex syntax. So you could simply write

theString = theString.replace("\\", "\\\\");

How can I draw circle through XML Drawable - Android?

no need for the padding or the corners.

here's a sample:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
        android:angle="270"/>
</shape>

based on :

https://stackoverflow.com/a/10104037/878126

Removing the title text of an iOS UIBarButtonItem

[[UIBarButtonItem appearance] setBackButtonTitlePositionAdjustment:UIOffsetMake(-60, -60)
                                                         forBarMetrics:UIBarMetricsDefault];

Then you can remove the back button item title.

If you use Storyboard, you can set navigation attributes inspector Back Button with space.

What is w3wp.exe?

An Internet Information Services (IIS) worker process is a windows process (w3wp.exe) which runs Web applications, and is responsible for handling requests sent to a Web Server for a specific application pool.

It is the worker process for IIS. Each application pool creates at least one instance of w3wp.exe and that is what actually processes requests in your application. It is not dangerous to attach to this, that is just a standard windows message.

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

This can be fixed by changing your URL, example bad:

https://raw.githubusercontent.com/svnpenn/bm/master/yt-dl/yt-dl.js
Content-Type: text/plain; charset=utf-8

Example good:

https://cdn.rawgit.com/svnpenn/bm/master/yt-dl/yt-dl.js
content-type: application/javascript;charset=utf-8

rawgit.com is a caching proxy service for github. You can also go there and interactively derive a corresponding URL for your original raw.githubusercontent.com URL. See its FAQ

Echo newline in Bash prints literal \n

Sometimes you can pass multiple strings separated by a space and it will be interpreted as \n.

For example when using a shell script for multi-line notifcations:

#!/bin/bash
notify-send 'notification success' 'another line' 'time now '`date +"%s"`

Find MongoDB records where array field is not empty

After some more looking, especially in the mongodb documents, and puzzling bits together, this was the answer:

ME.find({pictures: {$exists: true, $not: {$size: 0}}})

How can I determine the character encoding of an excel file?

For Excel 2010 it should be UTF-8. Instruction by MS :
http://msdn.microsoft.com/en-us/library/bb507946:

"The basic document structure of a SpreadsheetML document consists of the Sheets and Sheet elements, which reference the worksheets in the Workbook. A separate XML file is created for each Worksheet. For example, the SpreadsheetML for a workbook that has two worksheets name MySheet1 and MySheet2 is located in the Workbook.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?> 
<workbook xmlns=http://schemas.openxmlformats.org/spreadsheetml/2006/main xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
    <sheets>
        <sheet name="MySheet1" sheetId="1" r:id="rId1" /> 
        <sheet name="MySheet2" sheetId="2" r:id="rId2" /> 
    </sheets>
</workbook>

The worksheet XML files contain one or more block level elements such as SheetData. sheetData represents the cell table and contains one or more Row elements. A row contains one or more Cell elements. Each cell contains a CellValue element that represents the value of the cell. For example, the SpreadsheetML for the first worksheet in a workbook, that only has the value 100 in cell A1, is located in the Sheet1.xml file and is shown in the following code example.

<?xml version="1.0" encoding="UTF-8" ?> 
<worksheet xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
    <sheetData>
        <row r="1">
            <c r="A1">
                <v>100</v> 
            </c>
        </row>
    </sheetData>
</worksheet>

"

Detection of cell encodings:

https://metacpan.org/pod/Spreadsheet::ParseExcel::Cell

http://forums.asp.net/t/1608228.aspx/1

XML Schema How to Restrict Attribute by Enumeration

New answer to old question

None of the existing answers to this old question address the real problem.

The real problem was that xs:complexType cannot directly have a xs:extension as a child in XSD. The fix is to use xs:simpleContent first. Details follow...


Your XML,

<price currency="euros">20000.00</price>

will be valid against either of the following corrected XSDs:

Locally defined attribute type

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:element name="price">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:decimal">
          <xs:attribute name="currency">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:enumeration value="pounds" />
                <xs:enumeration value="euros" />
                <xs:enumeration value="dollars" />
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

Globally defined attribute type

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:simpleType name="currencyType">
    <xs:restriction base="xs:string">
      <xs:enumeration value="pounds" />
      <xs:enumeration value="euros" />
      <xs:enumeration value="dollars" />
    </xs:restriction>
  </xs:simpleType>

  <xs:element name="price">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:decimal">
          <xs:attribute name="currency" type="currencyType"/>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

Notes

  • As commented by @Paul, these do change the content type of price from xs:string to xs:decimal, but this is not strictly necessary and was not the real problem.
  • As answered by @user998692, you could separate out the definition of currency, and you could change to xs:decimal, but this too was not the real problem.

The real problem was that xs:complexType cannot directly have a xs:extension as a child in XSD; xs:simpleContent is needed first.

A related matter (that wasn't asked but may have confused other answers):

How could price be restricted given that it has an attribute?

In this case, a separate, global definition of priceType would be needed; it is not possible to do this with only local type definitions.

How to restrict element content when element has attribute

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">

  <xs:simpleType name="priceType">  
    <xs:restriction base="xs:decimal">  
      <xs:minInclusive value="0.00"/>  
      <xs:maxInclusive value="99999.99"/>  
    </xs:restriction>  
  </xs:simpleType>

  <xs:element name="price">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="priceType">
          <xs:attribute name="currency">
            <xs:simpleType>
              <xs:restriction base="xs:string">
                <xs:enumeration value="pounds" />
                <xs:enumeration value="euros" />
                <xs:enumeration value="dollars" />
              </xs:restriction>
            </xs:simpleType>
          </xs:attribute>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
</xs:schema>

Appending a list or series to a pandas DataFrame as a row?

simply use loc:

>>> df
     A  B  C
one  1  2  3
>>> df.loc["two"] = [4,5,6]
>>> df
     A  B  C
one  1  2  3
two  4  5  6

How do I clone a specific Git branch?

git --branch <branchname> <url>

But bash completion don't get this key: --branch

Best way to script remote SSH commands in Batch (Windows)

You can also use Bash on Ubuntu on Windows directly. E.g.,

bash -c "ssh -t user@computer 'cd /; sudo my-command'"

Per Martin Prikryl's comment below:

The -t enables terminal emulation. Whether you need the terminal emulation for sudo depends on configuration (and by default you do no need it, while many distributions override the default). On the contrary, many other commands need terminal emulation.

How to add new elements to an array?

I've made this code! It works like a charm!

public String[] AddToStringArray(String[] oldArray, String newString)
{
    String[] newArray = Arrays.copyOf(oldArray, oldArray.length+1);
    newArray[oldArray.length] = newString;
    return newArray;
}

I hope you like it!!

Perform an action in every sub-directory using Bash

Handy one-liners

for D in *; do echo "$D"; done
for D in *; do find "$D" -type d; done ### Option A

find * -type d ### Option B

Option A is correct for folders with spaces in between. Also, generally faster since it doesn't print each word in a folder name as a separate entity.

# Option A
$ time for D in ./big_dir/*; do find "$D" -type d > /dev/null; done
real    0m0.327s
user    0m0.084s
sys     0m0.236s

# Option B
$ time for D in `find ./big_dir/* -type d`; do echo "$D" > /dev/null; done
real    0m0.787s
user    0m0.484s
sys     0m0.308s

Using IQueryable with Linq

It allows for further querying further down the line. If this was beyond a service boundary say, then the user of this IQueryable object would be allowed to do more with it.

For instance if you were using lazy loading with nhibernate this might result in graph being loaded when/if needed.

Error message: "'chromedriver' executable needs to be available in the path"

Add the webdriver(chromedriver.exe or geckodriver.exe) here C:\Windows. This worked in my case

How do I get a platform-dependent new line character?

You can use

System.getProperty("line.separator");

to get the line separator

How to filter multiple values (OR operation) in angularJS

Creating a custom filter might be overkill here, you can just pass in a custom comparator, if you have the multiples values like:

$scope.selectedGenres = "Action, Drama"; 

$scope.containsComparator = function(expected, actual){  
  return actual.indexOf(expected) > -1;
};

then in the filter:

filter:{name:selectedGenres}:containsComparator

How to turn off word wrapping in HTML?

white-space: nowrap;: Will never break text, will keep other defaults

white-space: pre;: Will never break text, will keep multiple spaces after one another as multiple spaces, will break if explicitly written to break(pressing enter in html etc)

When to use static methods

No, static methods aren't associated with an instance; they belong to the class. Static methods are your second example; instance methods are the first.

How to convert a string variable containing time to time_t type in c++?

With C++11 you can now do

struct std::tm tm;
std::istringstream ss("16:35:12");
ss >> std::get_time(&tm, "%H:%M:%S"); // or just %T in this case
std::time_t time = mktime(&tm);

see std::get_time and strftime for reference

Starting a shell in the Docker Alpine container

Usually, an Alpine Linux image doesn't contain bash, Instead you can use /bin/ash, /bin/sh, ash or only sh.

/bin/ash

docker run -it --rm alpine /bin/ash

/bin/sh

docker run -it --rm alpine /bin/sh

ash

docker run -it --rm alpine ash

sh

docker run -it --rm alpine sh

I hope this information helps you.

Checking Date format from a string in C#

you could always try:

Regex r = new Regex(@"\d{2}/\d{2}/\d{4}");

r.isMatch(inputString);

this will check that the string is in the format "02/02/2002" you may need a bit more if you want to ensure that it is a valid date like dd/mm/yyyy

Check if PHP session has already started

you can do this, and it's really easy.

if (!isset($_SESSION)) session_start();

Hope it helps :)

MVC3 EditorFor readOnly

Here's how I do it:

Model:

[ReadOnly(true)]
public string Email { get { return DbUser.Email; } }

View:

@Html.TheEditorFor(x => x.Email)

Extension:

namespace System.Web.Mvc
{
    public static class CustomExtensions
    {
        public static MvcHtmlString TheEditorFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, object htmlAttributes = null)
        {
            return iEREditorForInternal(htmlHelper, expression, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
        }

        private static MvcHtmlString iEREditorForInternal<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IDictionary<string, object> htmlAttributes)
        {
            if (htmlAttributes == null) htmlAttributes = new Dictionary<string, object>();

            TagBuilder builder = new TagBuilder("div");
            builder.MergeAttributes(htmlAttributes);

            var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);


            string labelHtml = labelHtml = Html.LabelExtensions.LabelFor(htmlHelper, expression).ToHtmlString();

            if (metadata.IsRequired)
                labelHtml = Html.LabelExtensions.LabelFor(htmlHelper, expression, new { @class = "required" }).ToHtmlString();


            string editorHtml = Html.EditorExtensions.EditorFor(htmlHelper, expression).ToHtmlString();

            if (metadata.IsReadOnly)
                editorHtml = Html.DisplayExtensions.DisplayFor(htmlHelper, expression).ToHtmlString();


            string validationHtml = Html.ValidationExtensions.ValidationMessageFor(htmlHelper, expression).ToHtmlString();

            builder.InnerHtml = labelHtml + editorHtml + validationHtml;

            return new MvcHtmlString(builder.ToString(TagRenderMode.Normal));
        }
    }
}

Of course my editor is doing a bunch more stuff, like adding a label, adding a required class to that label as necessary, adding a DisplayFor if the property is ReadOnly EditorFor if its not, adding a ValidateMessageFor and finally wrapping all of that in a Div that can have Html Attributes assigned to it... my Views are super clean.

SQL server stored procedure return a table

create procedure PSaleCForms
as
begin
declare 
@b varchar(9),
@c nvarchar(500),
@q nvarchar(max)
declare @T table(FY nvarchar(9),Qtr int,title nvarchar    (max),invoicenumber     nvarchar(max),invoicedate datetime,sp decimal    18,2),grandtotal decimal(18,2))
declare @data cursor
set @data= Cursor
forward_only static
for 
select x.DBTitle,y.CurrentFinancialYear from [Accounts     Manager].dbo.DBManager x inner join [Accounts Manager].dbo.Accounts y on        y.DBID=x.DBID where x.cfy=1
open @data
fetch next from @data
into @c,@b
while @@FETCH_STATUS=0
begin
set @q=N'Select '''+@b+''' [fy], case cast(month(i.invoicedate)/3.1 as int)     when 0 then 4 else cast(month(i.invoicedate)/3.1 as int) end [Qtr],     l.title,i.invoicenumber,i.invoicedate,i.sp,i.grandtotal from     ['+@c+'].dbo.invoicemain i inner join  ['+@c+'].dbo.ledgermain l on     l.ledgerid=i.ledgerid where (sp=0 or stocktype=''x'') and invoicetype=''DS'''

insert into @T exec [master].dbo.sp_executesql @q fetch next from @data into @c,@b end close @data deallocate @data select * from @T return end

Looking to understand the iOS UIViewController lifecycle

iOS 10,11 (Swift 3.1,Swift 4.0)

According to UIViewController in UIKit developers,

1. loadView()

This is where subclasses should create their custom view hierarchy if they aren't using a nib. Should never be called directly.

2. loadViewIfNeeded()

Loads the view controller's view if it has not already been set.

3. viewDidLoad()

Called after the view has been loaded. For view controllers created in code, this is after -loadView. For view controllers unarchived from a nib, this is after the view is set.

4. viewWillAppear(_ animated: Bool)

Called when the view is about to made visible. Default does nothing

5. viewWillLayoutSubviews()

Called just before the view controller's view's layoutSubviews method is invoked. Subclasses can implement as necessary. Default does nothing.

6. viewDidLayoutSubviews()

Called just after the view controller's view's layoutSubviews method is invoked. Subclasses can implement as necessary. Default does nothing.

7. viewDidAppear(_ animated: Bool)

Called when the view has been fully transitioned onto the screen. Default does nothing

8. viewWillDisappear(_ animated: Bool)

Called when the view is dismissed, covered or otherwise hidden. Default does nothing

9. viewDidDisappear(_ animated: Bool)

Called after the view was dismissed, covered or otherwise hidden. Default does nothing

10. viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)

Called when the view is Transitioning.

11. willMove(toParentViewController parent: UIViewController?)

12. didMove(toParentViewController parent: UIViewController?)

These two methods are public for container subclasses to call when transitioning between child controllers. If they are overridden, the overrides should ensure to call the super.

The parent argument in both of these methods is nil when a child is being removed from its parent; otherwise it is equal to the new parent view controller.

13. didReceiveMemoryWarning()

Called when the parent application receives a memory warning. On iOS 6.0 it will no longer clear the view by default.

How can I set response header on express.js assets

@klode's answer is right.

However, you are supposed to set another response header to make your header accessible to others.


Example:

First, you add 'page-size' in response header

response.set('page-size', 20);

Then, all you need to do is expose your header

response.set('Access-Control-Expose-Headers', 'page-size')

Make $JAVA_HOME easily changable in Ubuntu

After making changes to .profile, you need to execute the file, in order for the changes to take effect.

root@masternode# . ~/.profile

Once this is done, the echo command will work.

Using command line arguments in VBscript

If you need direct access:

WScript.Arguments.Item(0)
WScript.Arguments.Item(1)
...

JPanel Padding in Java

When you need padding inside the JPanel generally you add padding with the layout manager you are using. There are cases that you can just expand the border of the JPanel.

How to use external ".js" files

You can simply add your JavaScript in body segment like this:

<body>

<script src="myScript.js"> </script>
</body>

myScript will be the file name for your JavaScript. Just write the code and enjoy!