Programs & Examples On #Zend server installation

How to get the nth element of a python list or a default if not available

Combining @Joachim's with the above, you could use

next(iter(my_list[index:index+1]), default)

Examples:

next(iter(range(10)[8:9]), 11)
8
>>> next(iter(range(10)[12:13]), 11)
11

Or, maybe more clear, but without the len

my_list[index] if my_list[index:index + 1] else default

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

There are only 3 joins:

  • A) Cross Join = Cartesian (E.g: Table A, Table B)
  • B) Inner Join = JOIN (E.g: Table A Join/Inner Join Table B)
  • C) Outer join:

       There are three type of outer join
       1)  Left Outer Join     = Left Join
       2)  Right Outer Join    = Right Join
       3)  Full Outer Join     = Full Join    
    

Hope it'd help.

SQLException: No suitable driver found for jdbc:derby://localhost:1527

If your using embedded Derby you need Derby.jar in your classpath.

Oracle client ORA-12541: TNS:no listener

Check out your TNS Names, this must not have spaces at the left side of the ALIAS

Best regards

Most Useful Attributes

[EditorBrowsable(EditorBrowsableState.Never)] allows you to hide properties and methods from IntelliSense if the project is not in your solution. Very helpful for hiding invalid flows for fluent interfaces. How often do you want to GetHashCode() or Equals()?

For MVC [ActionName("Name")] allows you to have a Get action and Post action with the same method signature, or to use dashes in the action name, which otherwise would not be possible without creating a route for it.

Difference between string object and string literal

"abc" is a literal String.

In Java, these literal strings are pooled internally and the same String instance of "abc" is used where ever you have that string literal declared in your code. So "abc" == "abc" will always be true as they are both the same String instance.

Using the String.intern() method you can add any string you like to the internally pooled strings, these will be kept in memory until java exits.

On the other hand, using new String("abc") will create a new string object in memory, which is logically the same as the "abc" literal. "abc" == new String("abc") will always be false, as although they are logically equal they refer to different instances.

Wrapping a String constructor around a string literal is of no value, it just needlessly uses more memory than it needs to.

Why do I keep getting 'SVN: Working Copy XXXX locked; try performing 'cleanup'?

After more exploration and testing, it appears that this issue was being caused by debugging the plugin and using breakpoints. SVN/Subclipse apparently didn't like having breakpoints midway through their execution and as a result this lock files were being created. As soon as I started just running the plugin, this issue disappeared.

How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?

As Jake points out, TARGET_IPHONE_SIMULATOR is a subset of TARGET_OS_IPHONE.

Also, TARGET_OS_IPHONE is a subset of TARGET_OS_MAC.

So a better approach might be:

#ifdef _WIN64
   //define something for Windows (64-bit)
#elif _WIN32
   //define something for Windows (32-bit)
#elif __APPLE__
    #include "TargetConditionals.h"
    #if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
        // define something for simulator   
    #elif TARGET_OS_IPHONE
        // define something for iphone  
    #else
        #define TARGET_OS_OSX 1
        // define something for OSX
    #endif
#elif __linux
    // linux
#elif __unix // all unices not caught above
    // Unix
#elif __posix
    // POSIX
#endif

Ascii/Hex convert in bash

jcomeau@aspire:~$ echo -n The quick brown fox jumps over the lazy dog | python -c "print raw_input().encode('hex'),"
54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f67
jcomeau@aspire:~$ echo -n The quick brown fox jumps over the lazy dog | python -c "print raw_input().encode('hex')," | python -c "print raw_input().decode('hex'),"
The quick brown fox jumps over the lazy dog

it could be done with Python3 as well, but differently, and I'm a lazy dog.

Push commits to another branch

_x000D_
_x000D_
git init _x000D_
#git remote remove origin_x000D_
git remote add origin  <http://...git>_x000D_
echo "This is for demo" >> README.md _x000D_
git add README.md_x000D_
git commit -m "Initail Commit" _x000D_
git checkout -b branch1 _x000D_
git branch --list_x000D_
****add files***_x000D_
git add -A_x000D_
git status_x000D_
git commit -m "Initial - branch1"_x000D_
git push --set-upstream origin branch1_x000D_
#git push origin --delete  branch1_x000D_
#git branch --unset-upstream  
_x000D_
_x000D_
_x000D_

How can I listen for keypress event on the whole page?

Be aware "document:keypress" is deprecated. We should use document:keydown instead.

Link: https://developer.mozilla.org/fr/docs/Web/API/Document/keypress_event

Java 8 Stream and operation on arrays

Be careful if you have to deal with large numbers.

int[] arr = new int[]{Integer.MIN_VALUE, Integer.MIN_VALUE};
long sum = Arrays.stream(arr).sum(); // Wrong: sum == 0

The sum above is not 2 * Integer.MIN_VALUE. You need to do this in this case.

long sum = Arrays.stream(arr).mapToLong(Long::valueOf).sum(); // Correct

How to set the JSTL variable value in javascript?

Just don't. Don't write code with code. Write a JSON object or a var somewhere but for the love of a sensible HTTP divide, don't write JavaScript functions or methods hardcoded with vars/properties provided by JSTL. Generating JSON is cool. It ends there or your UI dev hates you.

Imagine if you had to dig into JavaScript to find something that was setting parameters in the middle of a class that originated on the client-side. It's awful. Pass data back and forth. Handle the data. But don't try to generate actual code.

How to modify memory contents using GDB?

As Nikolai has said you can use the gdb 'set' command to change the value of a variable.

You can also use the 'set' command to change memory locations. eg. Expanding on Nikolai's example:

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

(gdb) p &i
$2 = (int *) 0xbfbb0000
(gdb) set *((int *) 0xbfbb0000) = 20
(gdb) p i
$3 = 20

This should work for any valid pointer, and can be cast to any appropriate data type.

MySql Inner Join with WHERE clause


1. Change the INNER JOIN before the WHERE clause.
2. You have two WHEREs which is not allowed.

Try this:

SELECT table1.f_id FROM table1
  INNER JOIN table2 
     ON (table2.f_id = table1.f_id AND table2.f_type = 'InProcess') 
   WHERE table1.f_com_id = '430' AND table1.f_status = 'Submitted'

jQuery Scroll to Div

Could just use JQuery position function to get coordinates of your div, then use javascript scroll:

var position = $("div").position();
scroll(0,position.top);

onMeasure custom view explanation

onMeasure() is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in a match_parent situation than a wrap_content situation). These constraints are packaged up into the MeasureSpec values that are passed into the method. Here is a rough correlation of the mode values:

  • EXACTLY means the layout_width or layout_height value was set to a specific value. You should probably make your view this size. This can also get triggered when match_parent is used, to set the size exactly to the parent view (this is layout dependent in the framework).
  • AT_MOST typically means the layout_width or layout_height value was set to match_parent or wrap_content where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.
  • UNSPECIFIED typically means the layout_width or layout_height value was set to wrap_content with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.

The contract that exists with onMeasure() is that setMeasuredDimension() MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found in View, which is why it is safe to call super instead if that fits your use case.

Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with wrap_content in both directions, your view may not show up at all because the framework doesn't know how large it is!

Generally, if you are overriding View and not another existing widget, it is probably a good idea to provide an implementation, even if it is as simple as something like this:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int desiredWidth = 100;
    int desiredHeight = 100;

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int width;
    int height;

    //Measure Width
    if (widthMode == MeasureSpec.EXACTLY) {
        //Must be this size
        width = widthSize;
    } else if (widthMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        width = Math.min(desiredWidth, widthSize);
    } else {
        //Be whatever you want
        width = desiredWidth;
    }

    //Measure Height
    if (heightMode == MeasureSpec.EXACTLY) {
        //Must be this size
        height = heightSize;
    } else if (heightMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        height = Math.min(desiredHeight, heightSize);
    } else {
        //Be whatever you want
        height = desiredHeight;
    }

    //MUST CALL THIS
    setMeasuredDimension(width, height);
}

Hope that Helps.

Can I use VARCHAR as the PRIMARY KEY?

A blanket "no you shouldn't" is terrible advice. This is perfectly reasonable in many situations depending on your use case, workload, data entropy, hardware, etc.. What you shouldn't do is make assumptions.

It should be noted that you can specify a prefix which will limit MySQL's indexing, thereby giving you some help in narrowing down the results before scanning the rest. This may, however, become less useful over time as your prefix "fills up" and becomes less unique.

It's very simple to do, e.g.:

CREATE TABLE IF NOT EXISTS `foo` (
  `id` varchar(128),
  PRIMARY KEY (`id`(4))
)

Also note that the prefix (4) appears after the column quotes. Where the 4 means that it should use the first 4 characters of the 128 possible characters that can exist as the id.

Lastly, you should read how index prefixes work and their limitations before using them: https://dev.mysql.com/doc/refman/8.0/en/create-index.html

How to convert jsonString to JSONObject in Java

String to JSON using Jackson with com.fasterxml.jackson.databind:

Assuming your json-string represents as this: jsonString = {"phonetype":"N95","cat":"WP"}

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
 * Simple code exmpl
 */
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(jsonString);
String phoneType = node.get("phonetype").asText();
String cat = node.get("cat").asText();

Angular 4 default radio button checked by default

getting following error

_x000D_
_x000D_
It happens:  Error: 
      ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
      formGroup's partner directive "formControlName" instead.  Example:
_x000D_
_x000D_
_x000D_

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

No command ā€“ neither typenor echoā€“ is necessary to emulate Unix's/Mac OS X's 'touch' command in a Windows Powershell terminal. Simply use the following shorthand:

$null > filename

This will create an empty file named 'filename' at your current location. Use any filename extension that you might need, e.g. '.txt'.

Source: https://superuser.com/questions/502374/equivalent-of-linux-touch-to-create-an-empty-file-with-powershell (see comments)

Error occurred during initialization of VM (java/lang/NoClassDefFoundError: java/lang/Object)

please try to execute java from

C:\Program Files\Java\jdk1.7.0_10\bin

i.e from the location where java is installed.

If it is successful, it means that the error lies somewhere in the classpath.

Also, this guy seems to have had the same problem as yours, check it out

Get Selected value from dropdown using JavaScript

Working jsbin: http://jsbin.com/ANAYeDU/4/edit

Main bit:

function answers()
{

var element = document.getElementById("mySelect");
var elementValue = element.value;

if(elementValue == "To measure time"){
  alert("Thats correct"); 
  }
}

Android java.lang.NoClassDefFoundError

I've run into this problem a few times opening old projects that include other Android libraries. What works for me is to:

move Android to the top in the Order and Export tab and deselecting it.

Yes, this really makes the difference. Maybe it's time for me to ditch ADT for Android Studio!

How to reload page every 5 seconds?

_x000D_
_x000D_
function reload() {_x000D_
  document.location.reload();_x000D_
}_x000D_
_x000D_
setTimeout(reload, 5000);
_x000D_
_x000D_
_x000D_

How to delete/unset the properties of a javascript object?

To blank it:

myObject["myVar"]=null;

To remove it:

delete myObject["myVar"]

as you can see in duplicate answers

What is difference between XML Schema and DTD?

DTD indicates the syntax of the XML element

XML Schemas are Microsoft's alternative to DTD for validating XML

How to have the formatter wrap code with IntelliJ?

IntelliJ IDEA 14, 15, 2016 & 2017

Format existing code

  1. Ensure right margin is not exceeded

    File > Settings > Editor > Code Style > Java > Wrapping and Braces > Ensure right margin is not exceeded

    File Settings Ensure right margin

  2. Reformat code

    Code > Reformat code...

    Reformat code

    or press Ctrl + Alt + L

    warning If you have something like this:

    thisLineIsVeryLongAndWillBeChanged();   // comment
    

    it will be converted to

    thisLineIsVeryLongAndWillBeChanged();   
    // comment  
    

    instead of

    // comment  
    thisLineIsVeryLongAndWillBeChanged();   
    

    This is why I select pieces of code before reformatting if the code looks like in the previous example.

Wrap when typing reaches right margin

  • IntelliJ IDEA 14: File > Settings > Editor > Code Style > Wrap when typing reaches right margin

    Wrap when typing

  • IntelliJ IDEA 15, 2016 & 2017: File > Settings > Editor > Code Style > Wrap on typing

    Wrap on typing

Why can't I see the "Report Data" window when creating reports?

I was also same problem in Visual Studio 2013, Then Suddenly got an Idea.. Click on Report to make focus on it. Simple Press Alt+Ctrl+D

Split string into strings by length?

And for dudes who prefer it to be a bit more readable:

def itersplit_into_x_chunks(string,x=10): # we assume here that x is an int and > 0
    size = len(string)
    chunksize = size//x
    for pos in range(0, size, chunksize):
        yield string[pos:pos+chunksize]

output:

>>> list(itersplit_into_x_chunks('qwertyui',x=4))
['qw', 'er', 'ty', 'ui']

How do I get the last day of a month?

To get last day of a month in a specific calendar - and in an extension method -:

public static int DaysInMonthBy(this DateTime src, Calendar calendar)
{
    var year = calendar.GetYear(src);                   // year of src in your calendar
    var month = calendar.GetMonth(src);                 // month of src in your calendar
    var lastDay = calendar.GetDaysInMonth(year, month); // days in month means last day of that month in your calendar
    return lastDay;
}

How to delete a record by id in Flask-SQLAlchemy

You can do this,

User.query.filter_by(id=123).delete()

or

User.query.filter(User.id == 123).delete()

Make sure to commit for delete() to take effect.

Define global variable with webpack

I was about to ask the very same question. After searching a bit further and decyphering part of webpack's documentation I think that what you want is the output.library and output.libraryTarget in the webpack.config.js file.

For example:

js/index.js:

var foo = 3;
var bar = true;

webpack.config.js

module.exports = {
   ...
   entry: './js/index.js',
   output: {
      path: './www/js/',
      filename: 'index.js',
      library: 'myLibrary',
      libraryTarget: 'var'
   ...
}

Now if you link the generated www/js/index.js file in a html script tag you can access to myLibrary.foo from anywhere in your other scripts.

C# difference between == and Equals()

== Operator

  1. If operands are Value Types and their values are equal, it returns true else false.
  2. If operands are Reference Types with exception of string and both refer to the same instance (same object), it returns true else false.
  3. If operands are string type and their values are equal, it returns true else false.

.Equals

  1. If operands are Reference Types, it performs Reference Equality that is if both refer to the same instance (same object), it returns true else false.
  2. If Operands are Value Types then unlike == operator it checks for their type first and if their types are same it performs == operator else it returns false.

Access Https Rest Service using Spring RestTemplate

You need to configure a raw HttpClient with SSL support, something like this:

@Test
public void givenAcceptingAllCertificatesUsing4_4_whenUsingRestTemplate_thenCorrect() 
throws ClientProtocolException, IOException {
    CloseableHttpClient httpClient
      = HttpClients.custom()
        .setSSLHostnameVerifier(new NoopHostnameVerifier())
        .build();
    HttpComponentsClientHttpRequestFactory requestFactory 
      = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    ResponseEntity<String> response 
      = new RestTemplate(requestFactory).exchange(
      urlOverHttps, HttpMethod.GET, null, String.class);
    assertThat(response.getStatusCode().value(), equalTo(200));
}

font: Baeldung

jquery animate background position

jQuery's animate function is not exclusively usable for directly animating properties of DOM-objects. You can also tween variables and use the step function to get the variables for every step of the tween.

For example, to animate a background-position from background-position(0px 0px) to background-position(100px 500px) you can do this:

$({temporary_x: 0, temporary_y: 0}).animate({temporary_x: 100, temporary_y: 500}, {
    duration: 1000,
    step: function() {
        var position = Math.round(this.temporary_x) + "px " + Math.round(this.temporary_y) + "px";
        $("#your_div").css("background-position",  position);
    }
});

Just make sure to not forget the this. inside the step function.

How to subtract 30 days from the current date using SQL Server

SELECT DATEADD(day,-30,date) AS before30d 
FROM...

But it is strongly recommended to keep date in datetime column, not varchar.

How to tell if string starts with a number with Python?

This piece of code:

for s in ("fukushima", "123 is a number", ""):
    print s.ljust(20),  s[0].isdigit() if s else False

prints out the following:

fukushima            False
123 is a number      True
                     False

How do I write to a Python subprocess' stdin?

You can provide a file-like object to the stdin argument of subprocess.call().

The documentation for the Popen object applies here.

To capture the output, you should instead use subprocess.check_output(), which takes similar arguments. From the documentation:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

What's the difference between OpenID and OAuth?

OAuth 2.0 is a Security protocol. It is NEITHER an Authentication NOR an Authorization protocol.

Authentication by definition the answers two questions.

  1. Who is the user?
  2. Is the user currently present on the system?

OAuth 2.0 has the following grant types

  • client_credentials: When one app needs to interact with another app and modify the data of multiple users.
  • authorization_code: User delegates the Authorization server to issue an access_token that the client can use to access protected resource
  • refresh_token: When the access_token expires, the refresh token can be leveraged to get a fresh access_token
  • password: User provides their login credentials to a client that calls the Authorization server and receives an access_token

All 4 have one thing in common, access_token, an artifact that can be used to access protected resource.

The access_token does not provide the answer to the 2 questions that an "Authentication" protocol must answer.

An example to explain Oauth 2.0 (credits: OAuth 2 in Action, Manning publications)

Let's talk about chocolate. We can make many confections out of chocolate including, fudge, ice cream, and cake. But, none of these can be equated to chocolate because multiple other ingredients such as cream and bread are needed to make the confection, even though chocolate sounds like the main ingredient. Similarly, OAuth 2.0 is the chocolate, and cookies, TLS infrastucture, Identity Providers are other ingredients that are required to provide the "Authentication" functionality.

If you want Authentication, you may go for OpenID Connect, which provides an "id_token", apart from an access_token, that answers the questions that every authentication protocol must answer.

ng: command not found while creating new project using angular-cli

Repairing NodeJS installation on windows resolved it for me.

Retrieving an element from array list in Android?

I have a list of positions of array to retrieve ,This worked for me.

  public void create_list_to_add_group(ArrayList<Integer> arrayList_loc) {
     //In my case arraylist_loc is the list of positions to retrive from 
    // contact_names 
    //arraylist and phone_number arraylist

    ArrayList<String> group_members_list = new ArrayList<>();
    ArrayList<String> group_members_phone_list = new ArrayList<>();

    int size = arrayList_loc.size();

    for (int i = 0; i < size; i++) {

        try {

            int loc = arrayList_loc.get(i);
            group_members_list.add(contact_names_list.get(loc));
            group_members_phone_list.add(phone_num_list.get(loc));


        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    Log.e("Group memnbers list", " " + group_members_list);
    Log.e("Group memnbers num list", " " + group_members_phone_list);

}

Style input type file?

use uniform js plugin to style input of any type, select, textarea.

The URL is http://uniformjs.com/

Python Inverse of a Matrix

You should have a look at numpy if you do matrix manipulation. This is a module mainly written in C, which will be much faster than programming in pure python. Here is an example of how to invert a matrix, and do other matrix manipulation.

from numpy import matrix
from numpy import linalg
A = matrix( [[1,2,3],[11,12,13],[21,22,23]]) # Creates a matrix.
x = matrix( [[1],[2],[3]] )                  # Creates a matrix (like a column vector).
y = matrix( [[1,2,3]] )                      # Creates a matrix (like a row vector).
print A.T                                    # Transpose of A.
print A*x                                    # Matrix multiplication of A and x.
print A.I                                    # Inverse of A.
print linalg.solve(A, x)     # Solve the linear equation system.

You can also have a look at the array module, which is a much more efficient implementation of lists when you have to deal with only one data type.

Angular 2: How to call a function after get a response from subscribe http.post

You can code as a lambda expression as the third parameter(on complete) to the subscribe method. Here I re-set the departmentModel variable to the default values.

saveData(data:DepartmentModel){
  return this.ds.sendDepartmentOnSubmit(data).
  subscribe(response=>this.status=response,
   ()=>{},
   ()=>this.departmentModel={DepartmentId:0});
}

Tomcat starts but home page cannot open with url http://localhost:8080

The problems may happen because of memory issue. java.lang.OutOfMemoryError: Java heap space

please verify the logfile, any issues related to hardware(memory).

JMS Topic vs Queues

That means a topic is appropriate. A queue means a message goes to one and only one possible subscriber. A topic goes to each and every subscriber.

Python 101: Can't open file: No such file or directory

From your question, you are running python2.7 and Cygwin.

Python should be installed for windows, which from your question it seems it is. If "which python" prints out /usr/bin/python , then from the bash prompt you are running the cygwin version.

Set the Python Environmental variables appropriately , for instance in my case:

PY_HOME=C:\opt\Python27
PYTHONPATH=C:\opt\Python27;c:\opt\Python27\Lib

In that case run cygwin setup and uninstall everything python. After that run "which pydoc", if it shows

/usr/bin/pydoc

Replace /usr/bin/pydoc with

#! /bin/bash
 /cygdrive/c/WINDOWS/system32/cmd /c %PYTHONHOME%\Scripts\\pydoc.bat

Then add this to $PY_HOME/Scripts/pydoc.bat

rem wrapper for pydoc on Win32
@python c:\opt\Python27\Lib\pydoc.py %*

Now when you type in the cygwin bash prompt you should see:

$ pydoc
 pydoc - the Python documentation tool

 pydoc.py <name> ...
   Show text documentation on something.  <name> 
   may be the name of a Python keyword, topic,
   function, module, or package, or a dotted
   reference to a class or function within a
   module or module in a package.
...

In HTML5, should the main navigation be inside or outside the <header> element?

It's completely up to you. You can either put them in the header or not, as long as the elements within them are internal navigation elements only (i.e. don't link to external sites such as a twitter or facebook account) then it's fine.

They tend to get placed in a header simply because that's where navigation often goes, but it's not set in stone.

You can read more about it at HTML5 Doctor.

How do I properly escape quotes inside HTML attributes?

&quot; is the correct way, the third of your tests:

<option value="&quot;asd">test</option>

You can see this working below, or on jsFiddle.

_x000D_
_x000D_
alert($("option")[0].value);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select>_x000D_
  <option value="&quot;asd">Test</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Alternatively, you can delimit the attribute value with single quotes:

<option value='"asd'>test</option>

Google Maps API OVER QUERY LIMIT per second limit

Instead of client-side geocoding

geocoder.geocode({
    'address': your_address
  }, function (results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
       var geo_data = results[0];
       // your code ...
   } 
})

I would go to server-side geocoding API

var apikey = YOUR_API_KEY;
var query = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&key=' + apikey;
$.getJSON(query, function (data) {
  if (data.status === 'OK') { 
    var geo_data = data.results[0];
  } 
})

Apache VirtualHost and localhost

This worked for me!

To run projects like http://localhost/projectName

<VirtualHost localhost:80>
   ServerAdmin localhost
    DocumentRoot path/to/htdocs/
    ServerName localhost
</VirtualHost>

To run projects like http://somewebsite.com locally

<VirtualHost somewebsite.com:80>
     ServerAdmin [email protected]
     DocumentRoot /path/to/htdocs/somewebsiteFolder
     ServerName www.somewebsite.com
     ServerAlias somewebsite.com
</VirtualHost>

Same for other websites

<VirtualHost anothersite.local:80>
     ServerAdmin [email protected]
     DocumentRoot /path/to/htdocs/anotherSiteFolder
     ServerName www.anothersite.local
     ServerAlias anothersite.com
</VirtualHost>

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

I had the same problem, however all popular answers - to change .tooltip-inner{width} for my task failed to do the job right. As for other (i.e. shorter) tooltips fixed width was too big. I was lazy to write separate html templates/classes for zilions of tooltips, so I just replaced all spaces between words with &nbsp; in each text line.

How do you get the cursor position in a textarea?

If there is no selection, you can use the properties .selectionStart or .selectionEnd (with no selection they're equal).

var cursorPosition = $('#myTextarea').prop("selectionStart");

Note that this is not supported in older browsers, most notably IE8-. There you'll have to work with text ranges, but it's a complete frustration.

I believe there is a library somewhere which is dedicated to getting and setting selections/cursor positions in input elements, though. I can't recall its name, but there seem to be dozens on articles about this subject.

Find a file with a certain extension in folder

It's quite easy, actually. You can use the System.IO.Directory class in conjunction with System.IO.Path. Something like (using LINQ makes it even easier):

var allFilenames = Directory.EnumerateFiles(path).Select(p => Path.GetFileName(p));

// Get all filenames that have a .txt extension, excluding the extension
var candidates = allFilenames.Where(fn => Path.GetExtension(fn) == ".txt")
                             .Select(fn => Path.GetFileNameWithoutExtension(fn));

There are many variations on this technique too, of course. Some of the other answers are simpler if your filter is simpler. This one has the advantage of the delayed enumeration (if that matters) and more flexible filtering at the expense of more code.

How can I get the current time in C#?

DateTime.Now is what you're searching for...

C# constructors overloading

You can factor out your common logic to a private method, for example called Initialize that gets called from both constructors.

Due to the fact that you want to perform argument validation you cannot resort to constructor chaining.

Example:

public Point2D(double x, double y)
{
    // Contracts

    Initialize(x, y);
}

public Point2D(Point2D point)
{
    if (point == null)
        throw new ArgumentNullException("point");

    // Contracts

    Initialize(point.X, point.Y);
}

private void Initialize(double x, double y)
{
    X = x;
    Y = y;
}

How to delete a character from a string using Python

You can simply use list comprehension.

Assume that you have the string: my name is and you want to remove character m. use the following code:

"".join([x for x in "my name is" if x is not 'm'])

What are all the common ways to read a file in Ruby?

File.open("my/file/path", "r") do |f|
  f.each_line do |line|
    puts line
  end
end
# File is closed automatically at end of block

It is also possible to explicitly close file after as above (pass a block to open closes it for you):

f = File.open("my/file/path", "r")
f.each_line do |line|
  puts line
end
f.close

AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

remove {{}} braces around foo.bar because angular expressions cannot be used in angular directives.

For More: https://docs.angularjs.org/api/ng/directive/ngShow

example

  <body ng-app="changeExample">
    <div ng-controller="ExampleController">
    <p ng-show="foo.bar">I could be shown, or I could be hidden</p>
    <p ng-hide="foo.bar">I could be shown, or I could be hidden</p>
    </div>
    </body>

<script>
     angular.module('changeExample', [])
        .controller('ExampleController', ['$scope', function($scope) {
          $scope.foo ={};
          $scope.foo.bar = true;
        }]);
</script>

How to list npm user-installed packages?

npm ls

npm list is just an alias for npm ls

For the extended info use

npm la    
npm ll

You can always set --depth=0 at the end to get the first level deep.

npm ls --depth=0

You can check development and production packages.

npm ls --only=dev
npm ls --only=prod

To show the info in json format

npm ls --json=true

The default is false

npm ls --json=false

You can insist on long format to show extended information.

npm ls --long=true

You can show parseable output instead of tree view.

npm ls --parseable=true

You can list packages in the global install prefix instead of in the current project.

npm ls --global=true
npm ls -g // shorthand

Full documentation you can find here.

Check orientation on Android phone

Old post I know. Whatever the orientation may be or is swapped etc. I designed this function that is used to set the device in the right orientation without the need to know how the portrait and landscape features are organised on the device.

   private void initActivityScreenOrientPortrait()
    {
        // Avoid screen rotations (use the manifests android:screenOrientation setting)
        // Set this to nosensor or potrait

        // Set window fullscreen
        this.activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

        DisplayMetrics metrics = new DisplayMetrics();
        this.activity.getWindowManager().getDefaultDisplay().getMetrics(metrics);

         // Test if it is VISUAL in portrait mode by simply checking it's size
        boolean bIsVisualPortrait = ( metrics.heightPixels >= metrics.widthPixels ); 

        if( !bIsVisualPortrait )
        { 
            // Swap the orientation to match the VISUAL portrait mode
            if( this.activity.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT )
             { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); }
            else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT ); }
        }
        else { this.activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR); }

    }

Works like a charm!

Plot two graphs in same plot in R

As described by @redmode, you may plot the two lines in the same graphical device using ggplot. In that answer the data were in a 'wide' format. However, when using ggplot it is generally most convenient to keep the data in a data frame in a 'long' format. Then, by using different 'grouping variables' in the aesthetics arguments, properties of the line, such as linetype or colour, will vary according to the grouping variable, and corresponding legends will appear.

In this case, we can use the colour aessthetics, which matches colour of the lines to different levels of a variable in the data set (here: y1 vs y2). But first we need to melt the data from wide to long format, using e.g. the function 'melt' from reshape2 package. Other methods to reshape the data are described here: Reshaping data.frame from wide to long format.

library(ggplot2)
library(reshape2)

# original data in a 'wide' format
x  <- seq(-2, 2, 0.05)
y1 <- pnorm(x)
y2 <- pnorm(x, 1, 1)
df <- data.frame(x, y1, y2)

# melt the data to a long format
df2 <- melt(data = df, id.vars = "x")

# plot, using the aesthetics argument 'colour'
ggplot(data = df2, aes(x = x, y = value, colour = variable)) + geom_line()

enter image description here

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

Python 3.3 and later now uses the 2010 compiler. To best way to solve the issue is to just install Visual C++ Express 2010 for free.

Now comes the harder part for 64 bit users and to be honest I just moved to 32 bit but 2010 express doesn't come with a 64 bit compiler (you get a new error, ValueError: ['path'] ) so you have to install Microsoft SDK 7.1 and follow the directions here to get the 64 bit compiler working with python: Python PIP has issues with path for MS Visual Studio 2010 Express for 64-bit install on Windows 7

It may just be easier for you to use the 32 bit version for now. In addition to getting the compiler working, you can bypass the need to compile many modules by getting the binary wheel file from this locaiton http://www.lfd.uci.edu/~gohlke/pythonlibs/

Just download the .whl file you need, shift + right click the download folder and select "open command window here" and run

pip install module-name.whl 

I used that method on 64 bit 3.4.3 before I broke down and decided to just get a working compiler for pip compiles modules from source by default, which is why the binary wheel files work and having pip build from source doesn't.

People getting this (vcvarsall.bat) error on Python 2.7 can instead install "Microsoft Visual C++ Compiler for Python 2.7"

Retrieving a Foreign Key value with django-rest-framework serializers

Simple solution source='category.name' where category is foreign key and .name it's attribute.

from rest_framework.serializers import ModelSerializer, ReadOnlyField
from my_app.models import Item

class ItemSerializer(ModelSerializer):
    category_name = ReadOnlyField(source='category.name')

    class Meta:
        model = Item
        fields = "__all__"

Checking if a variable is not nil and not zero in ruby

class Object
  def nil_zero?
    self.nil? || self == 0
  end
end

# which lets you do
nil.nil_zero? # returns true
0.nil_zero?   # returns true
1.nil_zero?   # returns false
"a".nil_zero? # returns false

unless discount.nil_zero?
  # do stuff...
end

Beware of the usual disclaimers... great power/responsibility, monkey patching leading to the dark side etc.

Use JSTL forEach loop's varStatus as an ID

You can try this. similar result

 <c:forEach items="${loopableObject}" var="theObject" varStatus="theCount">
    <div id="divIDNo${theCount.count}"></div>
 </c:forEach>

what is the difference between XSD and WSDL

XSD (XML schema definition) defines the element in an XML document. It can be used to verify if the elements in the xml document adheres to the description in which the content is to be placed. While wsdl is specific type of XML document which describes the web service. WSDL itself adheres to a XSD.

Writelines writes lines without newline, Just fills the file

As we want to only separate lines, and the writelines function in python does not support adding separator between lines, I have written the simple code below which best suits this problem:

sep = "\n" # defining the separator
new_lines = sep.join(lines) # lines as an iterator containing line strings

and finally:

with open("file_name", 'w') as file:
    file.writelines(new_lines)

and you are done.

In c# is there a method to find the max of 3 numbers?

Maximum element value in priceValues[] is maxPriceValues :

double[] priceValues = new double[3];
priceValues [0] = 1;
priceValues [1] = 2;
priceValues [2] = 3;
double maxPriceValues = priceValues.Max();

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

You cannot use properties that are not mapped to a database column in a Where expression. You must build the expression based on mapped properties, like:

var date = DateTime.Now.AddYears(-from);
result = result.Where(p => date >= p.DOB);
// you don't need `AsQueryable()` here because result is an `IQueryable` anyway

As a replacement for your not mapped Age property you can extract this expression into a static method like so:

public class clsProfileDate
{
    // ...
    public DateTime DOB { get; set; } // property mapped to DB table column

    public static Expression<Func<clsProfileDate, bool>> IsOlderThan(int age)
    {
        var date = DateTime.Now.AddYears(-age);
        return p => date >= p.DOB;
    }
}

And then use it this way:

result = result.Where(clsProfileDate.IsOlderThan(from));

Given a URL to a text file, what is the simplest way to read the contents of the text file?

I do think requests is the best option. Also note the possibility of setting encoding manually.

import requests
response = requests.get("http://www.gutenberg.org/files/10/10-0.txt")
# response.encoding = "utf-8"
hehe = response.text

Picasso v/s Imageloader v/s Fresco vs Glide

These answers are totally my opinion

Answers

  1. Picasso is an easy to use image loader, same goes for Imageloader. Fresco uses a different approach to image loading, i haven't used it yet but it looks too me more like a solution for getting image from network and caching them then showing the images. then the other way around like Picasso/Imageloader/Glide which to me are more Showing image on screen that also does getting images from network and caching them.

  2. Glide tries to be somewhat interchangeable with Picasso.I think when they were created Picasso's mind set was follow HTTP spec's and let the server decide the caching policies and cache full sized and resize on demand. Glide is the same with following the HTTP spec but tries to have a smaller memory footprint by making some different assumptions like cache the resized images instead of the fullsized images, and show images with RGB_565 instead of RGB_8888. Both libraries offer full customization of the default settings.

  3. As to which library is the best to use is really hard to say. Picasso, Glide and Imageloader are well respected and well tested libraries which all are easy to use with the default settings. Both Picasso and Glide require only 1 line of code to load an image and have a placeholder and error image. Customizing the behaviour also doesn't require that much work. Same goes for Imageloader which is also an older library then Picasso and Glide, however I haven't used it so can't say much about performance/memory usage/customizations but looking at the readme on github gives me the impression that it is also relatively easy to use and setup. So in choosing any of these 3 libraries you can't make the wrong decision, its more a matter of personal taste. For fresco my opinion is that its another facebook library so we have to see how that is going to work out for them, so far there track record isn't that good. Like the facebook SDK is still isn't officially released on mavenCentral I have not used to facebook sdk since sept 2014 and it seems they have put the first version online on mavenCentral in oct 2014. So it will take some time before we can get any good opinion about it.

  4. between the 3 big name libraries I think there are no significant differences. The only one that stand out is fresco but that is because it has a different approach and is new and not battle tested.

Conveniently map between enum and int / String

enum ? int

yourEnum.ordinal()

int ? enum

EnumType.values()[someInt]

String ? enum

EnumType.valueOf(yourString)

enum ? String

yourEnum.name()

A side-note:
As you correctly point out, the ordinal() may be "unstable" from version to version. This is the exact reason why I always store constants as strings in my databases. (Actually, when using MySql, I store them as MySql enums!)

How to convert byte array to string

To convert the byte[] to string[], simply use the below line.

byte[] fileData; // Some byte array
//Convert byte[] to string[]
var table = (Encoding.Default.GetString(
                 fileData, 
                 0, 
                 fileData.Length - 1)).Split(new string[] { "\r\n", "\r", "\n" },
                                             StringSplitOptions.None);

Dump a mysql database to a plaintext (CSV) backup from the command line

Check out mk-parallel-dump which is part of the ever-useful maatkit suite of tools. This can dump comma-separated files with the --csv option.

This can do your whole db without specifying individual tables, and you can specify groups of tables in a backupset table.

Note that it also dumps table definitions, views and triggers into separate files. In addition providing a complete backup in a more universally accessible form, it also immediately restorable with mk-parallel-restore

std::cin input with spaces?

I rather use the following method to get the input:

#include <iostream>
#include <string>

using namespace std;

int main(void) {
    string name;

    cout << "Hello, Input your name please: ";
    getline(cin, name);

    return 0;
}

It's actually super easy to use rather than defining the total length of array for a string which contains a space character.

How to convert a Hibernate proxy to a real entity object

Starting from Hiebrnate 5.2.10 you can use Hibernate.proxy method to convert a proxy to your real entity:

MyEntity myEntity = (MyEntity) Hibernate.unproxy( proxyMyEntity );

Android video streaming example

Your problem is most likely with the video file, not the code. Your video is most likely not "safe for streaming". See where to place videos to stream android for more.

Django DateField default options

You could also use lambda. Useful if you're using django.utils.timezone.now

date = models.DateField(_("Date"), default=lambda: now().date())

How can I scroll up more (increase the scroll buffer) in iTerm2?

There is an option ā€œunlimited scrollback bufferā€ which you can find under Preferences > Profiles > Terminal or you can just pump up number of lines that you want to have in history in the same place.

Rename a column in MySQL

From MySQL 5.7 Reference Manual.

Syntax :

ALTER TABLE t1 CHANGE a b DATATYPE;

e.g. : for Customer TABLE having COLUMN customer_name, customer_street, customercity.

And we want to change customercity TO customer_city :

alter table customer change customercity customer_city VARCHAR(225);

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

Tooltips for cells in HTML table (no Javascript)

The highest-ranked answer by Mudassar Bashir using the "title" attribute seems the easiest way to do this, but it gives you less control over how the comment/tooltip is displayed.

I found that The answer by Christophe for a custom tooltip class seems to give much more control over the behavior of the comment/tooltip. Since the provided demo does not include a table, as per the question, here is a demo that includes a table.

Note that the "position" style for the parent element of the span (a in this case), must be set to "relative" so that the comment does not push the table contents around when it is displayed. It took me a little while to figure that out.

_x000D_
_x000D_
#MyTable{_x000D_
  border-style:solid;_x000D_
  border-color:black;_x000D_
  border-width:2px_x000D_
}_x000D_
_x000D_
#MyTable td{_x000D_
  border-style:solid;_x000D_
  border-color:black;_x000D_
  border-width:1px;_x000D_
  padding:3px;_x000D_
}_x000D_
_x000D_
.CellWithComment{_x000D_
  position:relative;_x000D_
}_x000D_
_x000D_
.CellComment{_x000D_
  display:none;_x000D_
  position:absolute; _x000D_
  z-index:100;_x000D_
  border:1px;_x000D_
  background-color:white;_x000D_
  border-style:solid;_x000D_
  border-width:1px;_x000D_
  border-color:red;_x000D_
  padding:3px;_x000D_
  color:red; _x000D_
  top:20px; _x000D_
  left:20px;_x000D_
}_x000D_
_x000D_
.CellWithComment:hover span.CellComment{_x000D_
  display:block;_x000D_
}
_x000D_
<table id="MyTable">_x000D_
  <caption>Cell 1,2 Has a Comment</caption>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <td>Heading 1</td>_x000D_
      <td>Heading 2</td>_x000D_
      <td>Heading 3</td>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr></tr>_x000D_
      <td>Cell 1,1</td>_x000D_
      <td class="CellWithComment">Cell 1,2_x000D_
        <span class="CellComment">Here is a comment</span>_x000D_
      </td>_x000D_
      <td>Cell 1,3</td>_x000D_
    <tr>_x000D_
      <td>Cell 2,1</td>_x000D_
      <td>Cell 2,2</td>_x000D_
      <td>Cell 2,3</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Converting file into Base64String and back again

For Java, consider using Apache Commons FileUtils:

/**
 * Convert a file to base64 string representation
 */
public String fileToBase64(File file) throws IOException {
    final byte[] bytes = FileUtils.readFileToByteArray(file);
    return Base64.getEncoder().encodeToString(bytes);
}

/**
 * Convert base64 string representation to a file
 */
public void base64ToFile(String base64String, String filePath) throws IOException {
    byte[] bytes = Base64.getDecoder().decode(base64String);
    FileUtils.writeByteArrayToFile(new File(filePath), bytes);
}

How to run Linux commands in Java?

if the opening in windows

try {
        //chm file address
        String chmFile = System.getProperty("user.dir") + "/chm/sample.chm";
        Desktop.getDesktop().open(new File(chmFile));
    } catch (IOException ex) {
        Logger.getLogger(Frame.class.getName()).log(Level.SEVERE, null, ex);
        {
            JOptionPane.showMessageDialog(null, "Terjadi Kesalahan", "Error", JOptionPane.WARNING_MESSAGE);
        }
    }

Which characters make a URL invalid?

To add some clarification and directly address the question above, there are several classes of characters that cause problems for URLs and URIs.

There are some characters that are disallowed and should never appear in a URL/URI, reserved characters (described below), and other characters that may cause problems in some cases, but are marked as "unwise" or "unsafe". Explanations for why the characters are restricted are clearly spelled out in RFC-1738 (URLs) and RFC-2396 (URIs). Note the newer RFC-3986 (update to RFC-1738) defines the construction of what characters are allowed in a given context but the older spec offers a simpler and more general description of which characters are not allowed with the following rules.

Excluded US-ASCII Characters disallowed within the URI syntax:

   control     = <US-ASCII coded characters 00-1F and 7F hexadecimal>
   space       = <US-ASCII coded character 20 hexadecimal>
   delims      = "<" | ">" | "#" | "%" | <">

The character "#" is excluded because it is used to delimit a URI from a fragment identifier. The percent character "%" is excluded because it is used for the encoding of escaped characters. In other words, the "#" and "%" are reserved characters that must be used in a specific context.

List of unwise characters are allowed but may cause problems:

   unwise      = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`"

Characters that are reserved within a query component and/or have special meaning within a URI/URL:

  reserved    = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | ","

The "reserved" syntax class above refers to those characters that are allowed within a URI, but which may not be allowed within a particular component of the generic URI syntax. Characters in the "reserved" set are not reserved in all contexts. The hostname, for example, can contain an optional username so it could be something like ftp://user@hostname/ where the '@' character has special meaning.

Here is an example of a URL that has invalid and unwise characters (e.g. '$', '[', ']') and should be properly encoded:

http://mw1.google.com/mw-earth-vectordb/kml-samples/gp/seattle/gigapxl/$[level]/r$[y]_c$[x].jpg

Some of the character restrictions for URIs and URLs are programming language-dependent. For example, the '|' (0x7C) character although only marked as "unwise" in the URI spec will throw a URISyntaxException in the Java java.net.URI constructor so a URL like http://api.google.com/q?exp=a|b is not allowed and must be encoded instead as http://api.google.com/q?exp=a%7Cb if using Java with a URI object instance.

CSS hide scroll bar if not needed

You can use overflow:auto;

You can also control the x or y axis individually with the overflow-x and overflow-y properties.

Example:

.content {overflow:auto;}
.content {overflow-y:auto;}
.content {overflow-x:auto;}

program cant start because php5.dll is missing

What you can do to solve this is:

  1. Download PHP5.dll or PHP7.dll from: http://windows.php.net/download/.
  2. Copy the downloaded php5.dll or php7.dll to C:\xampp\php.
  3. Start Apache and MySQL from XAMPP Control Panel.

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

Git push hangs when pushing to Github?

  1. Had the same problem. Was a little bit confused but the thing was I had make a git init --bare on root, that means that you won't be able to push because of you don't have any rights. Instead make a new User or in my case I used Pi User and made git init --bare there, which then later on it worked.

  2. git config --global http.postBuffer 524288000

Maximum size in bytes of the buffer used by smart HTTP transports when POSTing data to the remote system. For requests larger than this buffer size, HTTP/1.1 and Transfer-Encoding: chunked is used to avoid creating a massive pack file locally. Default is 1 MiB, which is sufficient for most requests.

update package.json version automatically

Right answer

To do so, just npm version patch =)

My old answer

There is no pre-release hook originally in git. At least, man githooks does not show it.

If you're using git-extra (https://github.com/visionmedia/git-extras), for instance, you can use a pre-release hook which is implemented by it, as you can see at https://github.com/visionmedia/git-extras/blob/master/bin/git-release. It is needed only a .git/hook/pre-release.sh executable file which edits your package.json file. Committing, pushing and tagging will be done by the git release command.

If you're not using any extension for git, you can write a shell script (I'll name it git-release.sh) and than you can alias it to git release with something like:

git config --global alias.release '!sh path/to/pre-release.sh $1'

You can, than, use git release 0.4 which will execute path/to/pre-release.sh 0.4. Your script can edit package.json, create the tag and push it to the server.

Regular expression to allow spaces between words

Try with:

^(\w+ ?)*$

Explanation:

\w             - alias for [a-zA-Z_0-9]
"whitespace"?  - allow whitespace after word, set is as optional

Installing MySQL-python

Reread the error message. It says:

sh: mysql_config: not found

If you are on Ubuntu Natty, mysql_config belongs to package libmysqlclient-dev

Correlation heatmap

The code below will produce this plot:

enter image description here

import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

# A list with your data slightly edited
l = [1.0,0.00279981,0.95173379,0.02486161,-0.00324926,-0.00432099,
0.00279981,1.0,0.17728303,0.64425774,0.30735071,0.37379443,
0.95173379,0.17728303,1.0,0.27072266,0.02549031,0.03324756,
0.02486161,0.64425774,0.27072266,1.0,0.18336236,0.18913512,
-0.00324926,0.30735071,0.02549031,0.18336236,1.0,0.77678274,
-0.00432099,0.37379443,0.03324756,0.18913512,0.77678274,1.00]

# Split list
n = 6
data = [l[i:i + n] for i in range(0, len(l), n)]

# A dataframe
df = pd.DataFrame(data)

def CorrMtx(df, dropDuplicates = True):

    # Your dataset is already a correlation matrix.
    # If you have a dateset where you need to include the calculation
    # of a correlation matrix, just uncomment the line below:
    # df = df.corr()

    # Exclude duplicate correlations by masking uper right values
    if dropDuplicates:    
        mask = np.zeros_like(df, dtype=np.bool)
        mask[np.triu_indices_from(mask)] = True

    # Set background color / chart style
    sns.set_style(style = 'white')

    # Set up  matplotlib figure
    f, ax = plt.subplots(figsize=(11, 9))

    # Add diverging colormap from red to blue
    cmap = sns.diverging_palette(250, 10, as_cmap=True)

    # Draw correlation plot with or without duplicates
    if dropDuplicates:
        sns.heatmap(df, mask=mask, cmap=cmap, 
                square=True,
                linewidth=.5, cbar_kws={"shrink": .5}, ax=ax)
    else:
        sns.heatmap(df, cmap=cmap, 
                square=True,
                linewidth=.5, cbar_kws={"shrink": .5}, ax=ax)


CorrMtx(df, dropDuplicates = False)

I put this together after it was announced that the outstanding seaborn corrplot was to be deprecated. The snippet above makes a resembling correlation plot based on seaborn heatmap. You can also specify the color range and select whether or not to drop duplicate correlations. Notice that I've used the same numbers as you, but that I've put them in a pandas dataframe. Regarding the choice of colors you can have a look at the documents for sns.diverging_palette. You asked for blue, but that falls out of this particular range of the color scale with your sample data. For both observations of 0.95173379, try changing to -0.95173379 and you'll get this:

enter image description here

How do I detect IE 8 with jQuery?

document.documentMode is undefined if the browser is not IE8,

it returns 8 for standards mode and 7 for 'compatable to IE7'

If it is running as IE7 there are a lot of css and dom features that won't be supported.

JQuery find first parent element with specific class prefix

Use .closest() with a selector:

var $div = $('#divid').closest('div[class^="div-a"]');

How to get hostname from IP (Linux)?

To find a hostname in your local network by IP address you can use:

nmblookup -A <ip>

To find a hostname on the internet you could use the host program:

host <ip>

Or you can install nbtscan by running:

sudo apt-get install nbtscan

And use:

nbtscan <ip>

*Taken from https://askubuntu.com/questions/205063/command-to-get-the-hostname-of-remote-server-using-ip-address/205067#205067

Update 2018-05-13

You can query a name server with nslookup. It works both ways!

nslookup <IP>
nslookup <hostname>

Is JavaScript object-oriented?

It is object oriented, but not based on classes, it's based on prototypes.

Sending cookies with postman

Enable intercepter in this way

Basically it is a chrome plug in. After installing the extention, you also need to make sure the extention is enabled from chrome side.

enter image description here

get path for my .exe

in visualstudio 2008 you could use this code :

   var _assembly = System.Reflection.Assembly
               .GetExecutingAssembly().GetName().CodeBase;

   var _path = System.IO.Path.GetDirectoryName(_assembly) ;

How can I use "." as the delimiter with String.split() in java

The argument to split is a regular expression. "." matches anything so your delimiter to split on is anything.

Redirect to an external URL from controller action in Spring MVC

You can do it with two ways.

First:

@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public void method(HttpServletResponse httpServletResponse) {
    httpServletResponse.setHeader("Location", projectUrl);
    httpServletResponse.setStatus(302);
}

Second:

@RequestMapping(value = "/redirect", method = RequestMethod.GET)
public ModelAndView method() {
    return new ModelAndView("redirect:" + projectUrl);
}

super() fails with error: TypeError "argument 1 must be type, not classobj" when parent does not inherit from object

Also, if you can't change class B, you can fix the error by using multiple inheritance.

class B:
    def meth(self, arg):
        print arg

class C(B, object):
    def meth(self, arg):
        super(C, self).meth(arg)

print C().meth(1)

java.io.StreamCorruptedException: invalid stream header: 7371007E

when I send only one object from the client to server all works well.

when I attempt to send several objects one after another on the same stream I get StreamCorruptedException.

Actually, your client code is writing one object to the server and reading multiple objects from the server. And there is nothing on the server side that is writing the objects that the client is trying to read.

How to export data to an excel file using PHPExcel

Try the below complete example for the same

<?php
  $objPHPExcel = new PHPExcel();
  $query1 = "SELECT * FROM employee";
  $exec1 = mysql_query($query1) or die ("Error in Query1".mysql_error());
  $serialnumber=0;
  //Set header with temp array
  $tmparray =array("Sr.Number","Employee Login","Employee Name");
  //take new main array and set header array in it.
  $sheet =array($tmparray);

  while ($res1 = mysql_fetch_array($exec1))
  {
    $tmparray =array();
    $serialnumber = $serialnumber + 1;
    array_push($tmparray,$serialnumber);
    $employeelogin = $res1['employeelogin'];
    array_push($tmparray,$employeelogin);
    $employeename = $res1['employeename'];
    array_push($tmparray,$employeename);   
    array_push($sheet,$tmparray);
  }
   header('Content-type: application/vnd.ms-excel');
   header('Content-Disposition: attachment; filename="name.xlsx"');
  $worksheet = $objPHPExcel->getActiveSheet();
  foreach($sheet as $row => $columns) {
    foreach($columns as $column => $data) {
        $worksheet->setCellValueByColumnAndRow($column, $row + 1, $data);
    }
  }

  //make first row bold
  $objPHPExcel->getActiveSheet()->getStyle("A1:I1")->getFont()->setBold(true);
  $objPHPExcel->setActiveSheetIndex(0);
  $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
  $objWriter->save(str_replace('.php', '.xlsx', __FILE__));
?>

Table with fixed header and fixed column on pure css

An actual pure CSS solution with a fixed header row and first column

I had to create a table with both a fixed header and a fixed first column using pure CSS and none of the answers here were quite what I wanted.

The position: sticky property supports both sticking to the top (as I've seen it used the most) and to the side in modern versions of Chrome, Firefox, and Edge. This can be combined with a div that has the overflow: scroll property to give you a table with fixed headers that can be placed anywhere on your page:

Place your table in a container:

<div class="container">
  <table></table>
</div>

Use overflow: scroll on your container to enable scrolling:

div.container {
  overflow: scroll;
}

As Dagmar pointed out in the comments, the container also requires a max-width and a max-height.

Use position: sticky to have table cells stick to the edge and top, right, or left to choose which edge to stick to:

thead th {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  top: 0;
}

tbody th {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  left: 0;
}

As MarredCheese mentioned in the comments, if your first column contains <td> elements instead of <th> elements, you can use tbody td:first-child in your CSS instead of tbody th

To have the header in the first column stick to the left, use:

thead th:first-child {
  left: 0;
  z-index: 1;
}

_x000D_
_x000D_
/* Use overflow:scroll on your container to enable scrolling: */

div {
  max-width: 400px;
  max-height: 150px;
  overflow: scroll;
}


/* Use position: sticky to have it stick to the edge
 * and top, right, or left to choose which edge to stick to: */

thead th {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  top: 0;
}

tbody th {
  position: -webkit-sticky; /* for Safari */
  position: sticky;
  left: 0;
}


/* To have the header in the first column stick to the left: */

thead th:first-child {
  left: 0;
  z-index: 2;
}


/* Just to display it nicely: */

thead th {
  background: #000;
  color: #FFF;
  /* Ensure this stays above the emulated border right in tbody th {}: */
  z-index: 1;
}

tbody th {
  background: #FFF;
  border-right: 1px solid #CCC;
  /* Browsers tend to drop borders on sticky elements, so we emulate the border-right using a box-shadow to ensure it stays: */
  box-shadow: 1px 0 0 0 #ccc;
}

table {
  border-collapse: collapse;
}

td,
th {
  padding: 0.5em;
}
_x000D_
<div>
  <table>
    <thead>
      <tr>
        <th></th>
        <th>headheadhead</th>
        <th>headheadhead</th>
        <th>headheadhead</th>
        <th>headheadhead</th>
        <th>headheadhead</th>
        <th>headheadhead</th>
        <th>headheadhead</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <th>head</th>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
      </tr>
      <tr>
        <th>head</th>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
      </tr>
      <tr>
        <th>head</th>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
      </tr>
      <tr>
        <th>head</th>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
      </tr>
      <tr>
        <th>head</th>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
      </tr>
      <tr>
        <th>head</th>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
        <td>body</td>
      </tr>
    </tbody>
  </table>
</div>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/qwubvg9m/1/

Curl to return http status code along with the response

For programmatic usage, I use the following :

curlwithcode() {
    code=0
    # Run curl in a separate command, capturing output of -w "%{http_code}" into statuscode
    # and sending the content to a file with -o >(cat >/tmp/curl_body)
    statuscode=$(curl -w "%{http_code}" \
        -o >(cat >/tmp/curl_body) \
        "$@"
    ) || code="$?"

    body="$(cat /tmp/curl_body)"
    echo "statuscode : $statuscode"
    echo "exitcode : $code"
    echo "body : $body"
}

curlwithcode https://api.github.com/users/tj

It shows following output :

statuscode : 200
exitcode : 0
body : {
  "login": "tj",
  "id": 25254,
  ...
}

Output grep results to text file, need cleaner output

Redirection of program output is performed by the shell.

grep ... > output.txt

grep has no mechanism for adding blank lines between each match, but does provide options such as context around the matched line and colorization of the match itself. See the grep(1) man page for details, specifically the -C and --color options.

Use jQuery to get the file input's selected filename without the path

<script type="text/javascript">

    $('#upload').on('change',function(){
       // output raw value of file input
       $('#filename').html($(this).val().replace(/.*(\/|\\)/, '')); 

        // or, manipulate it further with regex etc.
        var filename = $(this).val().replace(/.*(\/|\\)/, '');
        // .. do your magic

        $('#filename').html(filename);
    });
</script>

XML to CSV Using XSLT

Here is a version with configurable parameters that you can set programmatically:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output method="text" encoding="utf-8" />

  <xsl:param name="delim" select="','" />
  <xsl:param name="quote" select="'&quot;'" />
  <xsl:param name="break" select="'&#xA;'" />

  <xsl:template match="/">
    <xsl:apply-templates select="projects/project" />
  </xsl:template>

  <xsl:template match="project">
    <xsl:apply-templates />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$break" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="*">
    <!-- remove normalize-space() if you want keep white-space at it is --> 
    <xsl:value-of select="concat($quote, normalize-space(), $quote)" />
    <xsl:if test="following-sibling::*">
      <xsl:value-of select="$delim" />
    </xsl:if>
  </xsl:template>

  <xsl:template match="text()" />
</xsl:stylesheet>

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

The way you can exclude a destination directory while using the /mir is by making sure the destination directory also exists on the source. I went into my source drive and created blank directories with the same name as on the destination, and then added that directory name to the /xd. It successfully mirrored everything while excluding the directory on the source, thereby leaving the directory on the destination intact.

Generate unique random numbers between 1 and 100

For example: To generate 8 unique random numbers and store them to an array, you can simply do this:

_x000D_
_x000D_
var arr = [];_x000D_
while(arr.length < 8){_x000D_
    var r = Math.floor(Math.random() * 100) + 1;_x000D_
    if(arr.indexOf(r) === -1) arr.push(r);_x000D_
}_x000D_
console.log(arr);
_x000D_
_x000D_
_x000D_

Using an array as needles in strpos

The question, is the provided example just an "example" or exact what you looking for? There are many mixed answers here, and I dont understand the complexibility of the accepted one.

To find out if ANY content of the array of needles exists in the string, and quickly return true or false:

$string = 'abcdefg';

if(str_replace(array('a', 'c', 'd'), '', $string) != $string){
    echo 'at least one of the needles where found';
};

If, so, please give @Leon credit for that.

To find out if ALL values of the array of needles exists in the string, as in this case, all three 'a', 'b' and 'c' MUST be present, like you mention as your "for example"

echo 'All the letters are found in the string!';

Many answers here is out of that context, but I doubt that the intension of the question as you marked as resolved. E.g. The accepted answer is a needle of

$array  = array('burger', 'melon', 'cheese', 'milk');

What if all those words MUST be found in the string?

Then you try out some "not accepted answers" on this page.

How to get setuptools and easy_install?

For python3 on Ubuntu

 sudo apt-get install python3-setuptools

Double precision floating values in Python?

Decimal datatype

  • Unlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem.

If you are pressed by performance issuses, have a look at GMPY

How to determine the screen width in terms of dp or dip at runtime in Android?

Get Screen Width and Height in terms of DP with some good decoration:

Step 1: Create interface

public interface ScreenInterface {

   float getWidth();

   float getHeight();

}

Step 2: Create implementer class

public class Screen implements ScreenInterface {
    private Activity activity;

    public Screen(Activity activity) {
        this.activity = activity;
    }

    private DisplayMetrics getScreenDimension(Activity activity) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        return displayMetrics;
    }

    private float getScreenDensity(Activity activity) {
        return activity.getResources().getDisplayMetrics().density;
    }

    @Override
    public float getWidth() {
        DisplayMetrics displayMetrics = getScreenDimension(activity);
        return displayMetrics.widthPixels / getScreenDensity(activity);
    }

    @Override
    public float getHeight() {
        DisplayMetrics displayMetrics = getScreenDimension(activity);
        return displayMetrics.heightPixels / getScreenDensity(activity);
    }
} 

Step 3: Get width and height in activity:

Screen screen = new Screen(this); // Setting Screen
screen.getWidth();
screen.getHeight();

Remove all special characters with RegExp

var desired = stringToReplace.replace(/[^\w\s]/gi, '')

As was mentioned in the comments it's easier to do this as a whitelist - replace the characters which aren't in your safelist.

The caret (^) character is the negation of the set [...], gi say global and case-insensitive (the latter is a bit redundant but I wanted to mention it) and the safelist in this example is digits, word characters, underscores (\w) and whitespace (\s).

How to use ConcurrentLinkedQueue?

The ConcurentLinkedQueue is a very efficient wait/lock free implementation (see the javadoc for reference), so not only you don't need to synchronize, but the queue will not lock anything, thus being virtually as fast as a non synchronized (not thread safe) one.

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

for the maven users, comment the scope provided in the following dependency:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <!--<scope>provided</scope>-->
    </dependency>

UPDATE

As feed.me mentioned you have to uncomment the provided part depending on what kind of app you are deploying.

Here is a useful link with the details: http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#build-tool-plugins-maven-packaging

Jquery post, response in new window

If you dont need a feedback about the requested data and also dont need any interactivity between the opener and the popup, you can post a hidden form into the popup:

Example:

<form method="post" target="popup" id="formID" style="display:none" action="https://example.com/barcode/generate" >
  <input type="hidden" name="packing_slip" value="35592" />
  <input type="hidden" name="reference" value="0018439" />
  <input type="hidden" name="total_boxes" value="1" />
</form>
<script type="text/javascript">
window.open('about:blank','popup','width=300,height=200')
document.getElementById('formID').submit();
</script>

Otherwise you could use jsonp. But this works only, if you have access to the other Server, because you have to modify the response.

Extracting numbers from vectors of strings

A stringr pipelined solution:

library(stringr)
years %>% str_match_all("[0-9]+") %>% unlist %>% as.numeric

Div Scrollbar - Any way to style it?

This one does well its scrolling job. It's very easy to understand, just really few lines of code, well written and totally readable.

Enable Hibernate logging

We have a tomcat-8.5 + restlet-2.3.4 + hibernate-4.2.0 + log4j-1.2.14 java 8 app running on AlpineLinux in docker.

On adding these 2 lines to /usr/local/tomcat/webapps/ROOT/WEB-INF/classes/log4j.properties, I started seeing the HQL queries in the logs:

### log just the SQL
log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=debug

However, the JDBC bind parameters are not being logged.

Difference between jQuery parent(), parents() and closest() functions

closest() selects the first element that matches the selector, up from the DOM tree. Begins from the current element and travels up.

parent() selects one element up (single level up) the DOM tree.

parents() method is similar to parent() but selects all the matching elements up the DOM tree. Begins from the parent element and travels up.

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

Simply apply Twitter Bootstrap text-success class on Glyphicon:

<span class="glyphicon glyphicon-play text-success">????? ??????</span>

enter image description here

Full list of available colors: Bootstrap Documentation: Helper classes
(Blue is present also)

Update using LINQ to SQL

I found a workaround a week ago. You can use direct commands with "ExecuteCommand":

MDataContext dc = new MDataContext();
var flag = (from f in dc.Flags
                   where f.Code == Code
                   select f).First();
_refresh = Convert.ToBoolean(flagRefresh.Value);
if (_refresh)
{
    dc.ExecuteCommand("update Flags set value = 0 where code = {0}", Code);
}

In the ExecuteCommand statement, you can send the query directly, with the value for the specific record you want to update.

value = 0 --> 0 is the new value for the record;

code = {0} --> is the field where you will send the filter value;

Code --> is the new value for the field;

I hope this reference helps.

C program to check little vs. big endian

In short, yes.

Suppose we are on a 32-bit machine.

If it is little endian, the x in the memory will be something like:

       higher memory
          ----->
    +----+----+----+----+
    |0x01|0x00|0x00|0x00|
    +----+----+----+----+
    A
    |
   &x

so (char*)(&x) == 1, and *y+48 == '1'.

If it is big endian, it will be:

    +----+----+----+----+
    |0x00|0x00|0x00|0x01|
    +----+----+----+----+
    A
    |
   &x

so this one will be '0'.

How to remove the first and the last character of a string

url=url.substring(1,url.Length-1);

This way you can use the directories if it is like .../.../.../... etc.

symfony2 : failed to write cache directory

If the folder is already writable so thats not the problem.

You can also just navigate to /www/projet_etienne/app/cache/ and manualy remove the folders in there (dev, dev_new, dev_old).

Make sure to SAVE a copy of those folder somewhere to put back if this doesn't fix the problem

I know this is not the way it should be done but it worked for me a couple of times now.

substring of an entire column in pandas dataframe

Use the str accessor with square brackets:

df['col'] = df['col'].str[:9]

Or str.slice:

df['col'] = df['col'].str.slice(0, 9)

How to insert multiple rows from array using CodeIgniter framework?

I have created this simple function which you guys can use easily. You will need to pass the table-name ($tbl), table-field ($insertFieldsArr) against your inserting data, data array ($arr).

insert_batch('table',array('field1','field2'),$dataArray);

    function insert_batch($tbl,$insertFieldsArr,$arr){ $sql = array(); 
    foreach( $arr as $row ) {
        $strVals='';
        $cnt=0;
        foreach($insertFieldsArr as $key=>$val){
            if(is_array($row)){
                $strVals.="'".mysql_real_escape_string($row[$cnt]).'\',';
            }
            else{
                $strVals.="'".mysql_real_escape_string($row).'\',';
            }
            $cnt++;
        }
        $strVals=rtrim($strVals,',');
        $sql[] = '('.$strVals.')';
    }

    $fields=implode(',',$insertFieldsArr);
    mysql_query('INSERT INTO `'.$tbl.'` ('.$fields.') VALUES '.implode(',', $sql));
}

Is it possible to run one logrotate check manually?

Created a shell script to solve the problem.

https://antofthy.gitlab.io/software/#logrotate_one

This script will run just the single logrotate sub-configuration file found in "/etc/logrotate.d", but include the global settings from in the global configuration file "/etc/logrotate.conf". You can also use other otpions for testing it...

For example...

  logrotate_one -d syslog

In .NET, which loop runs faster, 'for' or 'foreach'?

It will always be close. For an array, sometimes for is slightly quicker, but foreach is more expressive, and offers LINQ, etc. In general, stick with foreach.

Additionally, foreach may be optimised in some scenarios. For example, a linked list might be terrible by indexer, but it might be quick by foreach. Actually, the standard LinkedList<T> doesn't even offer an indexer for this reason.

How to run Spyder in virtual environment?

The above answers are correct but I calling spyder within my virtualenv would still use my PATH to look up the version of spyder in my default anaconda env. I found this answer which gave the following workaround:

source activate my_env            # activate your target env with spyder installed
conda info -e                     # look up the directory of your conda env
find /path/to/my/env -name spyder # search for the spyder executable in your env
/path/to/my/env/then/to/spyder    # run that executable directly

I chose this over modifying PATH or adding a link to the executable at a higher priority in PATH since I felt this was less likely to break other programs. However, I did add an alias to the executable in ~/.bash_aliases.

View more than one project/solution in Visual Studio

Don't know whether this is useful but if you want to work with multiple projects without navigating through projects tree {like multi window} you can try opening VS in another virtual desktop (at least it's possible for Windows 10) by holding Ctrl+win+D. Then open another VS studio and open your other project there. You can switch between projects by Ctrl+win+arrow key {left/right}.

MySQL SELECT only not null values

Yes use NOT NULL in your query like this below.

SELECT * 
FROM table
WHERE col IS NOT NULL;

How to save all console output to file in R?

If you have access to a command line, you might prefer running your script from the command line with R CMD BATCH.

== begin contents of script.R ==

a <- "a"
a
How come I do not see this in log

== end contents of script.R ==

At the command prompt ("$" in many un*x variants, "C:>" in windows), run

$ R CMD BATCH script.R &

The trailing "&" is optional and runs the command in the background. The default name of the log file has "out" appended to the extension, i.e., script.Rout

== begin contents of script.Rout ==

R version 3.1.0 (2014-04-10) -- "Spring Dance"
Copyright (C) 2014 The R Foundation for Statistical Computing
Platform: i686-pc-linux-gnu (32-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

  Natural language support but running in an English locale

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

[Previously saved workspace restored]

> a <- "a"
> a
[1] "a"
> How come I do not see this in log
Error: unexpected symbol in "How come"
Execution halted

== end contents of script.Rout ==

Using ADB to capture the screen

https://stackoverflow.com/a/37191719/75579 answer stopped working for me in Android 7 somehow. So I have to do it the manual way, so I want to share it.


How to install

  1. Put this snippet of code in your ~/.bash_profile or ~/.profile file:

    snap_screen() {
      if [ $# -eq 0 ]
      then
        name="screenshot.png"
      else
        name="$1.png"
      fi
      adb shell screencap -p /sdcard/$name
      adb pull /sdcard/$name
      adb shell rm /sdcard/$name
      curr_dir=pwd
      echo "save to `pwd`/$name"
    }
    
  2. Run source ~/.bash_profile or source ~/.profile command,


How to use

Usage without specifying filename:

$ snap_screen
11272 KB/s (256237 bytes in 0.022s)
Saved to /Users/worker8/desktop/screenshot.png

Usage with a filename:

$ snap_screen mega_screen_capture
11272 KB/s (256237 bytes in 0.022s)
Saved to /Users/worker8/desktop/mega_screen_capture.png

Hope it helps!

** This will not work if multiple devices are plugged in

VBA Go to last empty row

try this:

Sub test()

With Application.WorksheetFunction
    Cells(.CountA(Columns("A:A")) + 1, 1).Select
End With

End Sub

Hope this works for you.

Turning Sonar off for certain code

This is a FAQ. You can put //NOSONAR on the line triggering the warning. I prefer using the FindBugs mechanism though, which consists in adding the @SuppressFBWarnings annotation:

@edu.umd.cs.findbugs.annotations.SuppressFBWarnings(
    value = "NAME_OF_THE_FINDBUGS_RULE_TO_IGNORE",
    justification = "Why you choose to ignore it")

How to check if bootstrap modal is open, so I can use jquery validate?

$("element").data('bs.modal').isShown

won't work if the modal hasn't been shown before. You will need to add an extra condition:

$("element").data('bs.modal')

so the answer taking into account first appearance:

if ($("element").data('bs.modal') && $("element").data('bs.modal').isShown){
... 
}

Get list of all tables in Oracle?

The following query only list the required data, whereas the other answers gave me the extra data which only confused me.

select table_name from user_tables;

HTML5 pattern for formatting input box to take date mm/dd/yyyy?

pattern="[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}"

This is pattern to enter the date for textbox in HTML5.
The first one[0-9]{1,2} will take only decimal number minimum 1 and maximum 2.
And other similarly.

How to group pandas DataFrame entries by date in a non-unique column

This might be easier to explain with a sample dataset.

Create Sample Data

Let's assume we have a single column of Timestamps, date and another column we would like to perform an aggregation on, a.

df = pd.DataFrame({'date':pd.DatetimeIndex(['2012-1-1', '2012-6-1', '2015-1-1', '2015-2-1', '2015-3-1']),
                   'a':[9,5,1,2,3]}, columns=['date', 'a'])

df

        date  a
0 2012-01-01  9
1 2012-06-01  5
2 2015-01-01  1
3 2015-02-01  2
4 2015-03-01  3

There are several ways to group by year

  • Use the dt accessor with year property
  • Put date in index and use anonymous function to access year
  • Use resample method
  • Convert to pandas Period

.dt accessor with year property

When you have a column (and not an index) of pandas Timestamps, you can access many more extra properties and methods with the dt accessor. For instance:

df['date'].dt.year

0    2012
1    2012
2    2015
3    2015
4    2015
Name: date, dtype: int64

We can use this to form our groups and calculate some aggregations on a particular column:

df.groupby(df['date'].dt.year)['a'].agg(['sum', 'mean', 'max'])

      sum  mean  max
date                
2012   14     7    9
2015    6     2    3

put date in index and use anonymous function to access year

If you set the date column as the index, it becomes a DateTimeIndex with the same properties and methods as the dt accessor gives normal columns

df1 = df.set_index('date')
df1.index.year

Int64Index([2012, 2012, 2015, 2015, 2015], dtype='int64', name='date')

Interestingly, when using the groupby method, you can pass it a function. This function will be implicitly passed the DataFrame's index. So, we can get the same result from above with the following:

df1.groupby(lambda x: x.year)['a'].agg(['sum', 'mean', 'max'])

      sum  mean  max
2012   14     7    9
2015    6     2    3

Use the resample method

If your date column is not in the index, you must specify the column with the on parameter. You also need to specify the offset alias as a string.

df.resample('AS', on='date')['a'].agg(['sum', 'mean', 'max'])

             sum  mean  max
date                       
2012-01-01  14.0   7.0  9.0
2013-01-01   NaN   NaN  NaN
2014-01-01   NaN   NaN  NaN
2015-01-01   6.0   2.0  3.0

Convert to pandas Period

You can also convert the date column to a pandas Period object. We must pass in the offset alias as a string to determine the length of the Period.

df['date'].dt.to_period('A')

0   2012
1   2012
2   2015
3   2015
4   2015
Name: date, dtype: object

We can then use this as a group

df.groupby(df['date'].dt.to_period('Y'))['a'].agg(['sum', 'mean', 'max'])


      sum  mean  max
2012   14     7    9
2015    6     2    3

Why can't I center with margin: 0 auto?

Why not?

#header {
    text-align: center;
}

#header ul {
    display: inline;
}

Replace text inside td using jQuery having td containing other elements

Wrap your to be deleted contents within a ptag, then you can do something like this:

$(function(){
  $("td").click(function(){ console.log($("td").find("p"));
    $("td").find("p").remove();    });
});

FIDDLE DEMO: http://jsfiddle.net/y3p2F/

How to read from standard input in the console?

Try this code:-

var input string
func main() {
      fmt.Print("Enter Your Name=")
      fmt.Scanf("%s",&input)
      fmt.Println("Hello "+input)
      }

How can I compile and run c# program without using visual studio?

There are different ways for this:

1.Building C# Applications Using csc.exe

While it is true that you might never decide to build a large-scale application using nothing but the C# command-line compiler, it is important to understand the basics of how to compile your code files by hand.

2.Building .NET Applications Using Notepad++

Another simple text editor Iā€™d like to quickly point out is the freely downloadable Notepad++ application. This tool can be obtained from http://notepad-plus.sourceforge.net. Unlike the primitive Windows Notepad application, Notepad++ allows you to author code in a variety of languages and supports

3.Building .NET Applications Using SharpDevelop

As you might agree, authoring C# code with Notepad++ is a step in the right direction, compared to Notepad. However, these tools do not provide rich IntelliSense capabilities for C# code, designers for building graphical user interfaces, project templates, or database manipulation utilities. To address such needs, allow me to introduce the next .NET development option: SharpDevelop (also known as "#Develop").You can download it from http://www.sharpdevelop.com.

JPA or JDBC, how are they different?

Main difference between JPA and JDBC is level of abstraction.

JDBC is a low level standard for interaction with databases. JPA is higher level standard for the same purpose. JPA allows you to use an object model in your application which can make your life much easier. JDBC allows you to do more things with the Database directly, but it requires more attention. Some tasks can not be solved efficiently using JPA, but may be solved more efficiently with JDBC.

Is there a wikipedia API just for retrieve content summary?

There is actually a very nice prop called extracts that can be used with queries designed specifically for this purpose. Extracts allow you to get article extracts (truncated article text). There is a parameter called exintro that can be used to retrieve the text in the zeroth section (no additional assets like images or infoboxes). You can also retrieve extracts with finer granularity such as by a certain number of characters (exchars) or by a certain number of sentences(exsentences)

Here is a sample query http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&titles=Stack%20Overflow and the API sandbox http://en.wikipedia.org/wiki/Special:ApiSandbox#action=query&prop=extracts&format=json&exintro=&titles=Stack%20Overflow to experiment more with this query.

Please note that if you want the first paragraph specifically you still need to do some additionally parsing as suggested in the chosen answer. The difference here is that the response returned by this query is shorter than some of the other api queries suggested because you don't have additional assets such as images in the api response to parse.

How to abort makefile if variable not set?

Use the shell function test:

foo:
    test $(something)

Usage:

$ make foo
test 
Makefile:2: recipe for target 'foo' failed
make: *** [foo] Error 1
$ make foo something=x
test x

How do I disable the resizable property of a textarea?

This can be done in HTML easily:

<textarea name="textinput" draggable="false"></textarea>

This works for me. The default value is true for the draggable attribute.

Does a VPN Hide my Location on Android?

Your question can be conveniently divided into several parts:

Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.

How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.

You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):

  1. Download and install a trusted VPN.

  2. Install the VPN on your Android device.

  3. Open the application and connect to a server in a different country.

  4. Your Android location will now be successfully changed!

Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.

Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.

How to sort a data frame by alphabetic order of a character variable in R?

The order() function fails when the column has levels or factor. It works properly when stringsAsFactors=FALSE is used in data.frame creation.

What is Node.js' Connect, Express and "middleware"?

[Update: As of its 4.0 release, Express no longer uses Connect. However, Express is still compatible with middleware written for Connect. My original answer is below.]

I'm glad you asked about this, because it's definitely a common point of confusion for folks looking at Node.js. Here's my best shot at explaining it:

  • Node.js itself offers an http module, whose createServer method returns an object that you can use to respond to HTTP requests. That object inherits the http.Server prototype.

  • Connect also offers a createServer method, which returns an object that inherits an extended version of http.Server. Connect's extensions are mainly there to make it easy to plug in middleware. That's why Connect describes itself as a "middleware framework," and is often analogized to Ruby's Rack.

  • Express does to Connect what Connect does to the http module: It offers a createServer method that extends Connect's Server prototype. So all of the functionality of Connect is there, plus view rendering and a handy DSL for describing routes. Ruby's Sinatra is a good analogy.

  • Then there are other frameworks that go even further and extend Express! Zappa, for instance, which integrates support for CoffeeScript, server-side jQuery, and testing.

Here's a concrete example of what's meant by "middleware": Out of the box, none of the above serves static files for you. But just throw in connect.static (a middleware that comes with Connect), configured to point to a directory, and your server will provide access to the files in that directory. Note that Express provides Connect's middlewares also; express.static is the same as connect.static. (Both were known as staticProvider until recently.)

My impression is that most "real" Node.js apps are being developed with Express these days; the features it adds are extremely useful, and all of the lower-level functionality is still there if you want it.

"Unable to launch the IIS Express Web server" error

In Debug > Website Properties.

change port number in Project Url to any nearest value and save

enter image description here

document .click function for touch device

To trigger the function with click or touch, you could change this:

$(document).click( function () {

To this:

$(document).on('click touchstart', function () {

Or this:

$(document).on('click touch', function () {

The touchstart event fires as soon as an element is touched, the touch event is more like a "tap", i.e. a single contact on the surface. You should really try each of these to see what works best for you. On some devices, touch can be a little harder to trigger (which may be a good or bad thing - it prevents a drag being counted, but an accidental small drag may cause it to not be fired).

Permission denied when launch python script via bash

#strace ./scripts/replace-md5sums.py

How to get current PHP page name

You can use basename() and $_SERVER['PHP_SELF'] to get current page file name

echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */

How to export datagridview to excel using vb.net?

Excel Method

This method is different than many you will see. Others use a loop to write each cell and write the cells with text data type.

This method creates an object array from a DataTable or DataGridView and then writes the array to Excel. This means I can write to Excel without a loop and retain data types.

I extracted this from my library and I think I changed it enough to work with this code only, but more minor tweaking might be necessary. If you get errors just let me know and I'll correct them for you. Normally, I create an instance of my class and call these methods. If you would like to use my library then use this link to download it and if you need help just let me know.
https://zomp.co/Files.aspx?ID=zExcel


After copying the code to your solution you will use it like this.

In your button code add this and change the names to your controls.

WriteDataGrid("Sheet1", grid)

To open your file after exporting use this line

System.Diagnostics.Process.Start("The location and filename of your file")

In the WriteArray method you'll want to change the line that saves the workbook to where you want to save it. Probably makes sense to add this as a parameter.

wb.SaveAs("C:\MyWorkbook.xlsx")


Public Function WriteArray(Sheet As String, ByRef ObjectArray As Object(,)) As String
    Try
        Dim xl As Excel.Application = New Excel.Application
        Dim wb As Excel.Workbook = xl.Workbooks.Add()
        Dim ws As Excel.Worksheet = wb.Worksheets.Add()
        ws.Name = Sheet
        Dim range As Excel.Range = ws.Range("A1").Resize(ObjectArray.GetLength(0), ObjectArray.GetLength(1))
        range.Value = ObjectArray

        range = ws.Range("A1").Resize(1, ObjectArray.GetLength(1) - 1)

        range.Interior.Color = RGB(0, 70, 132)  'Con-way Blue
        range.Font.Color = RGB(Drawing.Color.White.R, Drawing.Color.White.G, Drawing.Color.White.B)
        range.Font.Bold = True
        range.WrapText = True

        range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter
        range.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter

        range.Application.ActiveWindow.SplitColumn = 0
        range.Application.ActiveWindow.SplitRow = 1
        range.Application.ActiveWindow.FreezePanes = True

        wb.SaveAs("C:\MyWorkbook.xlsx")
        wb.CLose()
        xl.Quit()
        xl = Nothing
        wb = Nothing
        ws  = Nothing
        range = Nothing
        ReleaseComObject(xl)
        ReleaseComObject(wb)
        ReleaseComObject(ws)
        ReleaseComObject(range)

        Return ""
    Catch ex As Exception
        Return "WriteArray()" & Environment.NewLine & Environment.NewLine & ex.Message
    End Try
End Function

Public Function WriteDataGrid(SheetName As String, ByRef dt As DataGridView) As String
        Try
            Dim l(dt.Rows.Count + 1, dt.Columns.Count) As Object
            For c As Integer = 0 To dt.Columns.Count - 1
                l(0, c) = dt.Columns(c).HeaderText
            Next

            For r As Integer = 1 To dt.Rows.Count
                For c As Integer = 0 To dt.Columns.Count - 1
                    l(r, c) = dt.Rows(r - 1).Cells(c)
                Next
            Next

            Dim errors As String = WriteArray(SheetName, l)
            If errors <> "" Then
                Return errors
            End If

            Return ""
        Catch ex As Exception
            Return "WriteDataGrid()" & Environment.NewLine & Environment.NewLine & ex.Message
        End Try
    End Function


 Public Function WriteDataTable(SheetName As String, ByRef dt As DataTable) As String
        Try
            Dim l(dt.Rows.Count + 1, dt.Columns.Count) As Object
            For c As Integer = 0 To dt.Columns.Count - 1
                l(0, c) = dt.Columns(c).ColumnName
            Next

            For r As Integer = 1 To dt.Rows.Count
                For c As Integer = 0 To dt.Columns.Count - 1
                    l(r, c) = dt.Rows(r - 1).Item(c)
                Next
            Next

            Dim errors As String = WriteArray(SheetName, l)
            If errors <> "" Then
                Return errors
            End If

            Return ""
        Catch ex As Exception
            Return "WriteDataTable()" & Environment.NewLine & Environment.NewLine & ex.Message
        End Try
    End Function

I actually don't use this method in my Database program because it's a slow method when you have a lot of rows/columns. I instead create a CSV from the DataGridView. Writing to Excel with Excel Automation is only useful if you need to format the data and cells otherwise you should use CSV. You can use the code after the image for CSV export.


CSV Method

Private Sub DataGridToCSV(ByRef dt As DataGridView, Qualifier As String)  
        Dim TempDirectory As String = "A temp Directory"  
        System.IO.Directory.CreateDirectory(TempDirectory)
        Dim oWrite As System.IO.StreamWriter
        Dim file As String = System.IO.Path.GetRandomFileName & ".csv"
        oWrite = IO.File.CreateText(TempDirectory & "\" & file)

        Dim CSV As StringBuilder = New StringBuilder()

        Dim i As Integer = 1
        Dim CSVHeader As StringBuilder = New StringBuilder()
        For Each c As DataGridViewColumn In dt.Columns
            If i = 1 Then
                CSVHeader.Append(Qualifier & c.HeaderText.ToString() & Qualifier)
            Else
                CSVHeader.Append("," & Qualifier & c.HeaderText.ToString() & Qualifier)
            End If
            i += 1
        Next

        'CSV.AppendLine(CSVHeader.ToString())
        oWrite.WriteLine(CSVHeader.ToString())
        oWrite.Flush()

        For r As Integer = 0 To dt.Rows.Count - 1

            Dim CSVLine As StringBuilder = New StringBuilder()
            Dim s As String = ""
            For c As Integer = 0 To dt.Columns.Count - 1
                If c = 0 Then
                    'CSVLine.Append(Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier)
                    s = s & Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier
                Else
                    'CSVLine.Append("," & Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier)
                    s = s & "," & Qualifier & gridResults.Rows(r).Cells(c).Value.ToString() & Qualifier
                End If

            Next
            oWrite.WriteLine(s)
            oWrite.Flush()
            'CSV.AppendLine(CSVLine.ToString())
            'CSVLine.Clear()
        Next

        'oWrite.Write(CSV.ToString())

        oWrite.Close()
        oWrite = Nothing    

        System.Diagnostics.Process.Start(TempDirectory & "\" & file)   

        GC.Collect()

    End Sub

Pandas split column of lists into multiple columns

The above solutions didn't work for me since I have nan observations in my dataframe. In my case df2[['team1','team2']] = pd.DataFrame(df2.teams.values.tolist(), index= df2.index) yields:

object of type 'float' has no len()

I solve this using list comprehension. Here the replicable example:

import pandas as pd
import numpy as np
d1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],
            ['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]}
df2 = pd.DataFrame(d1)
df2.loc[2,'teams'] = np.nan
df2.loc[4,'teams'] = np.nan
df2

output:

        teams
0   [SF, NYG]
1   [SF, NYG]
2   NaN
3   [SF, NYG]
4   NaN
5   [SF, NYG]
6   [SF, NYG]

df2['team1']=np.nan
df2['team2']=np.nan

solving with list comprehension:

for i in [0,1]:
    df2['team{}'.format(str(i+1))]=[k[i] if isinstance(k,list) else k for k in df2['teams']]

df2

yields:

    teams   team1   team2
0   [SF, NYG]   SF  NYG
1   [SF, NYG]   SF  NYG
2   NaN        NaN  NaN
3   [SF, NYG]   SF  NYG
4   NaN        NaN  NaN
5   [SF, NYG]   SF  NYG
6   [SF, NYG]   SF  NYG

What is the difference between Builder Design pattern and Factory Design pattern?

The main difference between them is that the Builder pattern primarily describes the creation of complex objects step by step. In the Abstract Factory pattern, the emphasis is on families of objects-products. Builder returns the product in the last step. While in the Abstract Factory pattern the product is available immediately.

Example: Let say that we are creating Maze

1. Abstract Factory:

Maze* MazeGame::CreateMaze (MazeFactory& factory) {
Maze* maze = factory.MakeMaze(); /// product is available at start!!
 /* Call some methods on maze */
return maze;
}

2. Builder:

Maze* MazeGame::CreateMaze (MazeBuilder& builder) {
builder.buildMaze(); /// We don't have access to maze
 /* Call some methods on builder */
return builder.GetMaze();
}

How can I repeat a character in Bash?

Simplest is to use this one-liner in bash:

seq 10 | xargs -n 1 | xargs -I {} echo -n  ===\>;echo

Jquery set radio button checked, using id and class selectors

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

/bin/sh: apt-get: not found

The image you're using is Alpine based, so you can't use apt-get because it's Ubuntu's package manager.

To fix this just use:

apk update and apk add

How do I create a SQL table under a different schema?

Hit F4 and you'll get what you are looking for.

Passing by reference in C

Because you're passing a pointer(memory address) to the variable p into the function f. In other words you are passing a pointer not a reference.

What is causing "Unable to allocate memory for pool" in PHP?

For newbies like myself, these resources helped:

Finding the apc.ini file to make the changes recommended by c33s above, and setting recommended amounts: http://www.untwistedvortex.com/optimizing-tuning-apc-alternate-php-cache/

Understanding what apc.ttl is: http://www.php.net/manual/en/apc.configuration.php#ini.apc.ttl

Understanding what apc.shm_size is: http://www.php.net/manual/en/apc.configuration.php#ini.apc.shm-size

How do I add space between items in an ASP.NET RadioButtonList

I know this is an old question but I did it like:

<asp:RadioButtonList runat="server" ID="myrbl" RepeatDirection="Horizontal" CssClass="rbl"> 

Use this as your class:

.rbl input[type="radio"]
{
   margin-left: 10px;
   margin-right: 1px;
}

jQuery - Create hidden form element on the fly

Working JSFIDDLE

If your form is like

<form action="" method="get" id="hidden-element-test">
      First name: <input type="text" name="fname"><br>
      Last name: <input type="text" name="lname"><br>
      <input type="submit" value="Submit">
</form> 
    <br><br>   
    <button id="add-input">Add hidden input</button>
    <button id="add-textarea">Add hidden textarea</button>

You can add hidden input and textarea to form like this

$(document).ready(function(){

    $("#add-input").on('click', function(){
        $('#hidden-element-test').prepend('<input type="hidden" name="ipaddress" value="192.168.1.201" />');
        alert('Hideen Input Added.');
    });

    $("#add-textarea").on('click', function(){
        $('#hidden-element-test').prepend('<textarea name="instructions" style="display:none;">this is a test textarea</textarea>');
        alert('Hideen Textarea Added.');
    });

});

Check working jsfiddle here

How can I convert a string to an int in Python?

Don't use str() method directly in html instead use with y=x|string()

<div class="row">
    {% for x in range(photo_upload_count) %}
        {% with y=x|string() %}

    <div col-md-4 >
        <div class="col-md-12">
            <div class="card card-primary "  style="border:1px solid #000">
                <div class="card-body">
                    {% if data['profile_photo']!= None: %}
                        <img class="profile-user-img img-responsive" src="{{ data['photo_'+y] }}" width="200px" alt="User profile picture">
                    {% else: %}
                        <img class="profile-user-img img-responsive" src="static/img/user.png" width="200px" alt="User profile picture">
                    {% endif %}
                </div>
                <div class="card-footer text-center">
                    <a href="{{value}}edit_photo/{{ 'photo_'+y }}" class="btn btn-primary">Edit</a>
                </div>
            </div>
        </div>
    </div>
    {% endwith %}
    {% endfor %}
</div>

How can I disable editing cells in a WPF Datagrid?

The DataGrid has an XAML property IsReadOnly that you can set to true:

<my:DataGrid
    IsReadOnly="True"
/>

Excel - Combine multiple columns into one column

You can combine the columns without using macros. Type the following function in the formula bar:

=IF(ROW()<=COUNTA(A:A),INDEX(A:A,ROW()),IF(ROW()<=COUNTA(A:B),INDEX(B:B,ROW()-COUNTA(A:A)),IF(ROW()>COUNTA(A:C),"",INDEX(C:C,ROW()-COUNTA(A:B)))))

The statement uses 3 IF functions, because it needs to combine 3 columns:

  • For column A, the function compares the row number of a cell with the total number of cells in A column that are not empty. If the result is true, the function returns the value of the cell from column A that is at row(). If the result is false, the function moves on to the next IF statement.
  • For column B, the function compares the row number of a cell with the total number of cells in A:B range that are not empty. If the result is true, the function returns the value of the first cell that is not empty in column B. If false, the function moves on to the next IF statement.
  • For column C, the function compares the row number of a cell with the total number of cells in A:C range that are not empty. If the result is true, the function returns a blank cell and doesn't do any more calculation. If false, the function returns the value of the first cell that is not empty in column C.

Create zip file and ignore directory structure

Alternatively, you could create a temporary symbolic link to your file:

ln -s /data/to/zip/data.txt data.txt
zip /dir/to/file/newZip !$
rm !$

This works also for a directory.

How do I convert from stringstream to string in C++?

Use the .str()-method:

Manages the contents of the underlying string object.

1) Returns a copy of the underlying string as if by calling rdbuf()->str().

2) Replaces the contents of the underlying string as if by calling rdbuf()->str(new_str)...

Notes

The copy of the underlying string returned by str is a temporary object that will be destructed at the end of the expression, so directly calling c_str() on the result of str() (for example in auto *ptr = out.str().c_str();) results in a dangling pointer...

Valid characters of a hostname?

If you're registering a domain and the termination (ex .com) it is not IDN, as Aaron Hathaway said: Hostnames are composed of series of labels concatenated with dots, as are all domain names. For example, en.wikipedia.org is a hostname. Each label must be between 1 and 63 characters long, and the entire hostname (including the delimiting dots but not a trailing dot) has a maximum of 253 ASCII characters.

The Internet standards (Requests for Comments) for protocols mandate that component hostname labels may contain only the ASCII letters a through z (in a case-insensitive manner), the digits 0 through 9, and the hyphen -. The original specification of hostnames in RFC 952, mandated that labels could not start with a digit or with a hyphen, and must not end with a hyphen. However, a subsequent specification (RFC 1123) permitted hostname labels to start with digits. No other symbols, punctuation characters, or white space are permitted.

Later, Spain with it's .es, .com.es, .org.es, .nom,es, .gob.es and .edu.es introduced IDN tlds, if your tld is one of .es or any other that supports it, any character can be used, but you can't combine alphabets like Latin, Greek or Cyril in one hostname, and that it respects the things that can't go at the start or at the end.

If you're using non-registered tlds, just for local networking, like with local DNS or with hosts files, you can treat them all as IDN.

Keep in mind some programs could not work well, especially old, outdated and unpopular ones.

What's the difference between :: (double colon) and -> (arrow) in PHP?

The difference between static and instantiated methods and properties seem to be one of the biggest obstacles to those just starting out with OOP PHP in PHP 5.

The double colon operator (which is called the Paamayim Nekudotayim from Hebrew - trivia) is used when calling an object or property from a static context. This means an instance of the object has not been created yet.

The arrow operator, conversely, calls methods or properties that from a reference of an instance of the object.

Static methods can be especially useful in object models that are linked to a database for create and delete methods, since you can set the return value to the inserted table id and then use the constructor to instantiate the object by the row id.

Provide static IP to docker containers via docker-compose

I was facing some difficulties with an environment variable that is with custom name (not with container name /port convention for KAPACITOR_BASE_URL and KAPACITOR_ALERTS_ENDPOINT). If we give service name in this case it wouldn't resolve the ip as

KAPACITOR_BASE_URL:  http://kapacitor:9092

In above http://[**kapacitor**]:9092 would not resolve to http://172.20.0.2:9092

I resolved the static IPs issues using subnetting configurations.

version: "3.3"

networks:
  frontend:
    ipam:
      config:
        - subnet: 172.20.0.0/24
services:
    db:
        image: postgres:9.4.4
        networks:
            frontend:
                ipv4_address: 172.20.0.5
        ports:
            - "5432:5432"
        volumes:
            - postgres_data:/var/lib/postgresql/data

    redis:
        image: redis:latest
        networks:
            frontend:
                ipv4_address: 172.20.0.6
        ports:
            - "6379"

    influxdb:
        image: influxdb:latest
        ports:
            - "8086:8086"
            - "8083:8083"
        volumes:
            - ../influxdb/influxdb.conf:/etc/influxdb/influxdb.conf
            - ../influxdb/inxdb:/var/lib/influxdb
        networks:
            frontend:
                ipv4_address: 172.20.0.4
        environment:
          INFLUXDB_HTTP_AUTH_ENABLED: "false"
          INFLUXDB_ADMIN_ENABLED: "true"
          INFLUXDB_USERNAME: "db_username"
          INFLUXDB_PASSWORD: "12345678"
          INFLUXDB_DB: db_customers

    kapacitor:
        image: kapacitor:latest
        ports: 
            - "9092:9092"
        networks:
            frontend:
                ipv4_address: 172.20.0.2
        depends_on:
            - influxdb
        volumes:
            - ../kapacitor/kapacitor.conf:/etc/kapacitor/kapacitor.conf
            - ../kapacitor/kapdb:/var/lib/kapacitor
        environment:
          KAPACITOR_INFLUXDB_0_URLS_0: http://influxdb:8086

    web:
        build: .
        environment:
          RAILS_ENV: $RAILS_ENV
        command: bundle exec rails s -b 0.0.0.0
        ports:
            - "3000:3000"
        networks:
            frontend:
                ipv4_address: 172.20.0.3
        links:
            - db
            - kapacitor
        depends_on:
            - db
        volumes:
            - .:/var/app/current
        environment:
          DATABASE_URL: postgres://postgres@db
          DATABASE_USERNAME: postgres
          DATABASE_PASSWORD: postgres
          INFLUX_URL: http://influxdb:8086
          INFLUX_USER: db_username
          INFLUX_PWD: 12345678
          KAPACITOR_BASE_URL:  http://172.20.0.2:9092
          KAPACITOR_ALERTS_ENDPOINT: http://172.20.0.3:3000

volumes:
  postgres_data:

Override browser form-filling and input highlighting with HTML/CSS

Autocomplete off is not supported by modern browsers. The easiest way to solve autocomplete I found was a little track with HTML and JS. The first thing to do is change the type of the input in HTML from 'password' to 'text'.

<input class="input input-xxl input-watery" type="text" name="password"/>

Autocomplete starts after window loaded. That's OK. But when the type of your field is not 'password', browser didn`t know what fields it must complete. So, there will be no autocomplete on form fields.

After that, bind event focusin to password field, for ex. in Backbone:

'focusin input[name=password]': 'onInputPasswordFocusIn',

In onInputPasswordFocusIn, just change the type of your field to password, by simple check:

if (e.currentTarget.value === '') {
    $(e.currentTarget).attr('type', 'password');
}

That`s it!

UPD: this thing doesn't work with disabled JavaSciprt

UPD in 2018. Also found some funny trick. Set readonly attribute to the input field, and remove it on the focus event. First prevent browser from autofilling fields, second will allow to input data.

How to convert a string to integer in C?

Ok, I had the same problem.I came up with this solution.It worked for me the best.I did try atoi() but didn't work well for me.So here is my solution:

void splitInput(int arr[], int sizeArr, char num[])
{
    for(int i = 0; i < sizeArr; i++)
        // We are subtracting 48 because the numbers in ASCII starts at 48.
        arr[i] = (int)num[i] - 48;
}

What exactly does numpy.exp() do?

The exponential function is e^x where e is a mathematical constant called Euler's number, approximately 2.718281. This value has a close mathematical relationship with pi and the slope of the curve e^x is equal to its value at every point. np.exp() calculates e^x for each value of x in your input array.

Why are primes important in cryptography?

One more resource for you. Security Now! episode 30(~30 minute podcast, link is to the transcript) talks about cryptography issues, and explains why primes are important.

How to split a string and assign it to variables

Golang does not support implicit unpacking of an slice (unlike python) and that is the reason this would not work. Like the examples given above, we would need to workaround it.

One side note:

The implicit unpacking happens for variadic functions in go:

func varParamFunc(params ...int) {

}

varParamFunc(slice1...)

How to round up value C# to the nearest integer?

Another option:

string strVal = "32.11"; // will return 33
// string strVal = "32.00" // returns 32
// string strVal = "32.98" // returns 33

string[] valStr = strVal.Split('.');

int32 leftSide = Convert.ToInt32(valStr[0]);
int32 rightSide = Convert.ToInt32(valStr[1]);

if (rightSide > 0)
    leftSide = leftSide + 1;


return (leftSide);

Can I replace groups in Java regex?

Here is a different solution, that also allows the replacement of a single group in multiple matches. It uses stacks to reverse the execution order, so the string operation can be safely executed.

private static void demo () {

    final String sourceString = "hello world!";

    final String regex = "(hello) (world)(!)";
    final Pattern pattern = Pattern.compile(regex);

    String result = replaceTextOfMatchGroup(sourceString, pattern, 2, world -> world.toUpperCase());
    System.out.println(result);  // output: hello WORLD!
}

public static String replaceTextOfMatchGroup(String sourceString, Pattern pattern, int groupToReplace, Function<String,String> replaceStrategy) {
    Stack<Integer> startPositions = new Stack<>();
    Stack<Integer> endPositions = new Stack<>();
    Matcher matcher = pattern.matcher(sourceString);

    while (matcher.find()) {
        startPositions.push(matcher.start(groupToReplace));
        endPositions.push(matcher.end(groupToReplace));
    }
    StringBuilder sb = new StringBuilder(sourceString);
    while (! startPositions.isEmpty()) {
        int start = startPositions.pop();
        int end = endPositions.pop();
        if (start >= 0 && end >= 0) {
            sb.replace(start, end, replaceStrategy.apply(sourceString.substring(start, end)));
        }
    }
    return sb.toString();       
}

Finding square root without using sqrt function?

This a very simple recursive approach.

double mySqrt(double v, double test) {
    if (abs(test * test - v) < 0.0001) {
        return test;
    }

    double highOrLow = v / test;
    return mySqrt(v, (test + highOrLow) / 2.0);
}
double mySqrt(double v) {
    return mySqrt(v, v/2.0);
}

Is it .yaml or .yml?

After reading a bunch of people's comments online about this, my first reaction was that this is basically one of those really unimportant debates. However, my initial interest was to find out the right format so I could be consistent with my file naming practice.

Long story short, the creator of YAML are saying .yaml, but personally I keep doing .yml. That just makes more sense to me. So I went on the journey to find affirmation and soon enough, I realise that docker uses .yml everywhere. I've been writing docker-compose.yml files all this time, while you keep seeing in kubernetes' docs kubectl apply -f *.yaml...

So, in conclusion, both formats are obviously accepted and if you are on the other end, (ie: writing systems that receive a YAML file as input) you should allow for both. That seems like another snake case versus camel case thingy...

What exceptions should be thrown for invalid or unexpected parameters in .NET?

There is a standard ArgumentException that you could use, or you could subclass and make your own. There are several specific ArgumentException classes:

http://msdn.microsoft.com/en-us/library/system.argumentexception(VS.71).aspx

Whichever one works best.

How to convert object array to string array in Java

You can use type-converter. To convert an array of any types to array of strings you can register your own converter:

 TypeConverter.registerConverter(Object[].class, String[].class, new Converter<Object[], String[]>() {

        @Override
        public String[] convert(Object[] source) {
            String[] strings = new String[source.length];
            for(int i = 0; i < source.length ; i++) {
                strings[i] = source[i].toString();
            }
            return strings;
        }
    });

and use it

   Object[] objects = new Object[] {1, 23.43, true, "text", 'c'};
   String[] strings = TypeConverter.convert(objects, String[].class);

How to install python modules without root access?

No permissions to access nor install easy_install?

Then, you can create a python virtualenv (https://pypi.python.org/pypi/virtualenv) and install the package from this virtual environment.

Executing 4 commands in the shell will be enough (insert current release like 16.1.0 for X.X.X):

$ curl --location --output virtualenv-X.X.X.tar.gz https://github.com/pypa/virtualenv/tarball/X.X.X
$ tar xvfz virtualenv-X.X.X.tar.gz
$ python pypa-virtualenv-YYYYYY/src/virtualenv.py my_new_env
$ . my_new_env/bin/activate
(my_new_env)$ pip install package_name

Source and more info: https://virtualenv.pypa.io/en/latest/installation/

Force browser to refresh css, javascript, etc

Make sure this isn't happening from your DNS. For example Cloudflare has it where you can turn on development mode where it forces a purge on your stylesheets and images as Cloudflare offers accelerated cache. This will disable it and force it to update everytime someone visits your site.

'this' is undefined in JavaScript class methods

Use arrow function:

Request.prototype.start = () => {
    if( this.stay_open == true ) {
        this.open({msg: 'listen'});
    } else {

    }
};

Formatting ISODate from Mongodb

// from MongoDate object to Javascript Date object

var MongoDate = {sec: 1493016016, usec: 650000};
var dt = new Date("1970-01-01T00:00:00+00:00");
    dt.setSeconds(MongoDate.sec);

Create a string with n characters

int c = 10; String spaces = String.format("%" +c+ "c", ' '); this will solve your problem.

How to install lxml on Ubuntu

For Ubuntu 14.04

sudo apt-get install python-lxml

worked for me.

Setting Elastic search limit to "unlimited"

use the scan method e.g.

 curl -XGET 'localhost:9200/_search?search_type=scan&scroll=10m&size=50' -d '
 {
    "query" : {
       "match_all" : {}
     }
 }

see here

Insert a row to pandas dataframe

One way to achieve this is

>>> pd.DataFrame(np.array([[2, 3, 4]]), columns=['A', 'B', 'C']).append(df, ignore_index=True)
Out[330]: 
   A  B  C
0  2  3  4
1  5  6  7
2  7  8  9

Generally, it's easiest to append dataframes, not series. In your case, since you want the new row to be "on top" (with starting id), and there is no function pd.prepend(), I first create the new dataframe and then append your old one.

ignore_index will ignore the old ongoing index in your dataframe and ensure that the first row actually starts with index 1 instead of restarting with index 0.

Typical Disclaimer: Cetero censeo ... appending rows is a quite inefficient operation. If you care about performance and can somehow ensure to first create a dataframe with the correct (longer) index and then just inserting the additional row into the dataframe, you should definitely do that. See:

>>> index = np.array([0, 1, 2])
>>> df2 = pd.DataFrame(columns=['A', 'B', 'C'], index=index)
>>> df2.loc[0:1] = [list(s1), list(s2)]
>>> df2
Out[336]: 
     A    B    C
0    5    6    7
1    7    8    9
2  NaN  NaN  NaN
>>> df2 = pd.DataFrame(columns=['A', 'B', 'C'], index=index)
>>> df2.loc[1:] = [list(s1), list(s2)]

So far, we have what you had as df:

>>> df2
Out[339]: 
     A    B    C
0  NaN  NaN  NaN
1    5    6    7
2    7    8    9

But now you can easily insert the row as follows. Since the space was preallocated, this is more efficient.

>>> df2.loc[0] = np.array([2, 3, 4])
>>> df2
Out[341]: 
   A  B  C
0  2  3  4
1  5  6  7
2  7  8  9