Programs & Examples On #Keycode

A number linked with specific key on keyboard in JavaScript language. May be different for one key depending on browser.

What are the JavaScript KeyCodes?

http://keycodes.atjayjo.com/

This app is just awesome. It is essentially a virtual keyboard that immediately shows you the keycode pressed on a standard US keyboard.

Where can I find a list of Mac virtual key codes?

Here are the all keycodes.

Here is a table with some keycodes for the three platforms. It is based on a US Extended keyboard layout.

http://web.archive.org/web/20100501161453/http://www.classicteck.com/rbarticles/mackeyboard.php

Or, there is an app in the Mac App Store named "Key Codes". Download it to see the keycodes of the keys you press.

Key Codes:
https://itunes.apple.com/tr/app/key-codes/id414568915?l=tr&mt=12

How to know if .keyup() is a character key (jQuery)

Note: In hindsight this was a quick and dirty answer, and may not work in all situations. To have a reliable solution, see Tim Down's answer (copy pasting that here as this answer is still getting views and upvotes):

You can't do this reliably with the keyup event. If you want to know something about the character that was typed, you have to use the keypress event instead.

The following example will work all the time in most browsers but there are some edge cases that you should be aware of. For what is in my view the definitive guide on this, see http://unixpapa.com/js/key.html.

$("input").keypress(function(e) {
    if (e.which !== 0) {
        alert("Character was typed. It was: " + String.fromCharCode(e.which));
    }
});

keyup and keydown give you information about the physical key that was pressed. On standard US/UK keyboards in their standard layouts, it looks like there is a correlation between the keyCode property of these events and the character they represent. However, this is not reliable: different keyboard layouts will have different mappings.


The following was the original answer, but is not correct and may not work reliably in all situations.

To match the keycode with a word character (eg., a would match. space would not)

$("input").keyup(function(event)
{ 
    var c= String.fromCharCode(event.keyCode);
    var isWordcharacter = c.match(/\w/);
}); 

Ok, that was a quick answer. The approach is the same, but beware of keycode issues, see this article in quirksmode.

Get the value of input text when enter key pressed

You should not place Javascript code in your HTML, since you're giving those input a class ("search"), there is no reason to do this. A better solution would be to do something like this :

$( '.search' ).on( 'keydown', function ( evt ) {
    if( evt.keyCode == 13 )
        search( $( this ).val() ); 
} ); 

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

Get Character value from KeyCode in JavaScript... then trim

I know this is an old question, but I came across it today searching for a pre-packaged solution to this problem, and found nothing that really met my needs.

Here is a solution (English only) that correctly supports Upper Case (shifted), Lower Case, punctuation, number keypad, etc.

It also allows for simple and straight-forward identification of - and reaction to - non-printable keys, like ESC, Arrows, Function keys, etc.

https://jsfiddle.net/5hhu896g/1/

keyboardCharMap and keyboardNameMap are the key to making this work

Thanks to DaveAlger for saving me some typing - and much discovery! - by providing the Named Key Array.

Select arrow style change

Here is an elegant fix that uses a span to show the value.

Layout is like this:

<div class="selectDiv">
   <span class="selectDefault"></span>
   <select name="txtCountry" class="selectBox">
      <option class="defualt-text">-- Select Country --</option>
      <option value="1">Abkhazia</option>
      <option value="2">Afghanistan</option>
   </select>
</div>

JsFiddle

querySelector, wildcard element match?

[id^='someId'] will match all ids starting with someId.

[id$='someId'] will match all ids ending with someId.

[id*='someId'] will match all ids containing someId.

If you're looking for the name attribute just substitute id with name.

If you're talking about the tag name of the element I don't believe there is a way using querySelector

What is the difference between Promises and Observables?

I've just dealt with an issue where Promises were the best solution, and I'm sharing it here for anyone stumbling across this question in the event it's useful (this was exactly the answer I was looking for earlier):

In an Angular2 project I have a service that takes some parameters and returns a value list to populate drop down menus on a form. When the form component initializes, I need to call the same service multiple times with different parameters to define a number of different dropdown menus, however if I simply queue up all the variables to call the service, only the last one succeeds and the rest error out. The service fetching from the database could only handle one request at a time.

The only way to successfully populate all the dropdown menu variables was to call the service in a way that prevented a new request from being processed until the last request was finished, and the Promise / .then mechanism solved the problem nicely.

  fetchValueList(listCode): Promise<any> {
      return this.dataSvc.getValueList(listCode, this.stateSvc.currentContext, this.stateSvc.currentLanguageCode)
          .map(response => response.json())
          .toPromise();
  }

  initializeDropDowns() {
      this.fetchValueList('First-Val-List')
          .then(data => {
              this.firstValList = data;
              return this.fetchValueList('Second-Val-List')
          }).then(data => {
              this.secondValList = data;
              return this.fetchValueList('Third-Val-List')
          }).then(data => {
              this.thirdValList = data;
          })  }

I defined the functions in the component, and then called initializeDropDowns() in ngOnInit.

The fetchValueList function returns a Promise, so the first call passes the first listCode and when the Promise resolves, the return value is in the data variable in the .then block where we can assign it to the this.firstValList variable. As the function has returned data, we know the service has finished and it's safe to call again with the second listCode, the return value is in the data variable in the next .then block and we assign it to the this.secondValList variable.

We can chain this as many times as required to populate all the variables, and on the last code block we simply omit the return statement and the block terminates.

This is a very specific use case where we have a single service that needs to be called multiple times as the component initializes, and where the service has to complete its fetch and return a value before it can be called again, but in this case, the Promise / .then method was ideal.

How to color the Git console?

GIT uses colored output by default but on some system like as CentOS it is not enabled . You can enable it like this

git config --global color.ui  true 
git config --global color.ui  false 
git config --global color.ui  auto 

You can choose your required command from here .

Here --global is optional to apply action for every repository in your system . If you want to apply coloring for current repository only then you can do something like this -

 git config color.ui  true 

get enum name from enum value

You could create a lookup method. Not the most efficient (depending on the enum's size) but it works.

public static String getNameByCode(int code){
  for(RelationActiveEnum e : RelationActiveEnum.values()){
    if(code == e.value) return e.name();
  }
  return null;
}

And call it like this:

RelationActiveEnum.getNameByCode(3);

Adding value labels on a matplotlib bar chart

If you only want to add Datapoints above the bars, you could easily do it with:

 for i in range(len(frequencies)): # your number of bars
    plt.text(x = x_values[i]-0.25, #takes your x values as horizontal positioning argument 
    y = y_values[i]+1, #takes your y values as vertical positioning argument 
    s = data_labels[i], # the labels you want to add to the data
    size = 9) # font size of datalabels

How to do one-liner if else statement?

A very similar construction is available in the language

**if <statement>; <evaluation> {
   [statements ...]
} else {
   [statements ...]
}*

*

i.e.

if path,err := os.Executable(); err != nil {
   log.Println(err)
} else {
   log.Println(path)
}

How to check if a MySQL query using the legacy API was successful?

This is the first example in the manual page for mysql_query:

$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

If you wish to use something other than die, then I'd suggest trigger_error.

HTTPS using Jersey Client

For Jersey 2 you'd need to modify the code:

        return ClientBuilder.newBuilder()
            .withConfig(config)
            .hostnameVerifier(new TrustAllHostNameVerifier())
            .sslContext(ctx)
            .build();

https://gist.github.com/JAlexoid/b15dba31e5919586ae51 http://www.panz.in/2015/06/jersey2https.html

Warning: A non-numeric value encountered

I encountered the issue in phpmyadmin with PHP 7.3. Thanks @coderama, I changed libraries/DisplayResults.class.php line 855 from

// Move to the next page or to the last one
$endpos = $_SESSION['tmpval']['pos']
    + $_SESSION['tmpval']['max_rows'];

into

// Move to the next page or to the last one
$endpos = (int)$_SESSION['tmpval']['pos']
    + (int)$_SESSION['tmpval']['max_rows'];

Fixed.

How do I remove packages installed with Python's easy_install?

Came across this question, while trying to uninstall the many random Python packages installed over time.

Using information from this thread, this is what I came up with:

cat package_list | xargs -n1 sudo pip uninstall -y

The package_list is cleaned up (awk) from a pip freeze in a virtualenv.

To remove almost all Python packages:

yolk -l | cut -f 1 -d " " | grep -v "setuptools|pip|ETC.." | xargs -n1 pip uninstall -y

How to get HttpClient to pass credentials along with the request?

In .NET Core, I managed to get a System.Net.Http.HttpClient with UseDefaultCredentials = true to pass through the authenticated user's Windows credentials to a back end service by using WindowsIdentity.RunImpersonated.

HttpClient client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true } );
HttpResponseMessage response = null;

if (identity is WindowsIdentity windowsIdentity)
{
    await WindowsIdentity.RunImpersonated(windowsIdentity.AccessToken, async () =>
    {
        var request = new HttpRequestMessage(HttpMethod.Get, url)
        response = await client.SendAsync(request);
    });
}

Creating for loop until list.length

You could learn about Python loops here: http://en.wikibooks.org/wiki/Python_Programming/Loops

You have to know that Python doesn't have { and } for start and end of loop, instead it depends on tab chars you enter in first of line, I mean line indents.

So you can do loop inside loop with double tab (indent)

An example of double loop is like this:

onetoten = range(1,11)
tentotwenty = range(10,21)
for count in onetoten:
    for count2 in tentotwenty
        print(count2)

How to change the default encoding to UTF-8 for Apache?

<meta charset='utf-8'> overrides the apache default charset (cf /etc/apache2/conf.d/charset)

If this is not enough, then you probably created your original file with iso-8859-1 encoding character set. You have to convert it to the proper character set:

iconv -f ISO-8859-1 -t UTF-8 source_file.php -o new file.php

How to fix Git error: object file is empty?

Copy everything (in the folder containing the .git) to a backup, then delete everything and restart. Make sure you have the git remote handy:

git remote -v
 origin [email protected]:rwldrn/idiomatic.js.git (fetch)
 origin [email protected]:rwldrn/idiomatic.js.git (push)

Then

mkdir mygitfolder.backup
cp mygitfolder/* mygitfolder.backup/
cd mygitfolder
rm -r * .git*
git init
git remote add origin [email protected]:rwldrn/idiomatic.js.git

Then merge any new files manually, and try to keep your computer turned on.

JQuery datepicker language

This is for the dutch people.

$.datepicker.regional['nl'] = {clearText: 'Effacer', clearStatus: '',
    closeText: 'sluiten', closeStatus: 'Onveranderd sluiten ',
    prevText: '<vorige', prevStatus: 'Zie de vorige maand',
    nextText: 'volgende>', nextStatus: 'Zie de volgende maand',
    currentText: 'Huidige', currentStatus: 'Bekijk de huidige maand',
    monthNames: ['januari','februari','maart','april','mei','juni',
    'juli','augustus','september','oktober','november','december'],
    monthNamesShort: ['jan','feb','mrt','apr','mei','jun',
    'jul','aug','sep','okt','nov','dec'],
    monthStatus: 'Bekijk een andere maand', yearStatus: 'Bekijk nog een jaar',
    weekHeader: 'Sm', weekStatus: '',
    dayNames: ['zondag','maandag','dinsdag','woensdag','donderdag','vrijdag','zaterdag'],
    dayNamesShort: ['zo', 'ma','di','wo','do','vr','za'],
    dayNamesMin: ['zo', 'ma','di','wo','do','vr','za'],
    dayStatus: 'Gebruik DD als de eerste dag van de week', dateStatus: 'Kies DD, MM d',
    dateFormat: 'dd/mm/yy', firstDay: 1, 
    initStatus: 'Kies een datum', isRTL: false};
$.datepicker.setDefaults($.datepicker.regional['nl']);

Importing Excel into a DataTable Quickly

 class DataReader
    {
        Excel.Application xlApp;
        Excel.Workbook xlBook;
        Excel.Range xlRange;
        Excel.Worksheet xlSheet;
        public DataTable GetSheetDataAsDataTable(String filePath, String sheetName)
        {
            DataTable dt = new DataTable();
            try
            {
                xlApp = new Excel.Application();
                xlBook = xlApp.Workbooks.Open(filePath);
                xlSheet = xlBook.Worksheets[sheetName];
                xlRange = xlSheet.UsedRange;
                DataRow row=null;
                for (int i = 1; i <= xlRange.Rows.Count; i++)
                {
                    if (i != 1)
                        row = dt.NewRow();
                    for (int j = 1; j <= xlRange.Columns.Count; j++)
                    {
                        if (i == 1)
                            dt.Columns.Add(xlRange.Cells[1, j].value);
                        else
                            row[j-1] = xlRange.Cells[i, j].value;
                    }
                    if(row !=null)
                        dt.Rows.Add(row);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                xlBook.Close();
                xlApp.Quit();
            }
            return dt;
        }
    }

HTML/CSS--Creating a banner/header

You have a type-o:

its: height: 200x;

and it should be: height: 200px; also check the image url; it should be in the same directory it seems.

Also, dont use 'px' at null (aka '0') values. 0px, 0em, 0% is still 0. :)

top: 0px;

is the same with:

top: 0;

Good Luck!

jQuery addClass onClick

$('#button').click(function(){
    $(this).addClass('active');
});

Items in JSON object are out of order using "json.dumps"?

The order of a dictionary doesn't have any relationship to the order it was defined in. This is true of all dictionaries, not just those turned into JSON.

>>> {"b": 1, "a": 2}
{'a': 2, 'b': 1}

Indeed, the dictionary was turned "upside down" before it even reached json.dumps:

>>> {"id":1,"name":"David","timezone":3}
{'timezone': 3, 'id': 1, 'name': 'David'}

Use of PUT vs PATCH methods in REST API real life scenarios

Everyone else has answered the PUT vs PATCH. I was just going to answer what part of the title of the original question asks: "... in REST API real life scenarios". In the real world, this happened to me with internet application that had a RESTful server and a relational database with a Customer table that was "wide" (about 40 columns). I mistakenly used PUT but had assumed it was like a SQL Update command and had not filled out all the columns. Problems: 1) Some columns were optional (so blank was valid answer), 2) many columns rarely changed, 3) some columns the user was not allowed to change such as time stamp of Last Purchase Date, 4) one column was a free-form text "Comments" column that users diligently filled with half-page customer services comments like spouses name to ask about OR usual order, 5) I was working on an internet app at time and there was worry about packet size.

The disadvantage of PUT is that it forces you to send a large packet of info (all columns including the entire Comments column, even though only a few things changed) AND multi-user issue of 2+ users editing the same customer simultaneously (so last one to press Update wins). The disadvantage of PATCH is that you have to keep track on the view/screen side of what changed and have some intelligence to send only the parts that changed. Patch's multi-user issue is limited to editing the same column(s) of same customer.

How to load a xib file in a UIView

You could try:

UIView *firstViewUIView = [[[NSBundle mainBundle] loadNibNamed:@"firstView" owner:self options:nil] firstObject];
[self.view.containerView addSubview:firstViewUIView];

How do I add a border to an image in HTML?

Two ways:

<img src="..." border="1" />

or

<img style='border:1px solid #000000' src="..." />

fatal: Not a valid object name: 'master'

copying Superfly Jon's comment into an answer:

To create a new branch without committing on master, you can use:

git checkout -b <branchname>

Python read in string from file and split it into values

Something like this - for each line read into string variable a:

>>> a = "123,456"
>>> b = a.split(",")
>>> b
['123', '456']
>>> c = [int(e) for e in b]
>>> c
[123, 456]
>>> x, y = c
>>> x
123
>>> y
456

Now you can do what is necessary with x and y as assigned, which are integers.

Examples for string find in Python

If you want to search for the last instance of a string in a text, you can run rfind.

Example:

   s="Hello"
   print s.rfind('l')

output: 3

*no import needed

Complete syntax:

stringEx.rfind(substr, beg=0, end=len(stringEx))

ECMAScript 6 class destructor

"A destructor wouldn't even help you here. It's the event listeners themselves that still reference your object, so it would not be able to get garbage-collected before they are unregistered."

Not so. The purpose of a destructor is to allow the item that registered the listeners to unregister them. Once an object has no other references to it, it will be garbage collected.

For instance, in AngularJS, when a controller is destroyed, it can listen for a destroy event and respond to it. This isn't the same as having a destructor automatically called, but it's close, and gives us the opportunity to remove listeners that were set when the controller was initialized.

// Set event listeners, hanging onto the returned listener removal functions
function initialize() {
    $scope.listenerCleanup = [];
    $scope.listenerCleanup.push( $scope.$on( EVENTS.DESTROY, instance.onDestroy) );
    $scope.listenerCleanup.push( $scope.$on( AUTH_SERVICE_RESPONSES.CREATE_USER.SUCCESS, instance.onCreateUserResponse ) );
    $scope.listenerCleanup.push( $scope.$on( AUTH_SERVICE_RESPONSES.CREATE_USER.FAILURE, instance.onCreateUserResponse ) );
}

// Remove event listeners when the controller is destroyed
function onDestroy(){
    $scope.listenerCleanup.forEach( remove => remove() );
}


How do I capture response of form.submit

I am doing it this way and its working.

$('#form').submit(function(){
    $.ajax({
      url: $('#form').attr('action'),
      type: 'POST',
      data : $('#form').serialize(),
      success: function(){
        console.log('form submitted.');
      }
    });
    return false;
});

How to automatically update your docker containers, if base-images are updated

Dependency management for Docker images is a real problem. I'm part of a team that built a tool, MicroBadger, to help with this by monitoring container images and inspecting metadata. One of its features is to let you set up a notification webhook that gets called when an image you're interested in (e.g. a base image) changes.

json and empty array

The first version is a null object while the second is an Array object with zero elements.

Null may mean here for example that no location is available for that user, no location has been requested or that some restrictions apply. Hard to tell with no reference to the API.

How to get C# Enum description from value?

Update

The Unconstrained Melody library is no longer maintained; Support was dropped in favour of Enums.NET.

In Enums.NET you'd use:

string description = ((MyEnum)value).AsString(EnumFormat.Description);

Original post

I implemented this in a generic, type-safe way in Unconstrained Melody - you'd use:

string description = Enums.GetDescription((MyEnum)value);

This:

  • Ensures (with generic type constraints) that the value really is an enum value
  • Avoids the boxing in your current solution
  • Caches all the descriptions to avoid using reflection on every call
  • Has a bunch of other methods, including the ability to parse the value from the description

I realise the core answer was just the cast from an int to MyEnum, but if you're doing a lot of enum work it's worth thinking about using Unconstrained Melody :)

Plotting two variables as lines using ggplot2 on the same graph

For a small number of variables, you can build the plot manually yourself:

ggplot(test_data, aes(date)) + 
  geom_line(aes(y = var0, colour = "var0")) + 
  geom_line(aes(y = var1, colour = "var1"))

Interesting 'takes exactly 1 argument (2 given)' Python error

try using:

def extractAll(self,tag):

attention to self

performing HTTP requests with cURL (using PROXY)

From man curl:

-x, --proxy <[protocol://][user:password@]proxyhost[:port]>

     Use the specified HTTP proxy. 
     If the port number is not specified, it is assumed at port 1080.

General way:

export http_proxy=http://your.proxy.server:port/

Then you can connect through proxy from (many) application.

And, as per comment below, for https:

export https_proxy=https://your.proxy.server:port/

Compiler error: memset was not declared in this scope

You should include <string.h> (or its C++ equivalent, <cstring>).

Obtain form input fields using jQuery?

http://api.jquery.com/serializearray/

$('#form').on('submit', function() {
    var data = $(this).serializeArray();
});

This can also be done without jQuery using the XMLHttpRequest Level 2 FormData object

http://www.w3.org/TR/2010/WD-XMLHttpRequest2-20100907/#the-formdata-interface

var data = new FormData([form])

PreparedStatement with list of parameters in a IN clause

public class Test1 {
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("helow");
String where="where task in ";
        where+="(";
    //  where+="'task1'";
        int num[]={1,2,3,4};
        for (int i=0;i<num.length+1;i++) {
            if(i==1){
                where +="'"+i+"'";
            }
            if(i>1 && i<num.length)
                where+=", '"+i+"'";
            if(i==num.length){
                System.out.println("This is last number"+i);
            where+=", '"+i+"')";
            }
        }
        System.out.println(where);  
    }
}

Converting to upper and lower case in Java

WordUtils.capitalizeFully(str) from apache commons-lang has the exact semantics as required.

CSS horizontal centering of a fixed div?

left: 50%;
margin-left: -400px; /* Half of the width */

Where does Android emulator store SQLite database?

The other answers are severely outdated. With Android Studio, this is the way to do it:

  1. Click on Tools > Android > Android Device Monitor

enter image description here

  1. Click on File Explorer

enter image description here

  1. Navigate to your db file and click on the Save button.

enter image description here

What does the star operator mean, in a function call?

I find this particularly useful for when you want to 'store' a function call.

For example, suppose I have some unit tests for a function 'add':

def add(a, b): return a + b
tests = { (1,4):5, (0, 0):0, (-1, 3):3 }
for test, result in tests.items():
    print 'test: adding', test, '==', result, '---', add(*test) == result

There is no other way to call add, other than manually doing something like add(test[0], test[1]), which is ugly. Also, if there are a variable number of variables, the code could get pretty ugly with all the if-statements you would need.

Another place this is useful is for defining Factory objects (objects that create objects for you). Suppose you have some class Factory, that makes Car objects and returns them. You could make it so that myFactory.make_car('red', 'bmw', '335ix') creates Car('red', 'bmw', '335ix'), then returns it.

def make_car(*args):
    return Car(*args)

This is also useful when you want to call a superclass' constructor.

Difference between uint32 and uint32_t

uint32_t is defined in the standard, in

18.4.1 Header <cstdint> synopsis [cstdint.syn]

namespace std {
//...
typedef unsigned integer type uint32_t; // optional
//...
}

uint32 is not, it's a shortcut provided by some compilers (probably as typedef uint32_t uint32) for ease of use.

Is there a way to set background-image as a base64 encoded image?

In my case, it was just because I didn't set the height and width.

But there is another issue.

The background image could be removed using

element.style.backgroundImage=""

but couldn't be set using

element.style.backgroundImage="some base64 data"

Jquery works fine.

Difference between <? super T> and <? extends T> in Java

The most confusing thing here is that whatever type restrictions we specify, assignment works only one way:

baseClassInstance = derivedClassInstance;

You may think that Integer extends Number and that an Integer would do as a <? extends Number>, but the compiler will tell you that <? extends Number> cannot be converted to Integer (that is, in human parlance, it is wrong that anything that extends number can be converted to Integer):

class Holder<T> {
    T v;
    T get() { return v; }
    void set(T n) { v=n; }
}
class A {
    public static void main(String[]args) {
        Holder<? extends Number> he = new Holder();
        Holder<? super Number> hs = new Holder();

        Integer i;
        Number n;
        Object o;

        // Producer Super: always gives an error except
        //       when consumer expects just Object
        i = hs.get(); // <? super Number> cannot be converted to Integer
        n = hs.get(); // <? super Number> cannot be converted to Number
                      // <? super Number> cannot be converted to ... (but
                      //       there is no class between Number and Object)
        o = hs.get();

        // Consumer Super
        hs.set(i);
        hs.set(n);
        hs.set(o); // Object cannot be converted to <? super Number>

        // Producer Extends
        i = he.get(); // <? extends Number> cannot be converted to Integer
        n = he.get();
        o = he.get();

        // Consumer Extends: always gives an error
        he.set(i); // Integer cannot be converted to <? extends Number>
        he.set(n); // Number cannot be converted to <? extends Number>
        he.set(o); // Object cannot be converted to <? extends Number>
    }
}

hs.set(i); is ok because Integer can be converted to any superclass of Number (and not because Integer is a superclass of Number, which is not true).

EDIT added a comment about Consumer Extends and Producer Super -- they are not meaningful because they specify, correspondingly, nothing and just Object. You are advised to remember PECS because CEPS is never useful.

Difference between subprocess.Popen and os.system

subprocess.Popen() is strict super-set of os.system().

Thread Safe C# Singleton Pattern

The Lazy<T> version:

public sealed class Singleton
{
    private static readonly Lazy<Singleton> lazy
        = new Lazy<Singleton>(() => new Singleton());

    public static Singleton Instance
        => lazy.Value;

    private Singleton() { }
}

Requires .NET 4 and C# 6.0 (VS2015) or newer.

Resetting a multi-stage form with jQuery

jQuery Plugin

I created a jQuery plugin so I can use it easily anywhere I need it:

jQuery.fn.clear = function()
{
    var $form = $(this);

    $form.find('input:text, input:password, input:file, textarea').val('');
    $form.find('select option:selected').removeAttr('selected');
    $form.find('input:checkbox, input:radio').removeAttr('checked');

    return this;
}; 

So now I can use it by calling:

$('#my-form').clear();

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

Make sure you didn't by mistake changed the file type of __init__.py files. If, for example, you changed their type to "Text" (instead of "Python"), PyCharm won't analyze the file for Python code. In that case, you may notice that the file icon for __init__.py files is different from other Python files.

To fix, in Settings > Editor > File Types, in the "Recognized File Types" list click on "Text" and in the "File name patterns" list remove __init__.py.

LaTeX Optional Arguments

All you need is the following:

\makeatletter
\def\sec#1{\def\tempa{#1}\futurelet\next\sec@i}% Save first argument
\def\sec@i{\ifx\next\bgroup\expandafter\sec@ii\else\expandafter\sec@end\fi}%Check brace
\def\sec@ii#1{\section*{\tempa\ and #1}}%Two args
\def\sec@end{\section*{\tempa}}%Single args
\makeatother

\sec{Hello}
%Output: Hello
\sec{Hello}{Hi}
%Output: Hello and Hi

How can I know if a branch has been already merged into master?

You can use the git merge-base command to find the latest common commit between the two branches. If that commit is the same as your branch head, then the branch has been completely merged.

Note that git branch -d does this sort of thing already because it will refuse to delete a branch that hasn't already been completely merged.

How do I get an element to scroll into view, using jQuery?

Have a look at the jQuery.scrollTo plugin. Here's a demo.

This plugin has a lot of options that go beyond what native scrollIntoView offers you. For instance, you can set the scrolling to be smooth, and then set a callback for when the scrolling finishes.

You can also have a look at all the JQuery plugins tagged with "scroll".

Return rows in random order

To be efficient, and random, it might be best to have two different queries.

Something like...

SELECT table_id FROM table

Then, in your chosen language, pick a random id, then pull that row's data.

SELECT * FROM table WHERE table_id = $rand_id

But that's not really a good idea if you're expecting to have lots of rows in the table. It would be better if you put some kind of limit on what you randomly select from. For publications, maybe randomly pick from only items posted within the last year.

Your password does not satisfy the current policy requirements

If you don't care what the password policy is. You can set it to LOW by issuing below mysql command:

mysql> SET GLOBAL validate_password_policy=LOW;

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

If you are using Windows command line to print the data, you should use

chcp 65001

This worked for me!

Removing double quotes from variables in batch file creates problems with CMD environment

Your conclusion (1) sounds wrong. There must be some other factor at play.

The problem of quotes in batch file parameters is normally solved by removing the quotes with %~ and then putting them back manually where appropriate.

E.g.:

set cmd=%~1
set params=%~2 %~3

"%cmd%" %params%

Note the quotes around %cmd%. Without them, path with spaces won't work.

If you could post your entire batch code, maybe more specific answer could be made.

java.lang.IllegalArgumentException: No converter found for return value of type

The problem was that one of the nested objects in Foo didn't have any getter/setter

Do I need to compile the header files in a C program?

In some systems, attempts to speed up the assembly of fully resolved '.c' files call the pre-assembly of include files "compiling header files". However, it is an optimization technique that is not necessary for actual C development.

Such a technique basically computed the include statements and kept a cache of the flattened includes. Normally the C toolchain will cut-and-paste in the included files recursively, and then pass the entire item off to the compiler. With a pre-compiled header cache, the tool chain will check to see if any of the inputs (defines, headers, etc) have changed. If not, then it will provide the already flattened text file snippets to the compiler.

Such systems were intended to speed up development; however, many such systems were quite brittle. As computers sped up, and source code management techniques changed, fewer of the header pre-compilers are actually used in the common project.

Until you actually need compilation optimization, I highly recommend you avoid pre-compiling headers.

Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?

The Car Analogy

enter image description here

IDE: The MS Office of Programming. It's where you type your code, plus some added features to make you a happier programmer. (e.g. Eclipse, Netbeans). Car body: It's what you really touch, see and work on.

Library: A library is a collection of functions, often grouped into multiple program files, but packaged into a single archive file. This contains programs created by other folks, so that you don't have to reinvent the wheel. (e.g. junit.jar, log4j.jar). A library generally has a key role, but does all of its work behind the scenes, it doesn't have a GUI. Car's engine.

API: The library publisher's documentation. This is how you should use my library. (e.g. log4j API, junit API). Car's user manual - yes, cars do come with one too!


Kits

What is a kit? It's a collection of many related items that work together to provide a specific service. When someone says medicine kit, you get everything you need for an emergency: plasters, aspirin, gauze and antiseptic, etc.

enter image description here

SDK: McDonald's Happy Meal. You have everything you need (and don't need) boxed neatly: main course, drink, dessert and a bonus toy. An SDK is a bunch of different software components assembled into a package, such that they're "ready-for-action" right out of the box. It often includes multiple libraries and can, but may not necessarily include plugins, API documentation, even an IDE itself. (e.g. iOS Development Kit).

Toolkit: GUI. GUI. GUI. When you hear 'toolkit' in a programming context, it will often refer to a set of libraries intended for GUI development. Since toolkits are UI-centric, they often come with plugins (or standalone IDE's) that provide screen-painting utilities. (e.g. GWT)

Framework: While not the prevalent notion, a framework can be viewed as a kit. It also has a library (or a collection of libraries that work together) that provides a specific coding structure & pattern (thus the word, framework). (e.g. Spring Framework)

How do I set the default Java installation/runtime (Windows)?

After many attempts, I found the junction approach more convenient. This is very similar on how this problem is solved in linux.

Basically it consists of having a link between c:\tools\java\default and the actual version of java you want to use as default in your system.


How to set it:

  1. Download junction and make sure to put it in your PATH environment variable
  2. Set your environment this way: - PATH pointing to ONLY to this jre c:\tools\java\default\bin - JAVA_HOME pointing to `c:\tools\java\default
  3. Store all your jre-s in one folder like (if you do that in your Program FIles folder you may encounter some
    • C:\tools\Java\JRE_1.6
    • C:\tools\Java\JRE_1.7
    • C:\tools\Java\JRE_1.8
  4. Open a command prompt and cd to C:\tools\Java\
  5. Execute junction default JRE_1.6

This will create a junction (which is more or less like a symbolic link in linux) between C:\tools\java\default and C:\tools\java\JRE_1.6

In this way you will always have your default java in c:\tools\java\default.

If you then need to change your default java to the 1.8 version you just need to execute

junction -d default
junction default JRE_1.8 

Then you can have batch files to do that without command prompt like set_jdk8.bat set_jdk7.bat

As suggested from @????????????

EDIT: From windows vista, you can use mklink /J default JRE_1.8

Set the space between Elements in Row Flutter

Just add "Container(width: 5, color: Colors.transparent)," between elements

new Container(
      alignment: FractionalOffset.center,
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          new FlatButton(
            child: new Text('Don\'t have an account?', style: new TextStyle(color: Color(0xFF2E3233))),
          ),
            Container(width: 5, color: Colors.transparent),
          new FlatButton(
            child: new Text('Register.', style: new TextStyle(color: Color(0xFF84A2AF), fontWeight: FontWeight.bold),),
            onPressed: moveToRegister,
          )
        ],
      ),
    ),  

Vector of Vectors to create matrix

Assume we have the following class:

#include <vector>

class Matrix {
 private:
  std::vector<std::vector<int>> data;
};

First of all I would like suggest you to implement a default constructor:

#include <vector>

class Matrix {
 public:
  Matrix(): data({}) {}

 private:
  std::vector<std::vector<int>> data;
};

At this time we can create Matrix instance as follows:

Matrix one;

The next strategic step is to implement a Reset method, which takes two integer parameters that specify the new number of rows and columns of the matrix, respectively:

#include <vector>

class Matrix {
 public:
  Matrix(): data({}) {}

  Matrix(const int &rows, const int &cols) {
    Reset(rows, cols);
  }

  void Reset(const int &rows, const int &cols) {
    if (rows == 0 || cols == 0) {
      data.assign(0, std::vector<int>(0));
    } else {
      data.assign(rows, std::vector<int>(cols));
    }
  }

 private:
  std::vector<std::vector<int>> data;
};

At this time the Reset method changes the dimensions of the 2D-matrix to the given ones and resets all its elements. Let me show you a bit later why we may need this.

Well, we can create and initialize our matrix:

Matrix two(3, 5);

Lets add info methods for our matrix:

#include <vector>

class Matrix {
 public:
  Matrix(): data({}) {}

  Matrix(const int &rows, const int &cols) {
    Reset(rows, cols);
  }

  void Reset(const int &rows, const int &cols) {
    data.resize(rows);
    for (int i = 0; i < rows; ++i) {
      data.at(i).resize(cols);
    }
  }

  int GetNumRows() const {
    return data.size();
  }

  int GetNumColumns() const {
    if (GetNumRows() > 0) {
      return data[0].size();
    }

    return 0;
  }

 private:
  std::vector<std::vector<int>> data;
};

At this time we can get some trivial matrix debug info:

#include <iostream>

void MatrixInfo(const Matrix& m) {
  std::cout << "{ \"rows\": " << m.GetNumRows()
            << ", \"cols\": " << m.GetNumColumns() << " }" << std::endl;
}

int main() {
  Matrix three(3, 4);
  MatrixInfo(three);
}

The second class method we need at this time is At. A sort of getter for our private data:

#include <vector>

class Matrix {
 public:
  Matrix(): data({}) {}

  Matrix(const int &rows, const int &cols) {
    Reset(rows, cols);
  }

  void Reset(const int &rows, const int &cols) {
    data.resize(rows);
    for (int i = 0; i < rows; ++i) {
      data.at(i).resize(cols);
    }
  }

  int At(const int &row, const int &col) const {
    return data.at(row).at(col);
  }

  int& At(const int &row, const int &col) {
    return data.at(row).at(col);
  }

  int GetNumRows() const {
    return data.size();
  }

  int GetNumColumns() const {
    if (GetNumRows() > 0) {
      return data[0].size();
    }

    return 0;
  }

 private:
  std::vector<std::vector<int>> data;
};

The constant At method takes the row number and column number and returns the value in the corresponding matrix cell:

#include <iostream>

int main() {
  Matrix three(3, 4);
  std::cout << three.At(1, 2); // 0 at this time
}

The second, non-constant At method with the same parameters returns a reference to the value in the corresponding matrix cell:

#include <iostream>

int main() {
  Matrix three(3, 4);
  three.At(1, 2) = 8;
  std::cout << three.At(1, 2); // 8
}

Finally lets implement >> operator:

#include <iostream>

std::istream& operator>>(std::istream& stream, Matrix &matrix) {
  int row = 0, col = 0;

  stream >> row >> col;
  matrix.Reset(row, col);

  for (int r = 0; r < row; ++r) {
    for (int c = 0; c < col; ++c) {
      stream >> matrix.At(r, c);
    }
  }

  return stream;
}

And test it:

#include <iostream>

int main() {
  Matrix four; // An empty matrix

  MatrixInfo(four);
  // Example output:
  //
  // { "rows": 0, "cols": 0 }

  std::cin >> four;
  // Example input
  //
  // 2 3
  // 4 -1 10
  // 8 7 13

  MatrixInfo(four);
  // Example output:
  //
  // { "rows": 2, "cols": 3 }
}

Feel free to add out of range check. I hope this example helps you :)

How can I make a clickable link in an NSAttributedString?

In case you're having issues with what @Karl Nosworthy and @esilver had provided above, I've updated the NSMutableAttributedString extension to its Swift 4 version.

extension NSMutableAttributedString {

public func setAsLink(textToFind:String, linkURL:String) -> Bool {

    let foundRange = self.mutableString.range(of: textToFind)
    if foundRange.location != NSNotFound {
         _ = NSMutableAttributedString(string: textToFind)
        // Set Attribuets for Color, HyperLink and Font Size
        let attributes = [NSFontAttributeName: UIFont.bodyFont(.regular, shouldResize: true), NSLinkAttributeName:NSURL(string: linkURL)!, NSForegroundColorAttributeName: UIColor.blue]

        self.setAttributes(attributes, range: foundRange)
        return true
    }
    return false
  }
}

How to save the contents of a div as a image?

There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.

Installing Pandas on Mac OSX

You can install python with homebrew:

brew install python

Make sure that OSX uses the correct path:

which python

Then you can use the pip tool to install pandas:

pip install pandas

Make sure that all dependencies are installed. I followed this tutorial: http://penandpants.com/2013/04/04/install-scientific-python-on-mac-os-x/

Works fine on my machine.

Injecting @Autowired private field during testing

The accepted answer (use MockitoJUnitRunner and @InjectMocks) is great. But if you want something a little more lightweight (no special JUnit runner), and less "magical" (more transparent) especially for occasional use, you could just set the private fields directly using introspection.

If you use Spring, you already have a utility class for this : org.springframework.test.util.ReflectionTestUtils

The use is quite straightforward :

ReflectionTestUtils.setField(myLauncher, "myService", myService);

The first argument is your target bean, the second is the name of the (usually private) field, and the last is the value to inject.

If you don't use Spring, it is quite trivial to implement such a utility method. Here is the code I used before I found this Spring class :

public static void setPrivateField(Object target, String fieldName, Object value){
        try{
            Field privateField = target.getClass().getDeclaredField(fieldName);
            privateField.setAccessible(true);
            privateField.set(target, value);
        }catch(Exception e){
            throw new RuntimeException(e);
        }
    }

Render HTML string as real HTML in a React component

dangerouslySetInnerHTML

dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous. For example:

function createMarkup() {
  return {__html: 'First &middot; Second'};
}

function MyComponent() {
  return <div dangerouslySetInnerHTML={createMarkup()} />;
}

One line if/else condition in linux shell scripting

You can use like bellow:

(( var0 = var1<98?9:21 ))

the same as

if [ "$var1" -lt 98 ]; then
   var0=9
else
   var0=21
fi

extends

condition?result-if-true:result-if-false

I found the interested thing on the book "Advanced Bash-Scripting Guide"

MD5 hashing in Android

Here is an implementation you can use (updated to use more up to date Java conventions - for:each loop, StringBuilder instead of StringBuffer):

public static String md5(final String s) {
    final String MD5 = "MD5";
    try {
        // Create MD5 Hash
        MessageDigest digest = java.security.MessageDigest
                .getInstance(MD5);
        digest.update(s.getBytes());
        byte messageDigest[] = digest.digest();

        // Create Hex String
        StringBuilder hexString = new StringBuilder();
        for (byte aMessageDigest : messageDigest) {
            String h = Integer.toHexString(0xFF & aMessageDigest);
            while (h.length() < 2)
                h = "0" + h;
            hexString.append(h);
        }
        return hexString.toString();

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return "";
}

Although it is not recommended for systems that involve even the basic level of security (MD5 is considered broken and can be easily exploited), it is sometimes enough for basic tasks.

2D cross-platform game engine for Android and iOS?

Recently I used an AS3 engine: PushButton (now is dead, but it's still functional and you could use something else) to do this job. To make it works with Android and iOS, the project was compiled in AIR for both platforms and everything worked with no performance damage. Since Flash Builder is kinda expensive ($249), you could use FlashDevelop (there is some tutorials to compile in AIR with it).

Flash could be an option since is very easy to learn.

Bold words in a string of strings.xml in Android

Use html tag inside string resources :-

<resources>
<string name="string_resource_name"><![CDATA[<b> Your text </b>]]> </string>
</resources>

And get bold text from string resources like :-

private Spanned getSpannedText(String text) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return Html.fromHtml(text, Html.FROM_HTML_MODE_COMPACT);
        } else {
            return Html.fromHtml(text);
        }
    }


 String s = format(context.getResources().getString(R.string.string_resource_name));
 textView.setText(getSpannedText(s));

npm install errors with Error: ENOENT, chmod

Ok it looks like NPM is using your .gitignore as a base for the .npmignore file, and thus ignores /lib. If you add a blank .npmignore file into the root of your application, everything should work.

[edit] - more info on this behaviour here: https://docs.npmjs.com/misc/developers#keeping-files-out-of-your-package

Sorting data based on second column of a file

Use sort.

sort ... -k 2,2 ...

INSERT SELECT statement in Oracle 11G

for inserting data into table you can write

insert into tablename values(column_name1,column_name2,column_name3);

but write the column_name in the sequence as per sequence in table ...

How to get on scroll events?

Listen to window:scroll event for window/document level scrolling and element's scroll event for element level scrolling.

window:scroll

@HostListener('window:scroll', ['$event'])
onWindowScroll($event) {

}

or

<div (window:scroll)="onWindowScroll($event)">

scroll

@HostListener('scroll', ['$event'])
onElementScroll($event) {

}

or

<div (scroll)="onElementScroll($event)">

@HostListener('scroll', ['$event']) won't work if the host element itself is not scroll-able.

Examples

what does "error : a nonstatic member reference must be relative to a specific object" mean?

CPMSifDlg::EncodeAndSend() method is declared as non-static and thus it must be called using an object of CPMSifDlg. e.g.

CPMSifDlg obj;
return obj.EncodeAndSend(firstName, lastName, roomNumber, userId, userFirstName, userLastName);

If EncodeAndSend doesn't use/relate any specifics of an object (i.e. this) but general for the class CPMSifDlg then declare it as static:

class CPMSifDlg {
...
  static int EncodeAndSend(...);
  ^^^^^^
};

How to connect a Windows Mobile PDA to Windows 10

Install Windows Mobile Device Center for your architecture. (It will install older versions of .NET if needed.) In USB to PC settings on device uncheck Enable advanced network and tap OK. This worked for me on 2 different Windows 10 PCs.

Sharing a variable between multiple different threads

Using static will not help your case.

Using synchronize locks a variable when it is in use by another thread.

You should use volatile keyword to keep the variable updated among all threads.

Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread safe. Thread safe means that a method or class instance can be used by multiple threads at the same time without any problem.

Android: ScrollView force to bottom

I increment to work perfectly.

    private void sendScroll(){
        final Handler handler = new Handler();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {Thread.sleep(100);} catch (InterruptedException e) {}
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.fullScroll(View.FOCUS_DOWN);
                    }
                });
            }
        }).start();
    }

Note

This answer is a workaround for really old versions of android. Today the postDelayed has no more that bug and you should use it.

How can I show/hide component with JSF?

Use the "rendered" attribute available on most if not all tags in the h-namespace.

<h:outputText value="Hi George" rendered="#{Person.name == 'George'}" />

Redis strings vs Redis hashes to represent JSON: efficiency?

This article can provide a lot of insight here: http://redis.io/topics/memory-optimization

There are many ways to store an array of Objects in Redis (spoiler: I like option 1 for most use cases):

  1. Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate). For example:

    INCR id:users
    SET user:{id} '{"name":"Fred","age":25}'
    SADD users {id}
    

    Generally speaking, this is probably the best method in most cases. If there are a lot of fields in the Object, your Objects are not nested with other Objects, and you tend to only access a small subset of fields at a time, it might be better to go with option 2.

    Advantages: considered a "good practice." Each Object is a full-blown Redis key. JSON parsing is fast, especially when you need to access many fields for this Object at once. Disadvantages: slower when you only need to access a single field.

  2. Store each Object's properties in a Redis hash.

    INCR id:users
    HMSET user:{id} name "Fred" age 25
    SADD users {id}
    

    Advantages: considered a "good practice." Each Object is a full-blown Redis key. No need to parse JSON strings. Disadvantages: possibly slower when you need to access all/most of the fields in an Object. Also, nested Objects (Objects within Objects) cannot be easily stored.

  3. Store each Object as a JSON string in a Redis hash.

    INCR id:users
    HMSET users {id} '{"name":"Fred","age":25}'
    

    This allows you to consolidate a bit and only use two keys instead of lots of keys. The obvious disadvantage is that you can't set the TTL (and other stuff) on each user Object, since it is merely a field in the Redis hash and not a full-blown Redis key.

    Advantages: JSON parsing is fast, especially when you need to access many fields for this Object at once. Less "polluting" of the main key namespace. Disadvantages: About same memory usage as #1 when you have a lot of Objects. Slower than #2 when you only need to access a single field. Probably not considered a "good practice."

  4. Store each property of each Object in a dedicated key.

    INCR id:users
    SET user:{id}:name "Fred"
    SET user:{id}:age 25
    SADD users {id}
    

    According to the article above, this option is almost never preferred (unless the property of the Object needs to have specific TTL or something).

    Advantages: Object properties are full-blown Redis keys, which might not be overkill for your app. Disadvantages: slow, uses more memory, and not considered "best practice." Lots of polluting of the main key namespace.

Overall Summary

Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. I prefer option 1 (generally speaking) because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don't want there to be a lot of keys in your database and you don't care about things like TTL, key sharding, or whatever).

If I got something wrong here, please consider leaving a comment and allowing me to revise the answer before downvoting. Thanks! :)

Put current changes in a new Git branch

You can simply check out a new branch, and then commit:

git checkout -b my_new_branch
git commit

Checking out the new branch will not discard your changes.

Getting a link to go to a specific section on another page

I tried the above answer - using page.html#ID_name it gave me a 404 page doesn't exist error.

Then instead of using .html, I simply put a slash / before the # and that worked fine. So my example on the sending page between the link tags looks like:

<a href= "http://my website.com/target-page/#El_Chorro">El Chorro</a>

Just use / instead of .html.

Python Linked List

I did also write a Single Linked List based on some tutorial, which has the basic two Node and Linked List classes, and some additional methods for insertion, delete, reverse, sorting, and such.

It's not the best or easiest, works OK though.

"""


Single Linked List (SLL):
A simple object-oriented implementation of Single Linked List (SLL) 
with some associated methods, such as create list, count nodes, delete nodes, and such. 


"""

class Node:
    """
    Instantiates a node
    """
    def __init__(self, value):
        """
        Node class constructor which sets the value and link of the node

        """
        self.info = value
        self.link = None

class SingleLinkedList:
    """
    Instantiates the SLL class
    """
    def __init__(self):
        """
        SLL class constructor which sets the value and link of the node

        """
        self.start = None

    def create_single_linked_list(self):
        """
        Reads values from stdin and appends them to this list and creates a SLL with integer nodes

        """
        try:
            number_of_nodes = int(input("   Enter a positive integer between 1-50 for the number of nodes you wish to have in the list: "))
            if number_of_nodes <= 0 or number_of_nodes > 51:
                print(" The number of nodes though must be an integer between 1 to 50!")
                self.create_single_linked_list()

        except Exception as e:
            print(" Error: ", e)
            self.create_single_linked_list()


        try:
            for _ in range(number_of_nodes):
                try:
                    data = int(input("   Enter an integer for the node to be inserted: "))
                    self.insert_node_at_end(data)
                except Exception as e:
                    print(" Error: ", e)
        except Exception as e:
            print(" Error: ", e)

    def count_sll_nodes(self):
        """
        Counts the nodes of the linked list

        """
        try:
            p = self.start
            n = 0
            while p is not None:
                n += 1
                p = p.link

            if n >= 1:
                print(f" The number of nodes in the linked list is {n}")
            else:
                print(f" The SLL does not have a node!")
        except Exception as e: 
            print(" Error: ", e)

    def search_sll_nodes(self, x):
        """
        Searches the x integer in the linked list
        """
        try:
            position =  1
            p = self.start
            while p is not None:
                if p.info == x:
                    print(f" YAAAY! We found {x} at position {position}")
                    return True

                #Increment the position
                position += 1 
                #Assign the next node to the current node
                p = p.link
            else:
                print(f" Sorry! We couldn't find {x} at any position. Maybe, you might want to use option 9 and try again later!")
                return False
        except Exception as e:
            print(" Error: ", e)

    def display_sll(self):
        """
        Displays the list
        """
        try:
            if self.start is None:
                print(" Single linked list is empty!")
                return

            display_sll = " Single linked list nodes are: "
            p = self.start
            while p is not None:
                display_sll += str(p.info) + "\t"
                p = p.link

            print(display_sll)

        except Exception as e:
            print(" Error: ", e) 

    def insert_node_in_beginning(self, data):
        """
        Inserts an integer in the beginning of the linked list

        """
        try:
            temp = Node(data)
            temp.link = self.start
            self.start = temp
        except Exception as e:
            print(" Error: ", e)

    def insert_node_at_end(self, data):
        """
        Inserts an integer at the end of the linked list

        """
        try:            
            temp = Node(data)
            if self.start is None:
                self.start = temp
                return

            p = self.start  
            while p.link is not None:
                p = p.link
            p.link = temp
        except Exception as e:
            print(" Error: ", e)


    def insert_node_after_another(self, data, x):
        """
        Inserts an integer after the x node

        """
        try:
            p = self.start

            while p is not None:
                if p.info == x:
                    break
                p = p.link

            if p is None:
                print(f" Sorry! {x} is not in the list.")
            else:
                temp = Node(data)
                temp.link = p.link
                p.link = temp
        except Exception as e: 
            print(" Error: ", e)


    def insert_node_before_another(self, data, x):
        """
        Inserts an integer before the x node

        """

        try:

            # If list is empty
            if self.start is None:
                print(" Sorry! The list is empty.")
                return 
            # If x is the first node, and new node should be inserted before the first node
            if x == self.start.info:
                temp = Node(data)
                temp.link = p.link
                p.link = temp

            # Finding the reference to the prior node containing x
            p = self.start
            while p.link is not None:
                if p.link.info == x:
                    break
                p = p.link

            if p.link is not None:
                print(f" Sorry! {x} is not in the list.")
            else:
                temp = Node(data)
                temp.link = p.link
                p.link = temp           

        except Exception as e:
            print(" Error: ", e)

    def insert_node_at_position(self, data, k):
        """
        Inserts an integer in k position of the linked list

        """
        try:
            # if we wish to insert at the first node
            if k == 1:
                temp = Node(data)
                temp.link = self.start
                self.start = temp
                return

            p = self.start
            i = 1

            while i < k-1 and p is not None:
                p = p.link
                i += 1

            if p is None:
                print(f" The max position is {i}") 
            else:    
                temp = Node(data)
                temp.link = self.start
                self.start = temp

        except Exception as e:
            print(" Error: ", e)

    def delete_a_node(self, x):
        """
        Deletes a node of a linked list

        """
        try:
            # If list is empty
            if self.start is None:
                print(" Sorry! The list is empty.")
                return

            # If there is only one node
            if self.start.info == x:
                self.start = self.start.link

            # If more than one node exists
            p = self.start
            while p.link is not None:
                if p.link.info == x:
                    break   
                p = p.link

            if p.link is None:
                print(f" Sorry! {x} is not in the list.")
            else:
                p.link = p.link.link

        except Exception as e:
            print(" Error: ", e)

    def delete_sll_first_node(self):
        """
        Deletes the first node of a linked list

        """
        try:
            if self.start is None:
                return
            self.start = self.start.link

        except Exception as e:
            print(" Error: ", e)


    def delete_sll_last_node(self):
        """
        Deletes the last node of a linked list

        """
        try:

            # If the list is empty
            if self.start is None:
                return

            # If there is only one node
            if self.start.link is None:
                self.start = None
                return

            # If there is more than one node    
            p = self.start

            # Increment until we find the node prior to the last node 
            while p.link.link is not None:
                p = p.link

            p.link = None   

        except Exception as e:
            print(" Error: ", e)


    def reverse_sll(self):
        """
        Reverses the linked list

        """

        try:

            prev = None
            p = self.start
            while p is not None:
                next = p.link
                p.link = prev
                prev = p
                p = next
            self.start = prev

        except Exception as e:
            print(" Error: ", e)


    def bubble_sort_sll_nodes_data(self):
        """
        Bubble sorts the linked list on integer values

        """

        try:

            # If the list is empty or there is only one node
            if self.start is None or self.start.link is None:
                print(" The list has no or only one node and sorting is not required.")
            end = None

            while end != self.start.link:
                p = self.start
                while p.link != end:
                    q = p.link
                    if p.info > q.info:
                        p.info, q.info = q.info, p.info
                    p = p.link
                end = p

        except Exception as e:
            print(" Error: ", e)


    def bubble_sort_sll(self):
        """
        Bubble sorts the linked list

        """

        try:

            # If the list is empty or there is only one node
            if self.start is None or self.start.link is None:
                print(" The list has no or only one node and sorting is not required.")
            end = None

            while end != self.start.link:
                r = p = self.start
                while p.link != end:
                    q = p.link
                    if p.info > q.info:
                        p.link = q.link
                        q.link = p
                    if  p != self.start:
                        r.link = q.link
                    else:
                        self.start = q
                    p, q = q, p
                    r = p
                    p = p.link
                end = p

        except Exception as e:
            print(" Error: ", e)


    def sll_has_cycle(self):
        """
        Tests the list for cycles using Tortoise and Hare Algorithm (Floyd's cycle detection algorithm)
        """

        try:

            if self.find_sll_cycle() is None:
                return False
            else:
                return True


        except Exception as e:
            print(" Error: ", e)


    def find_sll_cycle(self):
        """
        Finds cycles in the list, if any
        """

        try:

            # If there is one node or none, there is no cycle
            if self.start is None or self.start.link is None:
                return None

            # Otherwise, 
            slowR = self.start
            fastR = self.start

            while slowR is not None and fastR is not None:
                slowR = slowR.link
                fastR = fastR.link.link
                if slowR == fastR: 
                    return slowR

            return None

        except Exception as e:
            print(" Error: ", e)


    def remove_cycle_from_sll(self):
        """
        Removes the cycles
        """

        try:

            c = self.find_sll_cycle()

            # If there is no cycle
            if c is None:
                return

            print(f" There is a cycle at node: ", c.info)

            p = c
            q = c
            len_cycles = 0
            while True:
                len_cycles += 1
                q = q.link

                if p == q:
                    break

            print(f" The cycle length is {len_cycles}")

            len_rem_list = 0
            p = self.start

            while p != q:
                len_rem_list += 1
                p = p.link
                q = q.link

            print(f" The number of nodes not included in the cycle is {len_rem_list}")

            length_list = len_rem_list + len_cycles

            print(f" The SLL length is {length_list}")

            # This for loop goes to the end of the SLL, and set the last node to None and the cycle is removed. 
            p = self.start
            for _ in range(length_list-1):
                p = p.link
            p.link = None


        except Exception as e:
            print(" Error: ", e)


    def insert_cycle_in_sll(self, x):
        """
        Inserts a cycle at a node that contains x

        """

        try:

            if self.start is None:
                return False

            p = self.start
            px = None
            prev = None


            while p is not None:
                if p.info == x:
                    px = p
                prev = p
                p = p.link

            if px is not None:
                prev.link = px
            else:
                print(f" Sorry! {x} is not in the list.")


        except Exception as e:
            print(" Error: ", e)


    def merge_using_new_list(self, list2):
        """
        Merges two already sorted SLLs by creating new lists
        """
        merge_list = SingleLinkedList()
        merge_list.start = self._merge_using_new_list(self.start, list2.start)
        return merge_list

    def _merge_using_new_list(self, p1, p2):
        """
        Private method of merge_using_new_list
        """
        if p1.info <= p2.info:
            Start_merge = Node(p1.info)
            p1 = p1.link
        else:
            Start_merge = Node(p2.info)
            p2 = p2.link            
        pM = Start_merge

        while p1 is not None and p2 is not None:
            if p1.info <= p2.info:
                pM.link = Node(p1.info)
                p1 = p1.link
            else:
                pM.link = Node(p2.info)
                p2 = p2.link
            pM = pM.link

        #If the second list is finished, yet the first list has some nodes
        while p1 is not None:
            pM.link = Node(p1.info)
            p1 = p1.link
            pM = pM.link

        #If the second list is finished, yet the first list has some nodes
        while p2 is not None:
            pM.link = Node(p2.info)
            p2 = p2.link
            pM = pM.link

        return Start_merge

    def merge_inplace(self, list2):
        """
        Merges two already sorted SLLs in place in O(1) of space
        """
        merge_list = SingleLinkedList()
        merge_list.start = self._merge_inplace(self.start, list2.start)
        return merge_list

    def _merge_inplace(self, p1, p2):
        """
        Merges two already sorted SLLs in place in O(1) of space
        """
        if p1.info <= p2.info:
            Start_merge = p1
            p1 = p1.link
        else:
            Start_merge = p2
            p2 = p2.link
        pM = Start_merge

        while p1 is not None and p2 is not None:
            if p1.info <= p2.info:
                pM.link = p1
                pM = pM.link
                p1 = p1.link
            else:
                pM.link = p2
                pM = pM.link
                p2 = p2.link

        if p1 is None:
            pM.link = p2
        else:
            pM.link = p1

        return Start_merge

    def merge_sort_sll(self):
        """
        Sorts the linked list using merge sort algorithm
        """
        self.start = self._merge_sort_recursive(self.start)


    def _merge_sort_recursive(self, list_start):
        """
        Recursively calls the merge sort algorithm for two divided lists
        """

        # If the list is empty or has only one node
        if list_start is None or list_start.link is None:
            return list_start

        # If the list has two nodes or more
        start_one = list_start
        start_two = self._divide_list(self_start)
        start_one = self._merge_sort_recursive(start_one)
        start_two = self._merge_sort_recursive(start_two)
        start_merge = self._merge_inplace(start_one, start_two)

        return start_merge

    def _divide_list(self, p):
        """
        Divides the linked list into two almost equally sized lists
        """

        # Refers to the third nodes of the list
        q = p.link.link

        while q is not None and p is not None:
            # Increments p one node at the time
            p = p.link
            # Increments q two nodes at the time
            q = q.link.link

        start_two = p.link
        p.link = None

        return start_two

    def concat_second_list_to_sll(self, list2):
        """
        Concatenates another SLL to an existing SLL
        """

        # If the second SLL has no node
        if list2.start is None:
            return

        # If the original SLL has no node
        if self.start is None:
            self.start = list2.start
            return

        # Otherwise traverse the original SLL
        p = self.start
        while p.link is not None:
            p = p.link

        # Link the last node to the first node of the second SLL
        p.link = list2.start



    def test_merge_using_new_list_and_inplace(self):
        """

        """

        LIST_ONE = SingleLinkedList()
        LIST_TWO = SingleLinkedList()

        LIST_ONE.create_single_linked_list()
        LIST_TWO.create_single_linked_list()

        print("1??  The unsorted first list is: ")
        LIST_ONE.display_sll()

        print("2??  The unsorted second list is: ")
        LIST_TWO.display_sll()


        LIST_ONE.bubble_sort_sll_nodes_data()
        LIST_TWO.bubble_sort_sll_nodes_data()

        print("1??  The sorted first list is: ")
        LIST_ONE.display_sll()

        print("2??  The sorted second list is: ")
        LIST_TWO.display_sll()

        LIST_THREE = LIST_ONE.merge_using_new_list(LIST_TWO)

        print("The merged list by creating a new list is: ")
        LIST_THREE.display_sll()


        LIST_FOUR = LIST_ONE.merge_inplace(LIST_TWO)

        print("The in-place merged list is: ")
        LIST_FOUR.display_sll()     


    def test_all_methods(self):
        """
        Tests all methods of the SLL class
        """

        OPTIONS_HELP = """

    Select a method from 1-19:                                                          

        ??   (1)      Create a single liked list (SLL).
        ??   (2)      Display the SLL.                            
        ??   (3)      Count the nodes of SLL. 
        ??   (4)      Search the SLL.
        ??   (5)      Insert a node at the beginning of the SLL.
        ??   (6)      Insert a node at the end of the SLL.
        ??   (7)      Insert a node after a specified node of the SLL.
        ??   (8)      Insert a node before a specified node of the SLL.
        ??   (9)      Delete the first node of SLL.
        ??   (10)     Delete the last node of the SLL.
        ??   (11)     Delete a node you wish to remove.                           
        ??   (12)     Reverse the SLL.
        ??   (13)     Bubble sort the SLL by only exchanging the integer values.  
        ??   (14)     Bubble sort the SLL by exchanging links.                    
        ??   (15)     Merge sort the SLL.
        ??   (16)     Insert a cycle in the SLL.
        ??   (17)     Detect if the SLL has a cycle.
        ??   (18)     Remove cycle in the SLL.
        ??   (19)     Test merging two bubble-sorted SLLs.
        ??   (20)     Concatenate a second list to the SLL. 
        ??   (21)     Exit.

        """


        self.create_single_linked_list()

        while True:

            print(OPTIONS_HELP)

            UI_OPTION = int(input("   Enter an integer for the method you wish to run using the above help: "))

            if UI_OPTION == 1:
                data = int(input("   Enter an integer to be inserted at the end of the list: "))
                x = int(input("   Enter an integer to be inserted after that: "))
                self.insert_node_after_another(data, x)
            elif UI_OPTION == 2:
                self.display_sll()
            elif UI_OPTION == 3:
                self.count_sll_nodes()
            elif UI_OPTION == 4:
                data = int(input("   Enter an integer to be searched: "))
                self.search_sll_nodes(data)
            elif UI_OPTION == 5:
                data = int(input("   Enter an integer to be inserted at the beginning: "))
                self.insert_node_in_beginning(data)
            elif UI_OPTION == 6:
                data = int(input("   Enter an integer to be inserted at the end: "))
                self.insert_node_at_end(data)
            elif UI_OPTION == 7:
                data = int(input("   Enter an integer to be inserted: "))
                x = int(input("   Enter an integer to be inserted before that: "))
                self.insert_node_before_another(data, x)
            elif UI_OPTION == 8:
                data = int(input("   Enter an integer for the node to be inserted: "))
                k = int(input("   Enter an integer for the position at which you wish to insert the node: "))
                self.insert_node_before_another(data, k)
            elif UI_OPTION == 9:
                self.delete_sll_first_node()
            elif UI_OPTION == 10:
                self.delete_sll_last_node()
            elif UI_OPTION == 11:
                data = int(input("   Enter an integer for the node you wish to remove: "))
                self.delete_a_node(data)
            elif UI_OPTION == 12:
                self.reverse_sll()
            elif UI_OPTION == 13:
                self.bubble_sort_sll_nodes_data()
            elif UI_OPTION == 14:
                self.bubble_sort_sll()
            elif UI_OPTION == 15:
                self.merge_sort_sll()
            elif UI_OPTION == 16:
                data = int(input("   Enter an integer at which a cycle has to be formed: "))
                self.insert_cycle_in_sll(data)
            elif UI_OPTION == 17:
                if self.sll_has_cycle():
                    print(" The linked list has a cycle. ")
                else:
                    print(" YAAAY! The linked list does not have a cycle. ")
            elif UI_OPTION == 18:
                self.remove_cycle_from_sll()
            elif UI_OPTION == 19:
                self.test_merge_using_new_list_and_inplace()
            elif UI_OPTION == 20:
                list2 = self.create_single_linked_list()
                self.concat_second_list_to_sll(list2)
            elif UI_OPTION == 21:
                break
            else:
                print(" Option must be an integer, between 1 to 21.")

            print()     



if __name__ == '__main__':
    # Instantiates a new SLL object
    SLL_OBJECT = SingleLinkedList()
    SLL_OBJECT.test_all_methods()

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

ios will always tries to take the best image, but will fall back to other options .. so if you only have normal images in the app and it needs @2x images it will use the normal images.

if you only put @2x in the project and you open the app on a normal device it will scale the images down to display.

if you target ios7 and ios8 devices and want best quality you would need @2x and @3x for phone and normal and @2x for ipad assets, since there is no non retina phone left and no @3x ipad.

maybe it is better to create the assets in the app from vector graphic... check http://mattgemmell.com/using-pdf-images-in-ios-apps/

Axios get in url works but with second parameter as object it doesn't

On client:

  axios.get('/api', {
      params: {
        foo: 'bar'
      }
    });

On server:

function get(req, res, next) {

  let param = req.query.foo
   .....
}

Removing App ID from Developer Connection

Delete application IDs is allowed. Make sure you deleted all certificates, APNS certs and provisioning profiles associated with your application. Then go to Identitifies --> App IDs, select the application ID, Edit and Delete button should be enabled.

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

Node.js - SyntaxError: Unexpected token import

In my case it was looking after .babelrc file, and it should contain something like this:

{
  "presets": ["es2015-node5", "stage-3"],
  "plugins": []
}

Using "margin: 0 auto;" in Internet Explorer 8

One more time: we all hate IE!

<div style="width:100%;background-color:blue;">
    <div style="margin:0 auto;width:300px;background-color:red;">
        Not Working
    </div>
</div>

<div style="width:100%;background-color:green;text-align:center;">
    <div style="margin:0 auto;width:300px;background-color:orange;text-align:left;">
        Working, but dumb that you have to use text-align
    </div>
</div>

denied: requested access to the resource is denied : docker

In my case I was pushing to an organization where I am in a team that has admin permissions to the repository.

so my push command was: docker push org-name/image-name

I could push successfully to username/image-name but not to the organization. I triple checked the permissions. Nothing worked.

The solution was to delete the repo from docker hub and push again fresh using: docker push org-name/image-name

For what its worth, I think the repo was originally pushed before the account was converted to an organization.

Append a tuple to a list - what's the difference between two ways?

It has nothing to do with append. tuple(3, 4) all by itself raises that error.

The reason is that, as the error message says, tuple expects an iterable argument. You can make a tuple of the contents of a single object by passing that single object to tuple. You can't make a tuple of two things by passing them as separate arguments.

Just do (3, 4) to make a tuple, as in your first example. There's no reason not to use that simple syntax for writing a tuple.

Cannot read property 'push' of undefined when combining arrays

answer to your question is simple order is not a object make it an array. var order = new Array(); order.push(/item to push/); when ever this error appears just check the left of which property the error is in this case it is push which is order[] so it is undefined.

CodeIgniter : Unable to load the requested file:

"Unable to load the requested file"

Can be also caused by access permissions under linux , make sure you set the correct read permissions for the directory "views/home"

AngularJS $watch window resize inside directive

You can listen resize event and fire where some dimension change

directive

(function() {
'use strict';

    angular
    .module('myApp.directives')
    .directive('resize', ['$window', function ($window) {
        return {
            link: link,
            restrict: 'A'
        };

        function link(scope, element, attrs){
            scope.width = $window.innerWidth;
            function onResize(){
                // uncomment for only fire when $window.innerWidth change   
                // if (scope.width !== $window.innerWidth)
                {
                    scope.width = $window.innerWidth;
                    scope.$digest();
                }
            };

            function cleanUp() {
                angular.element($window).off('resize', onResize);
            }

            angular.element($window).on('resize', onResize);
            scope.$on('$destroy', cleanUp);
        }
    }]);
})();

In html

<div class="row" resize> ,
    <div class="col-sm-2 col-xs-6" ng-repeat="v in tag.vod"> 
        <h4 ng-bind="::v.known_as"></h4>
    </div> 
</div> 

Controller :

$scope.$watch('width', function(old, newv){
     console.log(old, newv);
 })

Why doesn't Dijkstra's algorithm work for negative weight edges?

The other answers so far demonstrate pretty well why Dijkstra's algorithm cannot handle negative weights on paths.

But the question itself is maybe based on a wrong understanding of the weight of paths. If negative weights on paths would be allowed in pathfinding algorithms in general, then you would get permanent loops that would not stop.

Consider this:

A  <- 5 ->  B  <- (-1) ->  C <- 5 -> D

What is the optimal path between A and D?

Any pathfinding algorithm would have to continuously loop between B and C because doing so would reduce the weight of the total path. So allowing negative weights for a connection would render any pathfindig algorithm moot, maybe except if you limit each connection to be used only once.

So, to explain this in more detail, consider the following paths and weights:

Path               | Total weight
ABCD               | 9
ABCBCD             | 7
ABCBCBCD           | 5
ABCBCBCBCD         | 3
ABCBCBCBCBCD       | 1
ABCBCBCBCBCBCD     | -1
...

So, what's the perfect path? Any time the algorithm adds a BC step, it reduces the total weight by 2.

So the optimal path is A (BC) D with the BC part being looped forever.

Since Dijkstra's goal is to find the optimal path (not just any path), it, by definition, cannot work with negative weights, since it cannot find the optimal path.

Dijkstra will actually not loop, since it keeps a list of nodes that it has visited. But it will not find a perfect path, but instead just any path.

Regular vs Context Free Grammars

Regular grammar is either right or left linear, whereas context free grammar is basically any combination of terminals and non-terminals. Hence you can see that regular grammar is a subset of context-free grammar.

So for a palindrome for instance, is of the form,

S->ABA
A->something
B->something

You can clearly see that palindromes cannot be expressed in regular grammar since it needs to be either right or left linear and as such cannot have a non-terminal on both side.

Since regular grammars are non-ambiguous, there is only one production rule for a given non-terminal, whereas there can be more than one in the case of a context-free grammar.

Detecting Back Button/Hash Change in URL

The answers here are all quite old.

In the HTML5 world, you should the use onpopstate event.

window.onpopstate = function(event)
{
    alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

Or:

window.addEventListener('popstate', function(event)
{
    alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
});

The latter snippet allows multiple event handlers to exist, whereas the former will replace any existing handler which may cause hard-to-find bugs.

How to size an Android view based on its parent's dimensions

You can now use PercentRelativeLayout. Boom! Problem solved.

How Big can a Python List Get?

It varies for different systems (depends on RAM). The easiest way to find out is

import six six.MAXSIZE 9223372036854775807 This gives the max size of list and dict too ,as per the documentation

Connecting to remote URL which requires authentication using Java

You can also use the following, which does not require using external packages:

URL url = new URL(“location address”);
URLConnection uc = url.openConnection();

String userpass = username + ":" + password;
String basicAuth = "Basic " + javax.xml.bind.DatatypeConverter.printBase64Binary(userpass.getBytes());

uc.setRequestProperty ("Authorization", basicAuth);
InputStream in = uc.getInputStream();

How to add data via $.ajax ( serialize() + extra data ) like this

You can do it like this:

postData[postData.length] = { name: "variable_name", value: variable_value };

Insert an item into sorted list in Python

This is the best way to append the list and insert values to sorted list:

 a = [] num = int(input('How many numbers: ')) for n in range(num):
     numbers = int(input('Enter values:'))
     a.append(numbers)

 b = sorted(a) print(b) c = int(input("enter value:")) for i in
 range(len(b)):
     if b[i] > c:
         index = i
         break d = b[:i] + [c] + b[i:] print(d)`

Loop backwards using indices in Python?

a = 10
for i in sorted(range(a), reverse=True):
    print i

Regular expression replace in C#

Try this::

sb_trim = Regex.Replace(stw, @"(\D+)\s+\$([\d,]+)\.\d+\s+(.)",
    m => string.Format(
        "{0},{1},{2}",
        m.Groups[1].Value,
        m.Groups[2].Value.Replace(",", string.Empty),
        m.Groups[3].Value));

This is about as clean an answer as you'll get, at least with regexes.

  • (\D+): First capture group. One or more non-digit characters.
  • \s+\$: One or more spacing characters, then a literal dollar sign ($).
  • ([\d,]+): Second capture group. One or more digits and/or commas.
  • \.\d+: Decimal point, then at least one digit.
  • \s+: One or more spacing characters.
  • (.): Third capture group. Any non-line-breaking character.

The second capture group additionally needs to have its commas stripped. You could do this with another regex, but it's really unnecessary and bad for performance. This is why we need to use a lambda expression and string format to piece together the replacement. If it weren't for that, we could just use this as the replacement, in place of the lambda expression:

"$1,$2,$3"

Spring MVC: Complex object as GET @RequestParam

While answers that refer to @ModelAttribute, @RequestParam, @PathParam and the likes are valid, there is a small gotcha I ran into. The resulting method parameter is a proxy that Spring wraps around your DTO. So, if you attempt to use it in a context that requires your own custom type, you may get some unexpected results.

The following will not work:

@GetMapping(produces = APPLICATION_JSON_VALUE)
public ResponseEntity<CustomDto> request(@ModelAttribute CustomDto dto) {
    return ResponseEntity.ok(dto);
}

In my case, attempting to use it in Jackson binding resulted in a com.fasterxml.jackson.databind.exc.InvalidDefinitionException.

You will need to create a new object from the dto.

How to set fake GPS location on IOS real device

Create a .GPX file with xcode, then specify your coordinates and when your device connected, hit the little arrow button and select your .GPX file. You can create multiple files and add lots of coordinates to single .GPX file in order to make some kind of route.

How to set portrait and landscape media queries in css?

iPad Media Queries (All generations - including iPad mini)

Thanks to Apple's work in creating a consistent experience for users, and easy time for developers, all 5 different iPads (iPads 1-5 and iPad mini) can be targeted with just one CSS media query. The next few lines of code should work perfect for a responsive design.

iPad in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px)  { /* STYLES GO HERE */}

iPad in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) { /* STYLES GO HERE */}

iPad in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) { /* STYLES GO HERE */ }

iPad 3 & 4 Media Queries

If you're looking to target only 3rd and 4th generation Retina iPads (or tablets with similar resolution) to add @2x graphics, or other features for the tablet's Retina display, use the following media queries.

Retina iPad in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

Retina iPad in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

Retina iPad in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */ }

iPad 1 & 2 Media Queries

If you're looking to supply different graphics or choose different typography for the lower resolution iPad display, the media queries below will work like a charm in your responsive design!

iPad 1 & 2 in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (-webkit-min-device-pixel-ratio: 1){ /* STYLES GO HERE */}

iPad 1 & 2 in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 1)  { /* STYLES GO HERE */}

iPad 1 & 2 in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) 
and (-webkit-min-device-pixel-ratio: 1) { /* STYLES GO HERE */ }

Source: http://stephen.io/mediaqueries/

Adjust list style image position?

Not really. Your padding is (probably) being applied to the list item, so will only affect the actual content within the list item.

Using a combination of background and padding styles can create something that looks similar e.g.

li {
  background: url(images/bullet.gif) no-repeat left top; /* <-- change `left` & `top` too for extra control */
  padding: 3px 0px 3px 10px;
  /* reset styles (optional): */
  list-style: none;
  margin: 0;
}

You might be looking to add styling to the parent list container (ul) to position your bulleted list items, this A List Apart article has a good starting reference.

AngularJS $http, CORS and http authentication

For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.

For enabling headers in Ubuntu:

sudo a2enmod headers

For php server to accept request from different origin use:

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

I was facing the same issue and just updated the JAVA_HOME worked for me.

previously it was like this: C:\Program Files\Java\jdk1.6.0_45\bin Just removed the \bin and it worked for me.

How to convert file to base64 in JavaScript?

I have used this simple method and it's worked successfully

 function  uploadImage(e) {
  var file = e.target.files[0];
    let reader = new FileReader();
    reader.onload = (e) => {
    let image = e.target.result;
    console.log(image);
    };
  reader.readAsDataURL(file);
  
}

How to turn off page breaks in Google Docs?

I also rarely want to print my google docs, and the breaks annoyed me as well.

I installed the Page Sizer add-on from the add-ons menu within google docs, and made the page really long.

The page settings work globally. So your collaborators will also enjoy a page page-break-free experience in google docs, unlike the style-bot solution.

How to turn a string formula into a "real" formula

The best, non-VBA, way to do this is using the TEXT formula. It takes a string as an argument and converts it to a value.

For example, =TEXT ("0.4*A1",'##') will return the value of 0.4 * the value that's in cell A1 of that worksheet.

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

You can also do

t.index([:branch_id, :party_id], unique: true, name: 'by_branch_party')

as in the Ruby on Rails API.

inner join in linq to entities

public IList<Splitting> get(Guid companyId, long customrId) {    
    var res=from c in Customers_data_source
            where c.CustomerId = customrId && c.CompanyID == companyId
            from s in Splittings_data_srouce
            where s.CustomerID = c.CustomerID
            select s;

    return res.ToList();
}

psql: FATAL: database "<user>" does not exist

Connect to postgres via existing superuser.

Create a Database by the name of user you are connecting through to postgres.

create database username;

Now try to connect via username

How to view unallocated free space on a hard disk through terminal

Use GNU parted and print free command:

root@sandbox:~# parted
GNU Parted 2.3
Using /dev/sda
Welcome to GNU Parted! Type 'help' to view a list of commands.
(parted) print free
Model: VMware Virtual disk (scsi)
Disk /dev/sda: 64.4GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End     Size    Type      File system  Flags
        32.3kB  1049kB  1016kB            Free Space
 1      1049kB  256MB   255MB   primary   ext2         boot
        256MB   257MB   1048kB            Free Space
 2      257MB   64.4GB  64.2GB  extended
 5      257MB   64.4GB  64.2GB  logical                lvm
        64.4GB  64.4GB  1049kB            Free Space

Swipe ListView item From right to left show delete button

see there link was very nice and simple. its working fine... u don't want any library its working fine. click here

OnTouchListener gestureListener = new View.OnTouchListener() {
    private int padding = 0;
    private int initialx = 0;
    private int currentx = 0;
    private  ViewHolder viewHolder;

    public boolean onTouch(View v, MotionEvent event) {
        if ( event.getAction() == MotionEvent.ACTION_DOWN) {
            padding = 0;
            initialx = (int) event.getX();
            currentx = (int) event.getX();
            viewHolder = ((ViewHolder) v.getTag());
        }
        if ( event.getAction() == MotionEvent.ACTION_MOVE) {
            currentx = (int) event.getX();
            padding = currentx - initialx;
        }       
        if ( event.getAction() == MotionEvent.ACTION_UP || 
                     event.getAction() == MotionEvent.ACTION_CANCEL) {
            padding = 0;
            initialx = 0;
            currentx = 0;
        }
        if(viewHolder != null) {
            if(padding == 0) {
                v.setBackgroundColor(0xFF000000 );  
                if(viewHolder.running)
                    v.setBackgroundColor(0xFF058805);
            }
            if(padding > 75) {
                viewHolder.running = true;
                v.setBackgroundColor(0xFF00FF00 );  
                viewHolder.icon.setImageResource(R.drawable.clock_running);
            }
            if(padding < -75) {
                viewHolder.running = false;
                v.setBackgroundColor(0xFFFF0000 );  
            }

            v.setPadding(padding, 0,0, 0);
        }

        return true;
    }
};

CSS Always On Top

Assuming that your markup looks like:

<div id="header" style="position: fixed;"></div>
<div id="content" style="position: relative;"></div>

Now both elements are positioned; in which case, the element at the bottom (in source order) will cover element above it (in source order).

Add a z-index on header; 1 should be sufficient.

Linq select object from list depending on objects attribute

I assume you are getting an exception because of Single. Your list may have more than one answer marked as correct, that is why Single will throw an exception use First, or FirstOrDefault();

Answer answer = Answers.FirstOrDefault(a => a.Correct);

Also if you want to get list of all items marked as correct you may try:

List<Answer> correctedAnswers =  Answers.Where(a => a.Correct).ToList();

If your desired result is Single, then the mistake you are doing in your query is comparing an item with the bool value. Your comparison

a == a.Correct

is wrong in the statement. Your single query should be:

Answer answer = Answers.Single(a => a.Correct == true);

Or shortly as:

Answer answer = Answers.Single(a => a.Correct);

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

After a bit of time (and more searching), I found this blog entry by Jomo Fisher.

One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:

Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

[Snip]

The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0"/>
</startup>

So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy attribute reverts back to CLR 2.0 loading.

How Can I Remove “public/index.php” in the URL Generated Laravel?

I tried this on Laravel 4.2

Rename the server.php in the your Laravel root folder to index.php and copy the .htaccess file from /public directory to your Laravel root folder.

I hope it works

How to create text file and insert data to that file on Android

I'm using Kotlin here

Just adding the information in here, you can also create readable file outside Private Directory for the apps by doing this example

var teks="your teks"
var NamaFile="Text1.txt"
var strwrt:FileWriter
 strwrt=FileWriter(File("sdcard/${NamaFile}"))
            strwrt.write(teks)
            strwrt.close()

after that you can acces File Manager and look up on the Internal Storage. Text1.txt will be on there below all the folder.

Scroll to the top of the page using JavaScript?

Just Try, no need other plugin / frameworks

_x000D_
_x000D_
document.getElementById("jarscroolbtn").addEventListener("click", jarscrollfunction);_x000D_
_x000D_
function jarscrollfunction() {_x000D_
  var body = document.body; // For Safari_x000D_
  var html = document.documentElement; // Chrome, Firefox, IE and Opera _x000D_
  body.scrollTop = 0; _x000D_
  html.scrollTop = 0;_x000D_
}
_x000D_
<button id="jarscroolbtn">Scroll contents</button> 
_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
html, body {_x000D_
  scroll-behavior: smooth;_x000D_
}
_x000D_
_x000D_
_x000D_

Difference between Pig and Hive? Why have both?

Hive Vs Pig-

Hive is as SQL interface which allows sql savvy users or Other tools like Tableu/Microstrategy/any other tool or language that has sql interface..

PIG is more like a ETL pipeline..with step by step commands like declaring variables, looping, iterating , conditional statements etc.

I prefer writing Pig scripts over hive QL when I want to write complex step by step logic. When I am comfortable writing a single sql for pulling the data i want i use Hive. for hive you will need to define table before querying(as you do in RDBMS)

The purpose of both are different but under the hood, both do the same, convert to map reduce programs.Also the Apache open source community is add more and more features to both there projects

How can I get the intersection, union, and subset of arrays in Ruby?

I assume X and Y are arrays? If so, there's a very simple way to do this:

x = [1, 1, 2, 4]
y = [1, 2, 2, 2]

# intersection
x & y            # => [1, 2]

# union
x | y            # => [1, 2, 4]

# difference
x - y            # => [4]

Source

Get Date Object In UTC format in Java

In java 8 , It's really easy to get timestamp in UTC by using java 8 java.time.Instant library :

Instant.now();

That few word of code will return the UTC Timestamp.

Calling @Html.Partial to display a partial view belonging to a different controller

That's no problem.

@Html.Partial("../Controller/View", model)

or

@Html.Partial("~/Views/Controller/View.cshtml", model)

Should do the trick.

If you want to pass through the (other) controller, you can use:

@Html.Action("action", "controller", parameters)

or any of the other overloads

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

I have a solution to a problem that may also apply to you. My database was in a state where a DROP TABLE failed because it couldn't find the table... but a CREATE TABLE also failed because MySQL thought the table existed. (This state could easily mess with your IF NOT EXISTS clause).

I eventually found this solution:

sudo mysqladmin flush-tables

For me, without the sudo, I got the following error:

mysqladmin: refresh failed; error: 'Access denied; you need the RELOAD privilege for this operation'

(Running on OS X 10.6)

JOptionPane Input to int

Simply use:

int ans = Integer.parseInt( JOptionPane.showInputDialog(frame,
        "Text",
        JOptionPane.INFORMATION_MESSAGE,
        null,
        null,
        "[sample text to help input]"));

You cannot cast a String to an int, but you can convert it using Integer.parseInt(string).

SQL Server Express CREATE DATABASE permission denied in database 'master'

Solution for Microsoft SQL Server, Error: 262

Click on Start -> Click in Microsoft SQL Server 2005 Now right click on SQL Server Management Studio Click on Run as administrator

How to set a parameter in a HttpServletRequest?

As mentioned in the previous posts, using an HttpServletReqiestWrapper is the way to go, however the missed part in those posts was that apart from overriding the method getParameter(), you should also override other parameter related methods to produce a consistent response. e.g. the value of a param added by the custom request wrapper should also be included in the parameters map returned by the method getParameterMap(). Here is an example:

   public class AddableHttpRequest extends HttpServletRequestWrapper {

    /** A map containing additional request params this wrapper adds to the wrapped request */
    private final Map<String, String> params = new HashMap<>();

    /**
     * Constructs a request object wrapping the given request.
     * @throws java.lang.IllegalArgumentException if the request is null
     */
    AddableHttpRequest(final HttpServletRequest request) {
        super(request)
    }

    @Override
    public String getParameter(final String name) {
        // if we added one with the given name, return that one
        if ( params.get( name ) != null ) {
            return params.get( name );
        } else {
            // otherwise return what's in the original request
            return super.getParameter(name);
        }
    }


    /**
     * *** OVERRIDE THE METHODS BELOW TO REFLECT PARAMETERS ADDED BY THIS WRAPPER ****
     */

    @Override
    public Map<String, String> getParameterMap() {
        // defaulf impl, should be overridden for an approprivate map of request params
        return super.getParameterMap();
    }

    @Override
    public Enumeration<String> getParameterNames() {
        // defaulf impl, should be overridden for an approprivate map of request params names
        return super.getParameterNames();
    }

    @Override
    public String[] getParameterValues(final String name) {
        // defaulf impl, should be overridden for an approprivate map of request params values
        return super.getParameterValues(name);
    }
}

Asynchronous file upload (AJAX file upload) using jsp and javascript

I don't believe AJAX can handle file uploads but this can be achieved with libraries that leverage flash. Another advantage of the flash implementation is the ability to do multiple files at once (like gmail).

SWFUpload is a good start : http://www.swfupload.org/documentation

jQuery and some of the other libraries have plugins that leverage SWFUpload. On my last project we used SWFUpload and Java without a problem.

Also helpful and worth looking into is Apache's FileUpload : http://commons.apache.org/fileupload/index.html

Using port number in Windows host file

This doesn't give the requested result exactly, however, for what I was doing, I was not fussed with adding the port into the URL within a browser.

I added the domain name to the hosts file

127.0.0.1      example.com

Ran my HTTP server from the domain name on port 8080

php -S example.com:8080

Then accessed the website through port 8080

http://example.com:8080

Just wanted to share in case anyone else is in a similar situation.

This Handler class should be static or leaks might occur: IncomingHandler

As others have mentioned the Lint warning is because of the potential memory leak. You can avoid the Lint warning by passing a Handler.Callback when constructing Handler (i.e. you don't subclass Handler and there is no Handler non-static inner class):

Handler mIncomingHandler = new Handler(new Handler.Callback() {
    @Override
    public boolean handleMessage(Message msg) {
        // todo
        return true;
    }
});

As I understand it, this will not avoid the potential memory leak. Message objects hold a reference to the mIncomingHandler object which holds a reference the Handler.Callback object which holds a reference to the Service object. As long as there are messages in the Looper message queue, the Service will not be GC. However, it won't be a serious issue unless you have long delay messages in the message queue.

jQuery - passing value from one input to another

Add ID attributes with same values as name attributes and then you can do this:

$('#first_name').change(function () {
  $('#firstname').val($(this).val());
});

How to get whole and decimal part of a number?

PHP 5.4+

$n = 12.343;
intval($n); // 12
explode('.', number_format($n, 1))[1]; // 3
explode('.', number_format($n, 2))[1]; // 34
explode('.', number_format($n, 3))[1]; // 343
explode('.', number_format($n, 4))[1]; // 3430

Do I need a content-type header for HTTP GET requests?

Get requests should not have content-type because they do not have request entity (that is, a body)

Android: Create a toggle button with image and no text

ToggleButton inherits from TextView so you can set drawables to be displayed at the 4 borders of the text. You can use that to display the icon you want on top of the text and hide the actual text

<ToggleButton
    android:id="@+id/toggleButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableTop="@android:drawable/ic_menu_info_details"
    android:gravity="center"
    android:textOff=""
    android:textOn=""
    android:textSize="0dp" />

The result compared to regular ToggleButton looks like

enter image description here

The seconds option is to use an ImageSpan to actually replace the text with an image. Looks slightly better since the icon is at the correct position but can't be done with layout xml directly.

You create a plain ToggleButton

<ToggleButton
    android:id="@+id/toggleButton3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="false" />

Then set the "text" programmatially

ToggleButton button = (ToggleButton) findViewById(R.id.toggleButton3);
ImageSpan imageSpan = new ImageSpan(this, android.R.drawable.ic_menu_info_details);
SpannableString content = new SpannableString("X");
content.setSpan(imageSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
button.setText(content);
button.setTextOn(content);
button.setTextOff(content);

The result here in the middle - icon is placed slightly lower since it takes the place of the text.

enter image description here

Error "The input device is not a TTY"

Using docker-compose exec -T fixed the problem for me via Jenkins

docker-compose exec -T containerName php script.php

How do I change the value of a global variable inside of a function

Just use the name of that variable.

In JavaScript, variables are only local to a function, if they are the function's parameter(s) or if you declare them as local explicitely by typing the var keyword before the name of the variable.

If the name of the local value has the same name as the global value, use the window object

See this jsfiddle

_x000D_
_x000D_
x = 1;_x000D_
y = 2;_x000D_
z = 3;_x000D_
_x000D_
function a(y) {_x000D_
  // y is local to the function, because it is a function parameter_x000D_
  console.log('local y: should be 10:', y); // local y through function parameter_x000D_
  y = 3; // will only overwrite local y, not 'global' y_x000D_
  console.log('local y: should be 3:', y); // local y_x000D_
  // global value could be accessed by referencing through window object_x000D_
  console.log('global y: should be 2:', window.y) // global y, different from local y ()_x000D_
_x000D_
  var x; // makes x a local variable_x000D_
  x = 4; // only overwrites local x_x000D_
  console.log('local x: should be 4:', x); // local x_x000D_
  _x000D_
  z = 5; // overwrites global z, because there is no local z_x000D_
  console.log('local z: should be 5:', z); // local z, same as global_x000D_
  console.log('global z: should be 5 5:', window.z, z) // global z, same as z, because z is not local_x000D_
}_x000D_
a(10);_x000D_
console.log('global x: should be 1:', x); // global x_x000D_
console.log('global y: should be 2:', y); // global y_x000D_
console.log('global z: should be 5:', z); // global z, overwritten in function a
_x000D_
_x000D_
_x000D_

Edit

With ES2015 there came two more keywords const and let, which also affect the scope of a variable (Language Specification)

Changing background color of selected cell?

I have a highly customized UITableViewCell. So I implemented my own cell selection.

cell.selectionStyle = UITableViewCellSelectionStyleNone;

I created a method in my cell's class:

- (void)highlightCell:(BOOL)highlight
{
    if (highlight) {
        self.contentView.backgroundColor = RGB(0x355881);
        _bodyLabel.textColor = RGB(0xffffff);
        _fromLabel.textColor = RGB(0xffffff);
        _subjectLabel.textColor = RGB(0xffffff);
        _dateLabel.textColor = RGB(0xffffff);
    }
    else {
        self.contentView.backgroundColor = RGB(0xf7f7f7);;
        _bodyLabel.textColor = RGB(0xaaaaaa);
        _fromLabel.textColor = [UIColor blackColor];
        _subjectLabel.textColor = [UIColor blackColor];
        _dateLabel.textColor = RGB(0x496487);
    }
}

In my UITableViewController class in ViewWillAppear added this:

NSIndexPath *tableSelection = [self.tableView indexPathForSelectedRow];
SideSwipeTableViewCell *cell = (SideSwipeTableViewCell*)[self.tableView cellForRowAtIndexPath:tableSelection];
[cell highlightCell:NO];

In didSelectRow added this:

SideSwipeTableViewCell *cell = (SideSwipeTableViewCell*)[self.tableView cellForRowAtIndexPath:indexPath];
[cell highlightCell:YES];

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

json.loads() takes a JSON encoded string, not a filename. You want to use json.load() (no s) instead and pass in an open file object:

with open('/Users/JoshuaHawley/clean1.txt') as jsonfile:
    data = json.load(jsonfile)

The open() command produces a file object that json.load() can then read from, to produce the decoded Python object for you. The with statement ensures that the file is closed again when done.

The alternative is to read the data yourself and then pass it into json.loads().

Pods stuck in Terminating status

I'd not recommend force deleting pods unless container already exited.

  1. Verify kubelet logs to see what is causing the issue "journalctl -u kubelet"
  2. Verify docker logs: journalctl -u docker.service
  3. Check if pod's volume mount points still exist and if anyone holds lock on it.
  4. Verify if host is out of memory or disk

Iterating each character in a string using Python

Several answers here use range. xrange is generally better as it returns a generator, rather than a fully-instantiated list. Where memory and or iterables of widely-varying lengths can be an issue, xrange is superior.

AngularJS ng-repeat handle empty list case

you can use ng-if because this is not render in html page and you dont see your html tag in inspect...

<ul ng-repeat="item in items" ng-if="items.length > 0">
    <li>{{item}}<li>
</ul>
<div class="alert alert-info">there is no items!</div>

Create tap-able "links" in the NSAttributedString of a UILabel?

Drop-in solution as a category on UILabel (this assumes your UILabel uses an attributed string with some NSLinkAttributeName attributes in it):

@implementation UILabel (Support)

- (BOOL)openTappedLinkAtLocation:(CGPoint)location {
  CGSize labelSize = self.bounds.size;

  NSTextContainer* textContainer = [[NSTextContainer alloc] initWithSize:CGSizeZero];
  textContainer.lineFragmentPadding = 0.0;
  textContainer.lineBreakMode = self.lineBreakMode;
  textContainer.maximumNumberOfLines = self.numberOfLines;
  textContainer.size = labelSize;

  NSLayoutManager* layoutManager = [[NSLayoutManager alloc] init];
  [layoutManager addTextContainer:textContainer];

  NSTextStorage* textStorage = [[NSTextStorage alloc] initWithAttributedString:self.attributedText];
  [textStorage addAttribute:NSFontAttributeName value:self.font range:NSMakeRange(0, textStorage.length)];
  [textStorage addLayoutManager:layoutManager];

  CGRect textBoundingBox = [layoutManager usedRectForTextContainer:textContainer];
  CGPoint textContainerOffset = CGPointMake((labelSize.width - textBoundingBox.size.width) * 0.5 - textBoundingBox.origin.x,
                                            (labelSize.height - textBoundingBox.size.height) * 0.5 - textBoundingBox.origin.y);
  CGPoint locationOfTouchInTextContainer = CGPointMake(location.x - textContainerOffset.x, location.y - textContainerOffset.y);
  NSInteger indexOfCharacter = [layoutManager characterIndexForPoint:locationOfTouchInTextContainer inTextContainer:textContainer fractionOfDistanceBetweenInsertionPoints:nullptr];
  if (indexOfCharacter >= 0) {
    NSURL* url = [textStorage attribute:NSLinkAttributeName atIndex:indexOfCharacter effectiveRange:nullptr];
    if (url) {
      [[UIApplication sharedApplication] openURL:url];
      return YES;
    }
  }
  return NO;
}

@end

Choose File Dialog

I have implemented the Samsung File Selector Dialog, it provides the ability to open, save file, file extension filter, and create new directory in the same dialog I think it worth trying Here is the Link you have to log in to Samsung developer site to view the solution

Reverse a string without using reversed() or [::-1]?

You've received a lot of alternative answers, but just to add another simple solution -- the first thing that came to mind something like this:

def reverse(text):
    reversed_text = ""   

    for n in range(len(text)):
        reversed_text += text[-1 - n]

    return reversed_text

It's not as fast as some of the other options people have mentioned(or built in methods), but easy to follow as we're simply using the length of the text string to concatenate one character at a time by slicing from the end toward the front.

Center align "span" text inside a div

If you know the width of the span you could just stuff in a left margin.

Try this:

.center { text-align: center}
div.center span { display: table; }

Add the "center: class to your .

If you want some spans centered, but not others, replace the "div.center span" in your style sheet to a class (e.g "center-span") and add that class to the span.

IOError: [Errno 13] Permission denied

I have a really stupid use case for why I got this error. Originally I was printing my data > file.txt

Then I changed my mind, and decided to use open("file.txt", "w") instead. But when I called python, I left > file.txt .....

Loading custom configuration files

the articles posted by Ricky are very good, but unfortunately they don't answer your question.

To solve your problem you should try this piece of code:

ExeConfigurationFileMap configMap = new ExeConfigurationFileMap();
configMap.ExeConfigFilename = @"d:\test\justAConfigFile.config.whateverYouLikeExtension";
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);

If need to access a value within the config you can use the index operator:

config.AppSettings.Settings["test"].Value;

Android emulator failed to allocate memory 8

Reducing the RAM size in the AVD settings worked for me. The AVD being slow can eat up a lot of RAM, so keeping it at a minimum is feasible.

How to copy a char array in C?

You cannot assign arrays, the names are constants that cannot be changed.

You can copy the contents, with:

strcpy(array2, array1);

assuming the source is a valid string and that the destination is large enough, as in your example.

When is null or undefined used in JavaScript?

I find that some of these answers are vague and complicated, I find the best way to figure out these things for sure is to just open up the console and test it yourself.

var x;

x == null            // true
x == undefined       // true
x === null           // false
x === undefined      // true

var y = null;

y == null            // true
y == undefined       // true
y === null           // true
y === undefined      // false

typeof x             // 'undefined'
typeof y             // 'object'

var z = {abc: null};

z.abc == null        // true
z.abc == undefined   // true
z.abc === null       // true
z.abc === undefined  // false

z.xyz == null        // true
z.xyz == undefined   // true
z.xyz === null       // false
z.xyz === undefined  // true

null = 1;            // throws error: invalid left hand assignment
undefined = 1;       // works fine: this can cause some problems

So this is definitely one of the more subtle nuances of JavaScript. As you can see, you can override the value of undefined, making it somewhat unreliable compared to null. Using the == operator, you can reliably use null and undefined interchangeably as far as I can tell. However, because of the advantage that null cannot be redefined, I might would use it when using ==.

For example, variable != null will ALWAYS return false if variable is equal to either null or undefined, whereas variable != undefined will return false if variable is equal to either null or undefined UNLESS undefined is reassigned beforehand.

You can reliably use the === operator to differentiate between undefined and null, if you need to make sure that a value is actually undefined (rather than null).

According to the ECMAScript 5 spec:

  • Both Null and Undefined are two of the six built in types.

4.3.9 undefined value

primitive value used when a variable has not been assigned a value

4.3.11 null value

primitive value that represents the intentional absence of any object value

Fastest way to write huge data in text file Java

For those who want to improve the time for retrieval of records and dump into the file (i.e no processing on records), instead of putting them into an ArrayList, append those records into a StringBuffer. Apply toSring() function to get a single String and write it into the file at once.

For me, the retrieval time reduced from 22 seconds to 17 seconds.

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

i mange to fix the issue by updating state. when you trigger find or any other query operation on the same record sate has been updated with modified so we need to set status to Detached then you can fire your update change

     ActivityEntity activity = new ActivityEntity();
      activity.name="vv";
    activity.ID = 22 ; //sample id
   var savedActivity = context.Activities.Find(22);

            if (savedActivity!=null)
            {
                context.Entry(savedActivity).State = EntityState.Detached;
                context.SaveChanges();

                activity.age= savedActivity.age;
                activity.marks= savedActivity.marks; 

                context.Entry(activity).State = EntityState.Modified;
                context.SaveChanges();
                return activity.ID;
            }

static function in C

Making a function static hides it from other translation units, which helps provide encapsulation.

helper_file.c

int f1(int);        /* prototype */
static int f2(int); /* prototype */

int f1(int foo) {
    return f2(foo); /* ok, f2 is in the same translation unit */
                    /* (basically same .c file) as f1         */
}

int f2(int foo) {
    return 42 + foo;
}

main.c:

int f1(int); /* prototype */
int f2(int); /* prototype */

int main(void) {
    f1(10); /* ok, f1 is visible to the linker */
    f2(12); /* nope, f2 is not visible to the linker */
    return 0;
}

How to check if a radiobutton is checked in a radiogroup in Android?

I used the id's of my radiobuttons to compare with the id of the checkedRadioButton that I got using mRadioGroup.getCheckedRadioButtonId()

Here is my code:

mRadioButton1=(RadioButton)findViewById(R.id.first);
mRadioButton2=(RadioButton)findViewById(R.id.second);
mRadioButton3=(RadioButton)findViewById(R.id.third);
mRadioButton4=(RadioButton)findViewById(R.id.fourth);

mNextButton=(Button)findViewById(R.id.next_button);

mNextButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        int selectedId=mRadioGroup.getCheckedRadioButtonId();

        int n=0;
        if(selectedId==R.id.first){n=1;}

        else if(selectedId==R.id.second){n=2;}

        else if(selectedId==R.id.third){n=3;}

        else if(selectedId==R.id.fourth){n=4;}
        //. . . .
    }

Bootstrap 3 - set height of modal window according to screen size

Similar to Bass, I had to also set the overflow-y. That could actually be done in the CSS

$('#myModal').on('show.bs.modal', function () {
    $('.modal .modal-body').css('overflow-y', 'auto'); 
    $('.modal .modal-body').css('max-height', $(window).height() * 0.7);
});

Domain Account keeping locking out with correct password every few minutes

Finally i found my problem. SQL Reporting Service was causing my account lockout. Stop and try, after confirm no more passwords bad attempts i should reconfigure reporting services service account ---Not at Service Properties, it is in Reporting Service own config--.

How to get a list of user accounts using the command line in MySQL?

I find this format the most useful as it includes the host field which is important in MySQL to distinguish between user records.

select User,Host from mysql.user;

Python memory usage of numpy arrays

In python notebooks I often want to filter out 'dangling' numpy.ndarray's, in particular the ones that are stored in _1, _2, etc that were never really meant to stay alive.

I use this code to get a listing of all of them and their size.

Not sure if locals() or globals() is better here.

import sys
import numpy
from humanize import naturalsize

for size, name in sorted(
    (value.nbytes, name)
    for name, value in locals().items()
    if isinstance(value, numpy.ndarray)):
  print("{:>30}: {:>8}".format(name, naturalsize(size)))

How do I set session timeout of greater than 30 minutes

Setting session timeout through the deployment descriptor should work - it sets the default session timeout for the web app. Calling session.setMaxInactiveInterval() sets the timeout for the particular session it is called on, and overrides the default. Be aware of the unit difference, too - the deployment descriptor version uses minutes, and session.setMaxInactiveInterval() uses seconds.

So

<session-config>
    <session-timeout>60</session-timeout>
</session-config>

sets the default session timeout to 60 minutes.

And

session.setMaxInactiveInterval(600);

sets the session timeout to 600 seconds - 10 minutes - for the specific session it's called on.

This should work in Tomcat or Glassfish or any other Java web server - it's part of the spec.

Set a div width, align div center and text align left

Use auto margins.

div {
   margin-left: auto;
   margin-right: auto;
   width: NNNpx;

   /* NOTE: Only works for non-floated block elements */
   display: block;
   float: none;
}

Further reading at SimpleBits CSS Centering 101

Get the week start date and week end date from week number

This doesn't come from me, but it got the job done regardless:

SELECT DATEADD(wk, -1, DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) --first day previous week
SELECT DATEADD(wk, 0, DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) --first day current week
SELECT DATEADD(wk, 1, DATEADD(DAY, 1-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) --first day next week

SELECT DATEADD(wk, 0, DATEADD(DAY, 0-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) --last day previous week
SELECT DATEADD(wk, 1, DATEADD(DAY, 0-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) --last day current week
SELECT DATEADD(wk, 2, DATEADD(DAY, 0-DATEPART(WEEKDAY, GETDATE()), DATEDIFF(dd, 0, GETDATE()))) --last day next week

I found it here.

glob exclude pattern

You can deduct sets:

set(glob("*")) - set(glob("eph*"))

JavaScript implementation of Gzip

I ported an implementation of LZMA from a GWT module into standalone JavaScript. It's called LZMA-JS.

How to delete shared preferences data from App in Android

In the class definitions:

private static final String PREFERENCES = "shared_prefs";

private static final SharedPreferences sharedPreferences  = getApplicationContext().getSharedPreferences(PREFERENCES, MODE_PRIVATE);

Inside the class:

public static void deleteAllSharedPrefs(){
    sharedPreferences.edit().clear().commit();
}

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

In memory usage and speed.

When you call jsonstr = json.dumps(mydata) it first creates a full copy of your data in memory and only then you file.write(jsonstr) it to disk. So this is a faster method but can be a problem if you have a big piece of data to save.

When you call json.dump(mydata, file) -- without 's', new memory is not used, as the data is dumped by chunks. But the whole process is about 2 times slower.

Source: I checked the source code of json.dump() and json.dumps() and also tested both the variants measuring the time with time.time() and watching the memory usage in htop.

How to set a border for an HTML div tag

In bootstrap 4, you can use border utilities like so.

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>_x000D_
_x000D_
<style>_x000D_
  .border-5 {_x000D_
    border-width: 5px !important;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
<textarea class="border border-dark border-5">some content</textarea>
_x000D_
_x000D_
_x000D_

_DEBUG vs NDEBUG

Visual Studio defines _DEBUG when you specify the /MTd or /MDd option, NDEBUG disables standard-C assertions. Use them when appropriate, ie _DEBUG if you want your debugging code to be consistent with the MS CRT debugging techniques and NDEBUG if you want to be consistent with assert().

If you define your own debugging macros (and you don't hack the compiler or C runtime), avoid starting names with an underscore, as these are reserved.

What does bundle exec rake mean?

When you directly run the rake task or execute any binary file of a gem, there is no guarantee that the command will behave as expected. Because it might happen that you already have the same gem installed on your system which have a version say 1.0 but in your project you have higher version say 2.0. In this case you can not predict which one will be used.

To enforce the desired gem version you take the help of bundle exec command which would execute the binary in context of current bundle. That means when you use bundle exec, bundler checks the gem version configured for the current project and use that to perform the task.

I have also written a post about it which also shows how we can avoid using it using bin stubs.

PHP Echo text Color

How about writing out some HTML tags and some CSS if you're outputting this to the browser?

echo '<span style="color:#AFA;text-align:center;">Request has been sent. Please wait for my reply!</span>';

Won't work from console though, only through browser.

How to include files outside of Docker's build context?

I spent a good time trying to figure out a good pattern and how to better explain what's going on with this feature support. I realized that the best way to explain it was as follows...

  • Dockerfile: Will only see files under its own relative path
  • Context: a place in "space" where the files you want to share and your Dockerfile will be copied to

So, with that said, here's an example of the Dockerfile that needs to reuse a file called start.sh

Dockerfile

It will always load from its relative path, having the current directory of itself as the local reference to the paths you specify.

COPY start.sh /runtime/start.sh

Files

Considering this idea, we can think of having multiple copies for the Dockerfiles building specific things, but they all need access to the start.sh.

./all-services/
   /start.sh
   /service-X/Dockerfile
   /service-Y/Dockerfile
   /service-Z/Dockerfile
./docker-compose.yaml

Considering this structure and the files above, here's a docker-compose.yml

docker-compose.yaml

  • In this example, your shared context directory is the runtime directory.
    • Same mental model here, think that all the files under this directory are moved over to the so-called context.
    • Similarly, just specify the Dockerfile that you want to copy to that same directory. You can specify that using dockerfile.
  • The directory where your main content is located is the actual context to be set.

The docker-compose.yml is as follows

version: "3.3"
services:
  
  service-A
    build:
      context: ./all-service
      dockerfile: ./service-A/Dockerfile

  service-B
    build:
      context: ./all-service
      dockerfile: ./service-B/Dockerfile

  service-C
    build:
      context: ./all-service
      dockerfile: ./service-C/Dockerfile
  • all-service is set as the context, the shared file start.sh is copied there as well the Dockerfile specified by each dockerfile.
  • Each gets to be built their own way, sharing the start file!

SQL server ignore case in a where expression

I found another solution elsewhere; that is, to use

upper(@yourString)

but everyone here is saying that, in SQL Server, it doesn't matter because it's ignoring case anyway? I'm pretty sure our database is case-sensitive.

Accessing items in an collections.OrderedDict by index

It is dramatically more efficient to use IndexedOrderedDict from the indexed package.

Following Niklas's comment, I have done a benchmark on OrderedDict and IndexedOrderedDict with 1000 entries.

In [1]: from numpy import *
In [2]: from indexed import IndexedOrderedDict
In [3]: id=IndexedOrderedDict(zip(arange(1000),random.random(1000)))
In [4]: timeit id.keys()[56]
1000000 loops, best of 3: 969 ns per loop

In [8]: from collections import OrderedDict
In [9]: od=OrderedDict(zip(arange(1000),random.random(1000)))
In [10]: timeit od.keys()[56]
10000 loops, best of 3: 104 µs per loop

IndexedOrderedDict is ~100 times faster in indexing elements at specific position in this specific case.

What is the difference between onBlur and onChange attribute in HTML?

onblur fires when a field loses focus, while onchange fires when that field's value changes. These events will not always occur in the same order, however.

In Firefox, tabbing out of a changed field will fire onchange then onblur, and it will normally do the same in IE. However, if you press the enter key instead of tab, in Firefox it will fire onblur then onchange, while IE will usually fire in the original order. However, I've seen cases where IE will also fire blur first, so be careful. You can't assume that either the onblur or the onchange will happen before the other one.

Parse (split) a string in C++ using string delimiter (standard C++)

Since this is the top-rated Stack Overflow Google search result for C++ split string or similar, I'll post a complete, copy/paste runnable example that shows both methods.

splitString uses stringstream (probably the better and easier option in most cases)

splitString2 uses find and substr (a more manual approach)

// SplitString.cpp

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

// function prototypes
std::vector<std::string> splitString(const std::string& str, char delim);
std::vector<std::string> splitString2(const std::string& str, char delim);
std::string getSubstring(const std::string& str, int leftIdx, int rightIdx);


int main(void)
{
  // Test cases - all will pass
  
  std::string str = "ab,cd,ef";
  //std::string str = "abcdef";
  //std::string str = "";
  //std::string str = ",cd,ef";
  //std::string str = "ab,cd,";   // behavior of splitString and splitString2 is different for this final case only, if this case matters to you choose which one you need as applicable
  
  
  std::vector<std::string> tokens = splitString(str, ',');
  
  std::cout << "tokens: " << "\n";
  
  if (tokens.empty())
  {
    std::cout << "(tokens is empty)" << "\n";
  }
  else
  {
    for (auto& token : tokens)
    {
      if (token == "") std::cout << "(empty string)" << "\n";
      else std::cout << token << "\n";
    }
  }
    
  return 0;
}

std::vector<std::string> splitString(const std::string& str, char delim)
{
  std::vector<std::string> tokens;
  
  if (str == "") return tokens;
  
  std::string currentToken;
  
  std::stringstream ss(str);
  
  while (std::getline(ss, currentToken, delim))
  {
    tokens.push_back(currentToken);
  }
  
  return tokens;
}

std::vector<std::string> splitString2(const std::string& str, char delim)
{
  std::vector<std::string> tokens;
  
  if (str == "") return tokens;
  
  int leftIdx = 0;
  
  int delimIdx = str.find(delim);
  
  int rightIdx;
  
  while (delimIdx != std::string::npos)
  {
    rightIdx = delimIdx - 1;
    
    std::string token = getSubstring(str, leftIdx, rightIdx);
    tokens.push_back(token);
    
    // prep for next time around
    leftIdx = delimIdx + 1;
    
    delimIdx = str.find(delim, delimIdx + 1);
  }
  
  rightIdx = str.size() - 1;
  
  std::string token = getSubstring(str, leftIdx, rightIdx);
  tokens.push_back(token);
  
  return tokens;
}

std::string getSubstring(const std::string& str, int leftIdx, int rightIdx)
{
  return str.substr(leftIdx, rightIdx - leftIdx + 1);
}

AngularJS open modal on button click

Set Jquery in scope

$scope.$ = $;

and call in html

ng-click="$('#novoModelo').modal('show')"

python xlrd unsupported format, or corrupt file.

You say:

The file doesn't seem to be corrupted or of a different format.

However as the error message says, the first 8 bytes of the file are '<table r' ... that is definitely not Excel .xls format. Open it with a text editor (e.g. Notepad) that won't take any notice of the (incorrect) .xls extension and see for yourself.

git remote add with other SSH port

Best answer doesn't work for me. I needed ssh:// from the beggining.

# does not work
git remote set-url origin [email protected]:10000/aaa/bbbb/ccc.git
# work
git remote set-url origin ssh://[email protected]:10000/aaa/bbbb/ccc.git

How to determine if a string is a number with C++?

A solution based on a comment by kbjorklu is:

bool isNumber(const std::string& s)
{
   return !s.empty() && s.find_first_not_of("-.0123456789") == std::string::npos;
}

As with David Rector's answer it is not robust to strings with multiple dots or minus signs, but you can remove those characters to just check for integers.


However, I am partial to a solution, based on Ben Voigt's solution, using strtod in cstdlib to look decimal values, scientific/engineering notation, hexidecimal notation (C++11), or even INF/INFINITY/NAN (C++11) is:

bool isNumberC(const std::string& s)
{
    char* p;
    strtod(s.c_str(), &p);
    return *p == 0;
}

Insert image after each list item

The easier way to do it is just:

ul li:after {
    content: url('../images/small_triangle.png');
}

What is a 'workspace' in Visual Studio Code?

I just installed Visual Studio Code v1.25.1. on a Windows 7 Professional SP1 machine. I wanted to understand workspaces in detail, so I spent a few hours figuring out how they work in this version of Visual Studio Code. I thought the results of my research might be of interest to the community.

First, workspaces are referred to by Microsoft in the Visual Studio Code documentation as "multi-root workspaces." In plain English that means "a multi-folder (A.K.A "root") work environment." A Visual Studio Code workspace is simply a collection of folders - any collection you desire, in any order you wish. The typical collection of folders constitutes a software development project. However, a folder collection could be used for anything else for which software code is being developed.

The mechanics behind how Visual Studio Code handles workspaces is a bit complicated. I think the quickest way to convey what I learned is by giving you a set of instructions that you can use to see how workspaces work on your computer. I am assuming that you are starting with a fresh install of Visual Studio Code v1.25.1. If you are using a production version of Visual Studio Code I don't recommend that you follow my instructions because you may lose some or all of your existing Visual Studio Code configuration! If you already have a test version of Visual Studio Code v1.25.1 installed, **and you are willing to lose any configuration that already exists, the following must be done to revert your Visual Studio Code to a fresh installation state:

Delete the following folder (if it exists):

  C:\Users\%username%\AppData\Roaming\Code\Workspaces (where "%username%" is the name of the currently logged-on user)

You will be adding folders to Visual Studio Code to create a new workspace. If any of the folders you intend to use to create this new workspace have previously been used with Visual Studio Code, please delete the ".vscode" subfolder (if it exists) within each of the folders that will be used to create the new workspace.

Launch Visual Studio Code. If the Welcome page is displayed, close it. Do the same for the Panel (a horizontal pane) if it is displayed. If you received a message that Git isn't installed click "Remind me later." If displayed, also close the "Untitled" code page that was launched as the default code page. If the Explorer pane is not displayed click "View" on the main menu then click "Explorer" to display the Explorer pane. Inside the Explorer pane you should see three (3) View headers - Open Editors, No Folder Opened, and Outline (located at the very bottom of the Explorer pane). Make sure that, at a minimum, the open editors and no folder opened view headers are displayed.

Visual Studio Code displays a button that reads "Open Folder." Click this button and select a folder of your choice. Visual Studio Code will refresh and the name of your selected folder will have replaced the "No Folder Opened" View name. Any folders and files that exist within your selected folder will be displayed beneath the View name.

Now open the Visual Studio Code Preferences Settings file. There are many ways to do this. I'll use the easiest to remember which is menu FilePreferencesSettings. The Settings file is displayed in two columns. The left column is a read-only listing of the default values for every Visual Studio Code feature. The right column is used to list the three (3) types of user settings. At this point in your test only two user settings will be listed - User Settings and Workspace Settings. The User Settings is displayed by default. This displays the contents of your User Settings .json file. To find out where this file is located, simply hover your mouse over the "User Settings" listing that appears under the OPEN EDITORS View in Explorer. This listing in the OPEN EDITORS View is automatically selected when the "User Settings" option in the right column is selected. The path should be:

C:\Users\%username%\AppData\Roaming\Code\User\settings.json

This settings.json file is where the User Settings for Visual Studio Code are stored.

Now click the Workspace Settings option in the right column of the Preferences listing. When you do this, a subfolder named ".vscode" is automatically created in the folder you added to Explore a few steps ago. Look at the listing of your folder in Explorer to confirm that the .vscode subfolder has been added. Inside the new .vscode subfolder is another settings.json file. This file contains the workspace settings for the folder you added to Explorer a few steps ago.

At this point you have a single folder whose User Settings are stored at:

C:\Users\%username%\AppData\Roaming\Code\User\settings.json

and whose Workspace Settings are stored at:

C:\TheLocationOfYourFolder\settings.json

This is the configuration when a single folder is added to a new installation of Visual Studio Code. Things get messy when we add a second (or greater) folder. That's because we are changing Visual Studio Code's User Settings and Workspace Settings to accommodate multiple folders. In a single-folder environment only two settings.json files are needed as listed above. But in a multi-folder environment a .vscode subfolder is created in each folder added to Explorer and a new file, "workspaces.json," is created to manage the multi-folder environment. The new "workspaces.json" file is created at:

c:\Users\%username%\AppData\Roaming\Code\Workspaces\%workspace_id%\workspaces.json

The "%workspaces_id%" is a folder with a unique all-number name.

In the Preferences right column there now appears three user setting options - User Settings, Workspace Settings, and Folder Settings. The function of User Settings remains the same as for a single-folder environment. However, the settings file behind the Workspace Settings has been changed from the settings.json file in the single folder's .vscode subfolder to the workspaces.json file located at the workspaces.json file path shown above. The settings.json file located in each folder's .vscode subfolder is now controlled by a third user setting, Folder Options. This is a drop-down selection list that allows for the management of each folder's settings.json file located in each folder's .vscode subfolder. Please note: the .vscode subfolder will not be created in newly-added explorer folders until the newly-added folder has been selected at least once in the folder options user setting.

Notice that the Explorer single folder name has bee changed to "UNTITLED (WORKSPACE)." This indicates the following:

  1. A multi-folder workspace has been created with the name "UNTITLED (WORKSPACE)
  2. The workspace is named "UNTITLED (WORKSPACE)" to communicate that the workspace has not yet been saved as a separate, unique, workspace file
  3. The UNTITLED (WORKSPACE) workspace can have folders added to it and removed from it but it will function as the ONLY workspace environment for Visual Studio Code

The full functionality of Visual Studio Code workspaces is only realized when a workspace is saved as a file that can be reloaded as needed. This provides the capability to create unique multi-folder workspaces (e.g., projects) and save them as files for later use! To do this select menu FileSave Workspace As from the main menu and save the current workspace configuration as a unique workspace file. If you need to create a workspace "from scratch," first save your current workspace configuration (if needed) then right-click each Explorer folder name and click "Remove Folder from Workspace." When all folders have been removed from the workspace, add the folders you require for your new workspace. When you finish adding new folders, simply save the new workspace as a new workspace file.

An important note - Visual Studio Code doesn't "revert" to single-folder mode when only one folder remains in Explorer or when all folders have been removed from Explorer when creating a new workspace "from scratch." The multi-folder workspace configuration that utilizes three user preferences remains in effect. This means that unless you follow the instructions at the beginning of this post, Visual Studio Code can never be returned to a single-folder mode of operation - it will always remain in multi-folder workspace mode.

bootstrap popover not showing on top of all elements

Just using

$().popover({container: 'body'})

could be not enough when displaying popover over a BootstrapDialog modal, which also uses body as container and has a higher z-index.

I come with this fix which uses internals of Bootstrap3 (may not work with 2.x / 4.x) but most of modern Bootstrap installations are 3.x.

self.$anchor.on('shown.bs.popover', function(ev) {
    var tipCSS = self.$anchor.data('tipCSS');
    if (tipCSS !== undefined) {
        self.$anchor.data('bs.popover').$tip.css(tipCSS);
    }
    // ...
});

Such way different popovers may have different z-index, some are under BootstrapDialog modal, while another ones are over it.

Check if input value is empty and display an alert

Better one is here.

$('#submit').click(function()
{
    if( !$('#myMessage').val() ) {
       alert('warning');
    }
});

And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:

$('#submit').on('click',function()
{
    if( $('#myMessage').val().length === 0 ) {
        alert('warning');
    }
});

If you're sure it will always operate on a textfield element then you can just use this.value.

$('#submit').click(function()
{
      if( !document.getElementById('myMessage').value ) {
          alert('warning');
      }
});

Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).

java.lang.IllegalArgumentException: View not attached to window manager

alex,

I could be wrong here, but I suspect that multiple phones 'in the wild' have a bug that causes them to switch orientation on applications that are marked as statically oriented. This happens quite a bit on my personal phone, and on many of the test phones our group uses (including droid, n1, g1, hero). Typically an app marked as statically oriented (perhaps vertically) will lay itself out for a second or two using a horizontal orientation, and then immediately switch back. End result is that even though you don't want your app to switch orientation, you have to be prepared that it may. I don't know under what exact conditions this behavior can be reproduced, I don't know if it is specific to a version of Android. All I know is that I have seen it happen plenty of times :(

I would recommend using the solution provided in the link you posted that suggests overriding the Activity onCreateDialog method and letting the Android OS manage the lifecycle of your Dialogs. It looks to me like even though you don't want your activity to switch orientations, it is switching orientation somewhere. You can try to track down a method that will always prevent orientation switching, but I am trying to tell you that I personally don't believe there is a foolproof way that works on all current Android phones in the market.

Spring Boot @Value Properties

I had the same problem like you. Here's my error code.

@Component
public class GetExprsAndEnvId {
    @Value("hello")
    private String Mysecret;


    public GetExprsAndEnvId() {
        System.out.println("construct");
    }


    public void print(){
        System.out.println(this.Mysecret);
    }


    public String getMysecret() {
        return Mysecret;
    }

    public void setMysecret(String mysecret) {
        Mysecret = mysecret;
    }
}

This is no problem like this, but we need to use it like this:

@Autowired
private GetExprsAndEnvId getExprsAndEnvId;

not like this:

getExprsAndEnvId = new GetExprsAndEnvId();

Here, the field annotated with @Value is null because Spring doesn't know about the copy of GetExprsAndEnvId that is created with new and didn't know to how to inject values in it.

The type or namespace name 'Objects' does not exist in the namespace 'System.Data'

You need to add a reference to the .NET assembly System.Data.Entity.dll.

Prevent scroll-bar from adding-up to the Width of page on Chrome

EDIT: this answer isn't quite right at the moment, refer to my other answer to see what I was attempting to do here. I'm trying to fix it up, but if you can offer assistance do so in the comments, thanks!

Using padding-right will mitigate the sudden appearance of a scrollbar

EXAMPLE

chrome devtools showing padding unmoved

As you can see from the dots, the text makes it to the same point in the page before wrapping, regardless of whether or not a scrollbar is present.
This is because when a scrollbar is introduced the padding hides behind it, so the scrollbar doesn't push on the text!

How to define the css :hover state in a jQuery selector?

It's too late, however the best example, how to add pseudo element in jQuery style

_x000D_
_x000D_
 $(document).ready(function(){_x000D_
 $("a.dummy").css({"background":"#003d79","color":"#fff","padding": "5px 10px","border-radius": "3px","text-decoration":"none"});_x000D_
 $("a.dummy").hover(function() {_x000D_
            $(this).css("background-color","#0670c9")_x000D_
          }).mouseout(function(){_x000D_
              $(this).css({"background-color":"#003d79",});_x000D_
          });_x000D_
 _x000D_
 });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>_x000D_
<a class="dummy" href="javascript:void()">Just Link</a>
_x000D_
_x000D_
_x000D_

How to convert Strings to and from UTF8 byte arrays in Java

As an alternative, StringUtils from Apache Commons can be used.

 byte[] bytes = {(byte) 1};
 String convertedString = StringUtils.newStringUtf8(bytes);

or

 String myString = "example";
 byte[] convertedBytes = StringUtils.getBytesUtf8(myString);

If you have non-standard charset, you can use getBytesUnchecked() or newString() accordingly.

bootstrap initially collapsed element

When you expand or collapse accordion it just adds/removes a class "in" and sets the height:auto or 0 to the accordion div.

Demo

So in your accordion when you define it just remove "in" class from the div as below. Whenever you expand an accorion it just adds the "in" class to make it visible.

If you render the page with "in" bootstrap looks for the class and it will make the div's height:auto, if it not present it will be at zero height.

<div id="collapseOne" class="accordion-body collapse">

Cloning an Object in Node.js

Another solution is to encapsulate directly in the new variable using: obj1= {...obj2}

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

i had similar problem. i solved it by trim. Please check, path.resolve may add additional space to end of path.

var path = require('path');
const envPath = path.resolve(process.cwd()+'/config','.env.'+process.env.NODE_ENV).trim()
require('dotenv').config({ path: envPath })

my package script is like this to use multiple .env:

 "scripts": {
    "start": "set NODE_ENV=development && nodemon ./bin/www",
    "prod": "set NODE_ENV=production && node ./bin/www"
  },

Expression must have class type

a is a pointer. You need to use->, not .

Filter Excel pivot table using VBA

Configure the pivot table so that it is like this:

enter image description here

Your code can simply work on range("B1") now and the pivot table will be filtered to you required SavedFamilyCode

Sub FilterPivotTable()
Application.ScreenUpdating = False
    ActiveSheet.Range("B1") = "K123224"
Application.ScreenUpdating = True
End Sub