Programs & Examples On #Zoho

Zoho is a SaaS based company which offers a comprehensive suite of on-line business, productivity & collaboration applications.

How to embed fonts in CSS?

I used Ataturk's font like this. I didn't use "TTF" version. I translated orginal font version ("otf" version) to "eot" and "woof" version. Then It works in local but not working when I uploaded the files to server. So I added "TTF" version too like this. Now, It's working on Chrome and Firefox but Internet Explorer still defence. When you installed on your computer "Ataturk" font, then working IE too. But I wanted to use this font without installing.

@font-face {
    font-family: 'Ataturk';
    font-style: normal;
    font-weight: normal;
    src: url('font/ataturk.eot');
    src: local('Ataturk Regular'), url('font/ataturk.ttf') format('truetype'), 
    url('font/ataturk.woff') format('woff');
}

You can see it on my website here: http://www.canotur.com

Changing iframe src with Javascript

change onselect to onchange in inputs and use

calendar.src = loc

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
_x000D_
<head>_x000D_
  <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />_x000D_
  <title>Untitled 1</title>_x000D_
_x000D_
  <script>_x000D_
  function go(loc) {_x000D_
    calendar.src = loc;_x000D_
  }_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <iframe id="calendar" src="about:blank" width="1000" height="450" frameborder="0" scrolling="no"></iframe>_x000D_
_x000D_
  <form method="post">_x000D_
    <input name="calendarSelection" type="radio" onchange="go('https://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Day_x000D_
    <input name="calendarSelection" type="radio" onchange="go('https://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Week_x000D_
    <input name="calendarSelection" type="radio" onchange="go('https://calendar.zoho.com/embed/9a6054c98fd2ad4047021cff76fee38773c34a35234fa42d426b9510864356a68cabcad57cbbb1a0?title=Kevin_Calendar&type=1&l=en&tz=America/Los_Angeles&sh=[0,0]&v=1')" />Month_x000D_
  </form>_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I make a multipart/form-data POST request using Java?

Use this code to upload images or any other files to the server using post in multipart.

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class SimplePostRequestTest {

    public static void main(String[] args) throws UnsupportedEncodingException, IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://192.168.0.102/uploadtest/upload_photo");

        try {
            FileBody bin = new FileBody(new File("/home/ubuntu/cd.png"));
            StringBody id = new StringBody("3");
            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("upload_image", bin);
            reqEntity.addPart("id", id);
            reqEntity.addPart("image_title", new StringBody("CoolPic"));

            httppost.setEntity(reqEntity);
            System.out.println("Requesting : " + httppost.getRequestLine());
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httppost, responseHandler);
            System.out.println("responseBody : " + responseBody);

        } catch (ClientProtocolException e) {

        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }

}

it requires below files to upload.

libraries are httpclient-4.1.2.jar, httpcore-4.1.2.jar, httpmime-4.1.2.jar, httpclient-cache-4.1.2.jar, commons-codec.jar and commons-logging-1.1.1.jar to be in classpath.

Constructors in Go

Go has objects. Objects can have constructors (although not automatic constructors). And finally, Go is an OOP language (data types have methods attached, but admittedly there are endless definitions of what OOP is.)

Nevertheless, the accepted best practice is to write zero or more constructors for your types.

As @dystroy posted his answer before me finishing this answer, let me just add an alternative version of his example constructor, which I would probably write instead as:

func NewThing(someParameter string) *Thing {
    return &Thing{someParameter, 33} // <- 33: a very sensible default value
}

The reason I want to show you this version is that pretty often "inline" literals can be used instead of a "constructor" call.

a := NewThing("foo")
b := &Thing{"foo", 33}

Now *a == *b.

Force git stash to overwrite added files

TL;DR:

git checkout HEAD path/to/file
git stash apply

Long version:

You get this error because of the uncommited changes that you want to overwrite. Undo these changes with git checkout HEAD. You can undo changes to a specific file with git checkout HEAD path/to/file. After removing the cause of the conflict, you can apply as usual.

Maven: How to rename the war file for the project?

Lookup pom.xml > project tag > build tag.

I would like solution below.

<artifactId>bird</artifactId>
<name>bird</name>

<build>
    ...
    <finalName>${project.artifactId}</finalName>
  OR
    <finalName>${project.name}</finalName>
    ...
</build>

Worked for me. ^^

What's the @ in front of a string in C#?

http://msdn.microsoft.com/en-us/library/aa691090.aspx

C# supports two forms of string literals: regular string literals and verbatim string literals.

A regular string literal consists of zero or more characters enclosed in double quotes, as in "hello", and may include both simple escape sequences (such as \t for the tab character) and hexadecimal and Unicode escape sequences.

A verbatim string literal consists of an @ character followed by a double-quote character, zero or more characters, and a closing double-quote character. A simple example is @"hello". In a verbatim string literal, the characters between the delimiters are interpreted verbatim, the only exception being a quote-escape-sequence. In particular, simple escape sequences and hexadecimal and Unicode escape sequences are not processed in verbatim string literals. A verbatim string literal may span multiple lines.

How to change the commit author for one specific commit?

Interactive rebase off of a point earlier in the history than the commit you need to modify (git rebase -i <earliercommit>). In the list of commits being rebased, change the text from pick to edit next to the hash of the one you want to modify. Then when git prompts you to change the commit, use this:

git commit --amend --author="Author Name <[email protected]>" --no-edit

For example, if your commit history is A-B-C-D-E-F with F as HEAD, and you want to change the author of C and D, then you would...

  1. Specify git rebase -i B (here is an example of what you will see after executing the git rebase -i B command)
    • if you need to edit A, use git rebase -i --root
  2. Change the lines for both C and D from pick to edit
  3. Exit the editor (for vim, this would be pressing Esc and then typing :wq).
  4. Once the rebase started, it would first pause at C
  5. You would git commit --amend --author="Author Name <[email protected]>"
  6. Then git rebase --continue
  7. It would pause again at D
  8. Then you would git commit --amend --author="Author Name <[email protected]>" again
  9. git rebase --continue
  10. The rebase would complete.
  11. Use git push -f to update your origin with the updated commits.

Return background color of selected cell

You can use Cell.Interior.Color, I've used it to count the number of cells in a range that have a given background color (ie. matching my legend).

How do I add a bullet symbol in TextView?

This worked for me:

<string name="text_with_bullet">Text with a \u2022</string>

How to get the caller's method name in the called method?

I found a way if you're going across classes and want the class the method belongs to AND the method. It takes a bit of extraction work but it makes its point. This works in Python 2.7.13.

import inspect, os

class ClassOne:
    def method1(self):
        classtwoObj.method2()

class ClassTwo:
    def method2(self):
        curframe = inspect.currentframe()
        calframe = inspect.getouterframes(curframe, 4)
        print '\nI was called from', calframe[1][3], \
        'in', calframe[1][4][0][6: -2]

# create objects to access class methods
classoneObj = ClassOne()
classtwoObj = ClassTwo()

# start the program
os.system('cls')
classoneObj.method1()

How do you execute SQL from within a bash script?

I've used the jdbcsql project on Sourceforge.

On *nix systems, this will create a csv stream of results to standard out:

java -Djava.security.egd=file///dev/urandom -jar jdbcsql.jar -d oracledb_SID -h $host -p 1521 -U some_username -m oracle -P "$PW" -f excel -s "," "$1"

Note that adding the -Djava.security.egd=file///dev/urandom increases performance greatly

Windows commands are similar: see http://jdbcsql.sourceforge.net/

How to get correct timestamp in C#

var timestamp = DateTime.Now.ToFileTime();

//output: 132260149842749745

This is an alternative way to individuate distinct transactions. It's not unix time, but windows filetime.

From the docs:

A Windows file time is a 64-bit value that represents the number of 100- 
nanosecond intervals that have elapsed since 12:00 midnight, January 1, 1601 
A.D. (C.E.) Coordinated Universal Time (UTC).

How to pass in a react component into another react component to transclude the first component's content?

const ParentComponent = (props) => {
  return(
    {props.childComponent}
    //...additional JSX...
  )
}

//import component
import MyComponent from //...where ever

//place in var
const myComponent = <MyComponent />

//pass as prop
<ParentComponent childComponent={myComponent} />

How to truncate float values?

def precision(value, precision):
    """
    param: value: takes a float
    param: precision: int, number of decimal places
    returns a float
    """
    x = 10.0**precision
    num = int(value * x)/ x
    return num
precision(1.923328437452, 3)

1.923

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Another way to wait for maximum of certain amount say 10 seconds of time for the element to be displayed as below:

(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.findElement(By.id("<name>")).isDisplayed();

            }
        });

CSS selector for text input fields?

The attribute selectors are often used for inputs. This is the list of attribute selectors:

[title] All elements with the title attribute are selected.

[title=banana] All elements which have the 'banana' value of the title attribute.

[title~=banana] All elements which contain 'banana' in the value of the title attribute.

[title|=banana] All elements which value of the title attribute starts with 'banana'.

[title^=banana] All elements which value of the title attribute begins with 'banana'.

[title$=banana] All elements which value of the title attribute ends with 'banana'.

[title*=banana] All elements which value of the title attribute contains the substring 'banana'.

Reference: https://kolosek.com/css-selectors/

Error :The remote server returned an error: (401) Unauthorized

Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?

Something like request.Credentials = new NetworkCredential("UserName", "PassWord");

Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;

How to symbolicate crash log Xcode?

There is an easier way using Xcode (without using command line tools and looking up addresses one at a time)

  1. Take any .xcarchive file. If you have one from before you can use that. If you don't have one, create one by running the Product > Archive from Xcode.

  2. Right click on the .xcarchive file and select 'Show Package Contents'

  3. Copy the dsym file (of the version of the app that crashed) to the dSYMs folder

  4. Copy the .app file (of the version of the app that crashed) to the Products > Applications folder

  5. Edit the Info.plist and edit the CFBundleShortVersionString and CFBundleVersion under the ApplicationProperties dictionary. This will help you identify the archive later

  6. Double click the .xcarchive to import it to Xcode. It should open Organizer.

  7. Go back to the crash log (in Devices window in Xcode)

  8. Drag your .crash file there (if not already present)

  9. The entire crash log should now be symbolicated. If not, then right click and select 'Re-symbolicate crash log'

Convert python long/int to fixed size byte array

long/int to the byte array looks like exact purpose of struct.pack. For long integers that exceed 4(8) bytes, you can come up with something like the next:

>>> limit = 256*256*256*256 - 1
>>> i = 1234567890987654321
>>> parts = []
>>> while i:
        parts.append(i & limit)
        i >>= 32

>>> struct.pack('>' + 'L'*len(parts), *parts )
'\xb1l\x1c\xb1\x11"\x10\xf4'

>>> struct.unpack('>LL', '\xb1l\x1c\xb1\x11"\x10\xf4')
(2976652465L, 287445236)
>>> (287445236L << 32) + 2976652465L
1234567890987654321L

How to edit nginx.conf to increase file size upload

First Navigate the Path of php.ini

sudo vi /etc/php/7.2/fpm/php.ini

then, next change

upload_max_filesize = 999M
post_max_size = 999M

then ESC-->:wq

Now Lastly Paste this command,

sudo systemctl restart php7.2-fpm.service

you are done.

Re-ordering columns in pandas dataframe based on column name

Tweet's answer can be passed to BrenBarn's answer above with

data.reindex_axis(sorted(data.columns, key=lambda x: float(x[1:])), axis=1)

So for your example, say:

vals = randint(low=16, high=80, size=25).reshape(5,5)
cols = ['Q1.3', 'Q6.1', 'Q1.2', 'Q9.1', 'Q10.2']
data = DataFrame(vals, columns = cols)

You get:

data

    Q1.3    Q6.1    Q1.2    Q9.1    Q10.2
0   73      29      63      51      72
1   61      29      32      68      57
2   36      49      76      18      37
3   63      61      51      30      31
4   36      66      71      24      77

Then do:

data.reindex_axis(sorted(data.columns, key=lambda x: float(x[1:])), axis=1)

resulting in:

data


     Q1.2    Q1.3    Q6.1    Q9.1    Q10.2
0    2       0       1       3       4
1    7       5       6       8       9
2    2       0       1       3       4
3    2       0       1       3       4
4    2       0       1       3       4

Mixing a PHP variable with a string literal

You can use {} arround your variable, to separate it from what's after:

echo "{$test}y"

As reference, you can take a look to the Variable parsing - Complex (curly) syntax section of the PHP manual.

How to correctly set Http Request Header in Angular 2

Your parameter for the request options in http.put() should actually be of type RequestOptions. Try something like this:

let headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('authentication', `${student.token}`);

let options = new RequestOptions({ headers: headers });
return this.http
    .put(url, JSON.stringify(student), options)

Build the full path filename in Python

Um, why not just:

>>>> import os
>>>> os.path.join(dir_name, base_filename + "." + format)
'/home/me/dev/my_reports/daily_report.pdf'

Change font size of UISegmentedControl

I ran into the same issue. This code sets the font size for the entire segmented control. Something similar might work for setting the font type. Note that this is only available for iOS5+

Obj C:

UIFont *font = [UIFont boldSystemFontOfSize:12.0f];
NSDictionary *attributes = [NSDictionary dictionaryWithObject:font
                                                       forKey:NSFontAttributeName];
[segmentedControl setTitleTextAttributes:attributes 
                                forState:UIControlStateNormal];

EDIT: UITextAttributeFont has been deprecated - use NSFontAttributeName instead.

EDIT #2: For Swift 4 NSFontAttributeName has been changed to NSAttributedStringKey.font.

Swift 5:

let font = UIFont.systemFont(ofSize: 16)
segmentedControl.setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)

Swift 4:

let font = UIFont.systemFont(ofSize: 16)
segmentedControl.setTitleTextAttributes([NSAttributedStringKey.font: font],
                                        for: .normal)

Swift 3:

let font = UIFont.systemFont(ofSize: 16)
segmentedControl.setTitleTextAttributes([NSFontAttributeName: font],
                                        for: .normal)

Swift 2.2:

let font = UIFont.systemFontOfSize(16)
segmentedControl.setTitleTextAttributes([NSFontAttributeName: font], 
    forState: UIControlState.Normal)

Thanks to the Swift implementations from @audrey-gordeev

Applying Comic Sans Ms font style

The font may exist with different names, and not at all on some systems, so you need to use different variations and fallback to get the closest possible look on all systems:

font-family: "Comic Sans MS", "Comic Sans", cursive;

Be careful what you use this font for, though. Many consider it as ugly and overused, so it should not be use for something that should look professional.

Do fragments really need an empty constructor?

As noted by CommonsWare in this question https://stackoverflow.com/a/16064418/1319061, this error can also occur if you are creating an anonymous subclass of a Fragment, since anonymous classes cannot have constructors.

Don't make anonymous subclasses of Fragment :-)

Iterate over each line in a string in PHP

Potential memory issues with strtok:

Since one of the suggested solutions uses strtok, unfortunately it doesn't point out a potential memory issue (though it claims to be memory efficient). When using strtok according to the manual, the:

Note that only the first call to strtok uses the string argument. Every subsequent call to strtok only needs the token to use, as it keeps track of where it is in the current string.

It does this by loading the file into memory. If you're using large files, you need to flush them if you're done looping through the file.

<?php
function process($str) {
    $line = strtok($str, PHP_EOL);

    /*do something with the first line here...*/

    while ($line !== FALSE) {
        // get the next line
        $line = strtok(PHP_EOL);

        /*do something with the rest of the lines here...*/

    }
    //the bit that frees up memory
    strtok('', '');
}

If you're only concerned with physical files (eg. datamining):

According to the manual, for the file upload part you can use the file command:

 //Create the array
 $lines = file( $some_file );

 foreach ( $lines as $line ) {
   //do something here.
 }

Get JSONArray without array name?

JSONArray has a constructor which takes a String source (presumed to be an array).

So something like this

JSONArray array = new JSONArray(yourJSONArrayAsString);

How can I show a message box with two buttons?

I did

msgbox "TEXT HERE",3,"TITLE HERE"
If Yes=true then
(result)

else
msgbox "Closing..."

How to create a session using JavaScript?

I assume you are using ASP.NET MVC (C#), if not then this answer is not in your issue.

Is it impossible to assign session values directly through javascript? No, there is a way to do that.

Look again your code:

<script type="text/javascript" >
{
Session["controlID"] ="This is my session";
}
</script> 

A little bit change:

<script type="text/javascript" >
{
  <%Session["controlID"] = "This is my session";%>
}
</script>

The session "controlID" has created, but what about the value of session? is that persistent or can changeable via javascript?

Let change a little bit more:

<script type="text/javascript" >
{
  var strTest = "This is my session"; 
  <%Session["controlID"] = "'+ strTest +'";%>
}
</script>

The session is created, but the value inside of session will be "'+ strTest +'" but not "This is my session". If you try to write variable directly into server code like:

<%Session["controlID"] = strTest;%>

Then an error will occur in you page "There is no parameter strTest in current context...". Until now it is still seem impossible to assign session values directly through javascript.

Now I move to a new way. Using WebMethod at code behind to do that. Look again your code with a little bit change:

<script type="text/javascript" >
{
 var strTest = "This is my session"; 
 PageMethods.CreateSessionViaJavascript(strTest);
}
</script> 

In code-behind page. I create a WebMethod:

[System.Web.Services.WebMethod]
public static string CreateSessionViaJavascript(string strTest)
{
    Page objp = new Page();
    objp.Session["controlID"] = strTest; 
    return strTest;
}

After call the web method to create a session from javascript. The session "controlID" will has value "This is my session".

If you use the way I have explained, then please add this block of code inside form tag of your aspx page. The code help to enable page methods.

<asp:ScriptManager EnablePageMethods="true" ID="MainSM" runat="server" ScriptMode="Release" LoadScriptsBeforeUI="true"></asp:ScriptManager>

Source: JavaScript - How to Set values to Session in Javascript

Happy codding, Tri

Can I restore a single table from a full mysql mysqldump file?

A simple solution would be to simply create a dump of just the table you wish to restore separately. You can use the mysqldump command to do so with the following syntax:

mysqldump -u [user] -p[password] [database] [table] > [output_file_name].sql

Then import it as normal, and it will only import the dumped table.

Mysql service is missing

I came across the same problem. I properly installed the MYSQL Workbench 6.x, but faced the connection as below:

enter image description here

I did a bit R&D on this and found that MySQL service in service.msc is not present. To achieve this I created a new connection in MySQL Workbench then manually configured the MySQL Database Server in "System Profile" (see the below picture).

You also need to install MySQL Database Server and set a configuration file path for my.ini. Now at last test the connection (make sure MySQL service is running in services.msc).

enter image description here

error: function returns address of local variable

a is defined locally in the function, and can't be used outside the function. If you want to return a char array from the function, you'll need to allocate it dynamically:

char *a = malloc(1000);

And at some point call free on the returned pointer.

You should also see a warning at this line: char b = "blah";: you're trying to assign a string literal to a char.

Get selected option from select element

Given this HTML:

<select>
    <option value="0">One</option>
    <option value="1">Two</option>
</select>

Select by description for jQuery v1.6+:

var text1 = 'Two';
$("select option").filter(function() {
    //may want to use $.trim in here
    return $(this).text() == text1; 
}).prop('selected', true);

How do I convert a double into a string in C++?

Normaly for this operations you have to use the ecvt, fcvt or gcvt Functions:

/* gcvt example */
#include <stdio.h>
#include <stdlib.h>

main ()
{
  char buffer [20];
  gcvt (1365.249,6,buffer);
  puts (buffer);
  gcvt (1365.249,3,buffer);
  puts (buffer);
  return 0;
}

Output:
1365.25
1.37e+003   

As a Function:

void double_to_char(double f,char * buffer){
  gcvt(f,10,buffer);
}

SQL Insert into table only if record doesn't exist

Assuming you cannot modify DDL (to create a unique constraint) or are limited to only being able to write DML then check for a null on filtered result of your values against the whole table

FIDDLE

insert into funds (ID, date, price) 
select 
    T.* 
from 
    (select 23 ID,  '2013-02-12' date,  22.43 price) T  
        left join 
    funds on funds.ID = T.ID and funds.date = T.date
where 
    funds.ID is null

ps command doesn't work in docker container

ps is not installed in the base wheezy image. Try this from within the container:

RUN apt-get update && apt-get install -y procps

Python Iterate Dictionary by Index

There are some very good answers here. I'd like to add the following here as well:

some_dict = {
    "foo": "bar",
    "lorem": "ipsum"
}

for index, (key, value) in enumerate(some_dict.items()):
    print(index, key, value)

results in

0 foo bar
1 lorem ipsum

Appears to work with Python 2.7 and 3.5

Jquery - How to get the style display attribute "none / block"

//animated show/hide

function showHide(id) {
      var hidden= ("none" == $( "#".concat(id) ).css("display"));
      if(hidden){
          $( "#".concat(id) ).show(1000);
      }else{
          $("#".concat(id) ).hide(1000);
      }
  }

Can't access to HttpContext.Current

Have you included the System.Web assembly in the application?

using System.Web;

If not, try specifying the System.Web namespace, for example:

 System.Web.HttpContext.Current

How can I convert this foreach code to Parallel.ForEach?

These lines Worked for me.

string[] lines = File.ReadAllLines(txtProxyListPath.Text);
var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount * 10 };
Parallel.ForEach(lines , options, (item) =>
{
 //My Stuff
});

Best way to test if a row exists in a MySQL table

You could also try EXISTS:

SELECT EXISTS(SELECT * FROM table1 WHERE ...)

and per the documentation, you can SELECT anything.

Traditionally, an EXISTS subquery starts with SELECT *, but it could begin with SELECT 5 or SELECT column1 or anything at all. MySQL ignores the SELECT list in such a subquery, so it makes no difference.

Android SDK location

When you first time install Android Studio Setup, you can also see the SDK folder. For me it is:

C:\Users\{USERNAME}\AppData\Local\Android\sdk

enter image description here

Enable remote connections for SQL Server Express 2012

You can use this to solve this issue:

Go to START > EXECUTE, and run CLICONFG.EXE.

The Named Pipes protocol will be first in the list.Demote it, and promote TCP/IP.

Test the application thoroughly.

I hope this help.

Javascript variable access in HTML

Here you go: http://codepen.io/anon/pen/cKflA

Although, I must say that what you are asking to do is not a good way to do it. A good way is this: http://codepen.io/anon/pen/jlkvJ

Need a row count after SELECT statement: what's the optimal SQL approach?

Here are some ideas:

  • Go with Approach #1 and resize the array to hold additional results or use a type that automatically resizes as neccessary (you don't mention what language you are using so I can't be more specific).
  • You could execute both statements in Approach #1 within a transaction to guarantee the counts are the same both times if your database supports this.
  • I'm not sure what you are doing with the data but if it is possible to process the results without storing all of them first this might be the best method.

How can I disable ARC for a single file in a project?

use -fno-objc-arc for each file in build phases

ValueError: all the input arrays must have same number of dimensions

The reason why you get your error is because a "1 by n" matrix is different from an array of length n.

I recommend using hstack() and vstack() instead. Like this:

import numpy as np
a = np.arange(32).reshape(4,8) # 4 rows 8 columns matrix.
b = a[:,-1:]                    # last column of that matrix.

result = np.hstack((a,b))       # stack them horizontally like this:
#array([[ 0,  1,  2,  3,  4,  5,  6,  7,  7],
#       [ 8,  9, 10, 11, 12, 13, 14, 15, 15],
#       [16, 17, 18, 19, 20, 21, 22, 23, 23],
#       [24, 25, 26, 27, 28, 29, 30, 31, 31]])

Notice the repeated "7, 15, 23, 31" column. Also, notice that I used a[:,-1:] instead of a[:,-1]. My version generates a column:

array([[7],
       [15],
       [23],
       [31]])

Instead of a row array([7,15,23,31])


Edit: append() is much slower. Read this answer.

What's the advantage of a Java enum versus a class with public static final fields?

Another important difference is that java compiler treats static final fields of primitive types and String as literals. It means these constants become inline. It's similar to C/C++ #define preprocessor. See this SO question. This is not the case with enums.

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

POST request not allowed - 405 Not Allowed - nginx, even with headers included

I noticed this wasn't working with a static-first-then-reverse-proxy setup. Here's what that looks like:

location @app {
  proxy_pass http://localhost:3000$request_uri;
}

location / {
  try_files $uri $uri/ @app;
  error_page 405 @app;
}

Concatenate chars to form String in java

Use str = ""+a+b+c;

Here the first + is String concat, so the result will be a String. Note where the "" lies is important.

Or (maybe) better, use a StringBuilder.

How to start and stop/pause setInterval?

As you've tagged this jQuery ...

First, put IDs on your input buttons and remove the inline handlers:

<input type="number" id="input" />
<input type="button" id="stop" value="stop"/>
<input type="button" id="start" value="start"/>

Then keep all of your state and functions encapsulated in a closure:

EDIT updated for a cleaner implementation, that also addresses @Esailija's concerns about use of setInterval().

$(function() {
    var timer = null;
    var input = document.getElementById('input');

    function tick() {
        ++input.value;
        start();        // restart the timer
    };

    function start() {  // use a one-off timer
        timer = setTimeout(tick, 1000);
    };

    function stop() {
        clearTimeout(timer);
    };

    $('#start').bind("click", start); // use .on in jQuery 1.7+
    $('#stop').bind("click", stop);

    start();  // if you want it to auto-start
});

This ensures that none of your variables leak into global scope, and can't be modified from outside.

(Updated) working demo at http://jsfiddle.net/alnitak/Q6RhG/

Binding a Button's visibility to a bool value in ViewModel

Assuming AdvancedFormat is a bool, you need to declare and use a BooleanToVisibilityConverter:

<!-- In your resources section of the XAML -->
<BooleanToVisibilityConverter x:Key="BoolToVis" />

<!-- In your Button declaration -->
<Button
 Height="50" Width="50"
 Style="{StaticResource MyButtonStyle}"
 Command="{Binding SmallDisp}" CommandParameter="{Binding}" 
Cursor="Hand" Visibility="{Binding Path=AdvancedFormat, Converter={StaticResource BoolToVis}}"/>

Note the added Converter={StaticResource BoolToVis}.

This is a very common pattern when working with MVVM. In theory you could do the conversion yourself on the ViewModel property (i.e. just make the property itself of type Visibility) though I would prefer not to do that, since now you are messing with the separation of concerns. An item's visbility should really be up to the View.

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

Try this

SELECT CONVERT(varchar(11),getdate(),101) -- Converts to 'mm/dd/yyyy'

SELECT CONVERT(varchar(11),getdate(),103) -- Converts to 'dd/mm/yyyy'

More info here: https://msdn.microsoft.com/en-us/library/ms187928.aspx

Ruby sleep or delay less than a second?

Pass float to sleep, like sleep 0.1

You seem to not be depending on "@angular/core". This is an error

While running ng serve you should be in the app's/project's directory.

If you run the command in another directory you get the error:

You seem to not be depending on "@angular/core". This is an error.

Entity Framework Code First - two Foreign Keys from same table

It's also possible to specify the ForeignKey() attribute on the navigation property:

[ForeignKey("HomeTeamID")]
public virtual Team HomeTeam { get; set; }
[ForeignKey("GuestTeamID")]
public virtual Team GuestTeam { get; set; }

That way you don't need to add any code to the OnModelCreate method

The CSRF token is invalid. Please try to resubmit the form

In addition to others' suggestions you can get CSRF token errors if your session storage is not working.

In a recent case a colleague of mine changed 'session_prefix' to a value that had a space in it.

session_prefix: 'My Website'

This broke session storage, which in turn meant my form could not obtain the CSRF token from the session.

How do you sort an array on multiple columns?

String Appending Method

You can sort by multiple values simply by appending the values into a string and comparing the strings. It is helpful to add a split key character to prevent runoff from one key to the next.

Example

_x000D_
_x000D_
const arr = [ 
    { a: 1, b: 'a', c: 3 },
    { a: 2, b: 'a', c: 5 },
    { a: 1, b: 'b', c: 4 },
    { a: 2, b: 'a', c: 4 }
]


function sortBy (arr, keys, splitKeyChar='~') {
    return arr.sort((i1,i2) => {
        const sortStr1 = keys.reduce((str, key) => str + splitKeyChar+i1[key], '')
        const sortStr2 = keys.reduce((str, key) => str + splitKeyChar+i2[key], '')
        return sortStr1.localeCompare(sortStr2)
    })
}

console.log(sortBy(arr, ['a', 'b', 'c']))
_x000D_
_x000D_
_x000D_

Recursion Method

You can also use Recursion to do this. It is a bit more complex than the String Appending Method but it allows you to do ASC and DESC on the key level. I'm commenting on each section as it is a bit more complex.

There are a few commented out tests to show and verify the sorting works with a mixture of order and default order.

Example

const arr = [ 
    { a: 1, b: 'a', c: 3 },
    { a: 2, b: 'a', c: 5 },
    { a: 1, b: 'b', c: 4 },
    { a: 2, b: 'a', c: 4 }
]


function sortBy (arr, keys) {
    return arr.sort(function sort (i1,i2, sKeys=keys) {
        // Get order and key based on structure
        const compareKey = (sKeys[0].key) ? sKeys[0].key : sKeys[0];
        const order = sKeys[0].order || 'ASC'; // ASC || DESC
        // Calculate compare value and modify based on order
        let compareValue = i1[compareKey].toString().localeCompare(i2[compareKey].toString())
        compareValue = (order.toUpperCase() === 'DESC') ? compareValue * -1 : compareValue
        // See if the next key needs to be considered 
        const checkNextKey = compareValue === 0 && sKeys.length !== 1
        // Return compare value
        return (checkNextKey) ? sort(i1, i2, sKeys.slice(1)): compareValue;
    })
}

// console.log(sortBy(arr, ['a', 'b', 'c']))
console.log(sortBy(arr, [{key:'a',order:'desc'}, 'b', 'c']))
// console.log(sortBy(arr, ['a', 'b', {key:'c',order:'desc'}]))
// console.log(sortBy(arr, ['a', {key:'b',order:'desc'}, 'c']))
// console.log(sortBy(arr, [{key:'a',order:'asc'}, {key:'b',order:'desc'}, {key:'c',order:'desc'}]))

How to POST a JSON object to a JAX-RS service

Jersey makes the process very easy, my service class worked well with JSON, all I had to do is to add the dependencies in the pom.xml

@Path("/customer")
public class CustomerService {

    private static Map<Integer, Customer> customers = new HashMap<Integer, Customer>();

    @POST
    @Path("save")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public SaveResult save(Customer c) {

        customers.put(c.getId(), c);

        SaveResult sr = new SaveResult();
        sr.sucess = true;
        return sr;
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{id}")
    public Customer getCustomer(@PathParam("id") int id) {
        Customer c = customers.get(id);
        if (c == null) {
            c = new Customer();
            c.setId(id * 3);
            c.setName("unknow " + id);
        }
        return c;
    }
}

And in the pom.xml

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.7</version>
</dependency>

How to build and fill pandas dataframe from for loop?

I may be wrong, but I think the accepted answer by @amit has a bug.

from pandas import DataFrame as df
x = [1,2,3]
y = [7,8,9,10]

# this gives me a syntax error at 'for' (Python 3.7)
d1 = df[[a, "A", b, "B"] for a in x for b in y]

# this works
d2 = df([a, "A", b, "B"] for a in x for b in y)

# and if you want to add the column names on the fly
# note the additional parentheses
d3 = df(([a, "A", b, "B"] for a in x for b in y), columns = ("l","m","n","o"))

WorksheetFunction.CountA - not working post upgrade to Office 2010

It may be obvious but, by stating the Range and not including which workbook or worksheet then it may be trying to CountA() on a different sheet entirely. I find to fully address these things saves a lot of headaches.

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I've gotten same problem. The servers logs showed:

DEBUG: <-- origin: null

I've investigated that and it occurred that this is not populated when I've been calling from file from local drive. When I've copied file to the server and used it from server - the request worked perfectly fine

Extracting columns from text file with different delimiters in Linux

You can use cut with a delimiter like this:

with space delim:

cut -d " " -f1-100,1000-1005 infile.csv > outfile.csv

with tab delim:

cut -d$'\t' -f1-100,1000-1005 infile.csv > outfile.csv

I gave you the version of cut in which you can extract a list of intervals...

Hope it helps!

Difference between Date(dateString) and new Date(dateString)

The difference is the fact (if I recall from the ECMA documentation) is that Date("xx") does not create (in a sense) a new date object (in fact it is equivalent to calling (new Date("xx").toString()). While new Date("xx") will actually create a new date object.

For More Information:

Look at 15.9.2 of http://www.ecma-international.org/publications/files/ECMA-ST/ECMA-262.pdf

How to dynamically change the color of the selected menu item of a web page?

I'm late to this question, but it's really super easy. You just define multiple tab classes in your css file, and then load the required tab as your class in the php file while creating the LI tag.

Here's an example of doing it entirely on the server:

CSS

html ul.tabs li.activeTab1, html ul.tabs li.activeTab1 a:hover, html ul.tabs li.activeTab1 a  { 
    background: #0076B5;
    color: white;
    border-bottom: 1px solid #0076B5;
}

html ul.tabs li.activeTab2, html ul.tabs li.activeTab2 a:hover, html ul.tabs li.activeTab2 a {
    background: #008C5D;
    color: white;
    border-bottom: 1px solid #008C5D;
}

PHP

<ul class="tabs">
    <li <?php print 'class="activeTab1"' ?>>
        <a href="<?php print 'Tab1.php';?>">Tab 1</a>
    </li>

    <li <?php print 'class="activeTab2"' ?>>
        <a href="<?php print 'Tab2.php';?>">Tab 2</a>
    </li>
</ul>

Container is running beyond memory limits

I had a really similar issue using HIVE in EMR. None of the extant solutions worked for me -- ie, none of the mapreduce configurations worked for me; and neither did setting yarn.nodemanager.vmem-check-enabled to false.

However, what ended up working was setting tez.am.resource.memory.mb, for example:

hive -hiveconf tez.am.resource.memory.mb=4096

Another setting to consider tweaking is yarn.app.mapreduce.am.resource.mb

How to get the sizes of the tables of a MySQL database?

Try the following shell command (replace DB_NAME with your database name):

mysql -uroot <<<"SELECT table_name AS 'Tables', round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema = \"DB_NAME\" ORDER BY (data_length + index_length) DESC;" | head

For Drupal/drush solution, check the following example script which will display the biggest tables in use:

#!/bin/sh
DB_NAME=$(drush status --fields=db-name --field-labels=0 | tr -d '\r\n ')
drush sqlq "SELECT table_name AS 'Tables', round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema = \"${DB_NAME}\" ORDER BY (data_length + index_length) DESC;" | head -n20

Best database field type for a URL

Most browsers will let you put very large amounts of data in a URL and thus lots of things end up creating very large URLs so if you are talking about anything more than the domain part of a URL you will need to use a TEXT column since the VARCHAR/CHAR are limited.

Can I change the checkbox size using CSS?

2020 version - using pseudo-elements, size depends on font size.

Default checkbox/radio is rendered outside of screen, but CSS creates virtual elements very similar to default elements. Supports all browsers, no blur. Size depends on font size. Keyboard actions (space, tabs) are also supported.

https://jsfiddle.net/ohf7nmzy/2/

_x000D_
_x000D_
body{_x000D_
 padding:0 20px;_x000D_
}_x000D_
.big{_x000D_
 font-size: 50px;_x000D_
}_x000D_
_x000D_
/* CSS below will force radio/checkbox size be same as font size */_x000D_
label{_x000D_
 position: relative;_x000D_
 line-height: 1.4;_x000D_
}_x000D_
/* radio */_x000D_
input[type=radio]{_x000D_
 width: 1em;_x000D_
 font-size: inherit;_x000D_
 margin: 0;_x000D_
 transform: translateX(-9999px);_x000D_
}_x000D_
input[type=radio] + label:before{_x000D_
 position: absolute;_x000D_
 content: '';_x000D_
 left: -1.3em;_x000D_
 top: 0;_x000D_
 width: 1em;_x000D_
 height: 1em;_x000D_
 margin: 0;_x000D_
 border:none;_x000D_
 border-radius: 50%;_x000D_
 background-color: #bbbbbb;_x000D_
}_x000D_
input[type=radio] + label:after{_x000D_
 position: absolute;_x000D_
 content: '';_x000D_
 left: -1.3em;_x000D_
 top: 0;_x000D_
 width: 1em;_x000D_
 height: 1em;_x000D_
 margin: 0;_x000D_
 border: none;_x000D_
 background-color: white;_x000D_
 border-radius: 50%;_x000D_
 transform: scale(0.8);_x000D_
}_x000D_
/*checked*/_x000D_
input[type=radio]:checked + label:before{_x000D_
 position:absolute;_x000D_
 content:'';_x000D_
 left: -1.3em;_x000D_
 top: 0;_x000D_
 width: 1em;_x000D_
 height: 1em;_x000D_
 margin: 0;_x000D_
 border: none;_x000D_
 background-color: #3b88fd;_x000D_
}_x000D_
input[type=radio]:checked + label:after{_x000D_
 position: absolute;_x000D_
 content: '';_x000D_
 left: -1.3em;_x000D_
 top: 0;_x000D_
 width: 1em;_x000D_
 height: 1em;_x000D_
 margin: 0;_x000D_
 border: none;_x000D_
 background-color: white;_x000D_
 border-radius: 50%;_x000D_
 transform: scale(0.3);_x000D_
}_x000D_
/*focused*/_x000D_
input[type=radio]:focus + label:before{_x000D_
 border: 0.2em solid #8eb9fb;_x000D_
 margin-top: -0.2em;_x000D_
 margin-left: -0.2em;_x000D_
 box-shadow: 0 0 0.3em #3b88fd;_x000D_
}_x000D_
_x000D_
_x000D_
/*checkbox/*/_x000D_
input[type=checkbox]{_x000D_
 width: 1em;_x000D_
 font-size: inherit;_x000D_
 margin: 0;_x000D_
 transform: translateX(-9999px);_x000D_
}_x000D_
input[type=checkbox] + label:before{_x000D_
 position: absolute;_x000D_
 content: '';_x000D_
 left: -1.3em;_x000D_
 top: 0;_x000D_
 width: 1em;_x000D_
 height: 1em;_x000D_
 margin: 0;_x000D_
 border:none;_x000D_
 border-radius: 10%;_x000D_
 background-color: #bbbbbb;_x000D_
}_x000D_
input[type=checkbox] + label:after{_x000D_
 position: absolute;_x000D_
 content: '';_x000D_
 left: -1.3em;_x000D_
 top: 0;_x000D_
 width: 1em;_x000D_
 height: 1em;_x000D_
 margin: 0;_x000D_
 border: none;_x000D_
 background-color: white;_x000D_
 border-radius: 10%;_x000D_
 transform: scale(0.8);_x000D_
}_x000D_
/*checked*/_x000D_
input[type=checkbox]:checked + label:before{_x000D_
 position:absolute;_x000D_
 content:'';_x000D_
 left: -1.3em;_x000D_
 top: 0;_x000D_
 width: 1em;_x000D_
 height: 1em;_x000D_
 margin: 0;_x000D_
 border: none;_x000D_
 background-color: #3b88fd;_x000D_
}_x000D_
input[type=checkbox]:checked + label:after{_x000D_
 position: absolute;_x000D_
 content: "\2713";_x000D_
 left: -1.3em;_x000D_
 top: 0;_x000D_
 width: 1em;_x000D_
 height: 1em;_x000D_
 margin: 0;_x000D_
 border: none;_x000D_
 background-color: #3b88fd;_x000D_
 border-radius: 10%;_x000D_
 color: white;_x000D_
 text-align: center;_x000D_
 line-height: 1;_x000D_
}_x000D_
/*focused*/_x000D_
input[type=checkbox]:focus + label:before{_x000D_
 border: 0.1em solid #8eb9fb;_x000D_
 margin-top: -0.1em;_x000D_
 margin-left: -0.1em;_x000D_
 box-shadow: 0 0 0.2em #3b88fd;_x000D_
}
_x000D_
<input type="checkbox" name="checkbox_1" id="ee" checked /> _x000D_
<label for="ee">Checkbox small</label>_x000D_
_x000D_
<br />_x000D_
_x000D_
<input type="checkbox" name="checkbox_2" id="ff" /> _x000D_
<label for="ff">Checkbox small</label>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<div class="big">_x000D_
 <input type="checkbox" name="checkbox_3" id="gg" checked /> _x000D_
 <label for="gg">Checkbox big</label>_x000D_
_x000D_
 <br />_x000D_
_x000D_
 <input type="checkbox" name="checkbox_4" id="hh" /> _x000D_
 <label for="hh">Checkbox big</label>_x000D_
</div>_x000D_
_x000D_
_x000D_
<hr />_x000D_
_x000D_
_x000D_
<input type="radio" name="radio_1" id="aa" value="1" checked /> _x000D_
<label for="aa">Radio small</label>_x000D_
_x000D_
<br />_x000D_
_x000D_
<input type="radio" name="radio_1" id="bb" value="2" /> _x000D_
<label for="bb">Radio small</label>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<div class="big">_x000D_
 <input type="radio" name="radio_2" id="cc" value="1" checked /> _x000D_
 <label for="cc">Radio big</label>_x000D_
_x000D_
 <br />_x000D_
_x000D_
 <input type="radio" name="radio_2" id="dd" value="2" /> _x000D_
 <label for="dd">Radio big</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

2017 version - using zoom or scale

Browser will use non-standard zoom feature if it is supported (nice quality) or standard transform: scale (blurry).

Scaling works on all browsers, but it will be blurry on Firefox and Safari.

https://jsfiddle.net/ksvx2txb/11/

_x000D_
_x000D_
@supports (zoom:2) {_x000D_
 input[type="radio"],  input[type=checkbox]{_x000D_
 zoom: 2;_x000D_
 }_x000D_
}_x000D_
@supports not (zoom:2) {_x000D_
 input[type="radio"],  input[type=checkbox]{_x000D_
  transform: scale(2);_x000D_
  margin: 15px;_x000D_
 }_x000D_
}_x000D_
label{_x000D_
  /* fix vertical align issues */_x000D_
 display: inline-block;_x000D_
 vertical-align: top;_x000D_
 margin-top: 10px;_x000D_
}
_x000D_
<input type="radio" name="aa" value="1" id="aa" checked /> _x000D_
<label for="aa">Radio 1</label>_x000D_
<br />_x000D_
<input type="radio" name="aa" value="2" id="bb" /> _x000D_
<label for="bb">Radio 2</label>_x000D_
_x000D_
<br /><br />_x000D_
_x000D_
<input  type="checkbox" name="optiona" id="cc" checked /> _x000D_
<label for="cc">Checkbox 1</label>_x000D_
<br />_x000D_
<input  type="checkbox" name="optiona" id="dd" /> _x000D_
<label for="dd">Checkbox 1</label>
_x000D_
_x000D_
_x000D_

How to get std::vector pointer to the raw data?

&something gives you the address of the std::vector object, not the address of the data it holds. &something.begin() gives you the address of the iterator returned by begin() (as the compiler warns, this is not technically allowed because something.begin() is an rvalue expression, so its address cannot be taken).

Assuming the container has at least one element in it, you need to get the address of the initial element of the container, which you can get via

  • &something[0] or &something.front() (the address of the element at index 0), or

  • &*something.begin() (the address of the element pointed to by the iterator returned by begin()).

In C++11, a new member function was added to std::vector: data(). This member function returns the address of the initial element in the container, just like &something.front(). The advantage of this member function is that it is okay to call it even if the container is empty.

How do I add an integer value with javascript (jquery) to a value that's returning a string?

var month = new Date().getMonth();
var newmon = month + 1;
$('#month').html((newmon < 10 ? '0' : '') + newmon );

I simply fixed your month issue, getMonth array start from 0 to 11.

handle textview link click in my android app

I changed the TextView's color to blue by using for example:

android:textColor="#3399FF"

in the xml file. How to make it underlined is explained here.

Then use its onClick property to specify a method (I'm guessing you could call setOnClickListener(this) as another way), e.g.:

myTextView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
    doSomething();
}
});

In that method, I can do whatever I want as normal, such as launch an intent. Note that you still have to do the normal myTextView.setMovementMethod(LinkMovementMethod.getInstance()); thing, like in your acitivity's onCreate() method.

How to Add Stacktrace or debug Option when Building Android Studio Project

To be able to run options like --stacktrace within a gradle command, you need to put it at the beginning, like:

./gradlew --stacktrace assembleMyBuild

E.g,

./gradlew --stacktrace assembleDebug

Notepad++ Multi editing

Notepad++ has a powerful regex engine, capable to search and replace patterns at will.

In your scenario:

  1. Click the menu item Search\Replace...

  2. Fill the 'Find what' field with the search pattern:

    ^(\d{4})\s+(\w{3})\s+(\w{3})$
    
  3. Fill the replace pattern:

    Insert into tbl (\1, \2) where clm = \3
    
  4. Click the Replace All button.

And that's it.

NotePad++ replace window screenshot

How can I run a html file from terminal?

You can make the file accessible via a web server then you can use curl or lynx

How to call a parent class function from derived class function?

If your base class is called Base, and your function is called FooBar() you can call it directly using Base::FooBar()

void Base::FooBar()
{
   printf("in Base\n");
}

void ChildOfBase::FooBar()
{
  Base::FooBar();
}

How to use a DataAdapter with stored procedure and parameter

 SqlConnection con = new SqlConnection(@"Some Connection String");
 SqlDataAdapter da = new SqlDataAdapter("ParaEmp_Select",con);
            da.SelectCommand.CommandType = CommandType.StoredProcedure;
            da.SelectCommand.Parameters.Add("@Contactid", SqlDbType.Int).Value = 123;
            DataTable dt = new DataTable();
            da.Fill(dt);
            dataGridView1.DataSource = dt;

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

delay does not work on none queue functions, so we should use setTimeout().

And you don't need to separate things. All you need to do is including everything in a setTimeOut method:

setTimeout(function () {
    $("#div").addClass("error").delay(1000).removeClass("error");
}, 1000);

CHECK constraint in MySQL is not working

Update to MySQL 8.0.16 to use checks:

As of MySQL 8.0.16, CREATE TABLE permits the core features of table and column CHECK constraints, for all storage engines. CREATE TABLE permits the following CHECK constraint syntax, for both table constraints and column constraints

MySQL Checks Documentation

How to open a new tab using Selenium WebDriver

Do this:

driver.ExecuteScript("window.open('your URL', '_blank');");

How to view file diff in git before commit

Did you try -v (or --verbose) option for git commit? It adds the diff of the commit in the message editor.

Can I serve multiple clients using just Flask app.run() as standalone?

Tips from 2020:

From Flask 1.0, it defaults to enable multiple threads (source), you don't need to do anything, just upgrade it with:

$ pip install -U flask

If you are using flask run instead of app.run() with older versions, you can control the threaded behavior with a command option (--with-threads/--without-threads):

$ flask run --with-threads

It's same as app.run(threaded=True)

g++ ld: symbol(s) not found for architecture x86_64

finally solved my problem.

I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.

What is the "right" way to iterate through an array in Ruby?

This will iterate through all the elements:

array = [1, 2, 3, 4, 5, 6]
array.each { |x| puts x }

Prints:

1
2
3
4
5
6

This will iterate through all the elements giving you the value and the index:

array = ["A", "B", "C"]
array.each_with_index {|val, index| puts "#{val} => #{index}" }

Prints:

A => 0
B => 1
C => 2

I'm not quite sure from your question which one you are looking for.

Can I set enum start value in Java?

Java enums are not like C or C++ enums, which are really just labels for integers.

Java enums are implemented more like classes - and they can even have multiple attributes.

public enum Ids {
    OPEN(100), CLOSE(200);

    private final int id;
    Ids(int id) { this.id = id; }
    public int getValue() { return id; }
}

The big difference is that they are type-safe which means you don't have to worry about assigning a COLOR enum to a SIZE variable.

See http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html for more.

Java null check why use == instead of .equals()

here is an example where str != null but str.equals(null) when using org.json

 JSONObject jsonObj = new JSONObject("{field :null}");
 Object field = jsonObj.get("field");
 System.out.println(field != null);        // => true
 System.out.println( field.equals(null)); //=> true
 System.out.println( field.getClass());  // => org.json.JSONObject$Null




EDIT: here is the org.json.JSONObject$Null class:

/**
 * JSONObject.NULL is equivalent to the value that JavaScript calls null,
 * whilst Java's null is equivalent to the value that JavaScript calls
 * undefined.
 */
private static final class Null {

    /**
     * A Null object is equal to the null value and to itself.
     *
     * @param object
     *            An object to test for nullness.
     * @return true if the object parameter is the JSONObject.NULL object or
     *         null.
     */
    @Override
    public boolean equals(Object object) {
        return object == null || object == this;
    }  
}

Arduino error: does not name a type?

The two includes you mention in your comment are essential. 'does not name a type' just means there is no definition for that identifier visible to the compiler. If there are errors in the LCD library you mention, then those need to be addressed - omitting the #include will definitely not fix it!

Two notes from experience which might be helpful:

  1. You need to add all #include's to the main sketch - irrespective of whether they are included via another #include.

  2. If you add files to the library folder, the Arduino IDE must be restarted before those new files will be visible.

Accessing dict_keys element by index in Python3

test = {'foo': 'bar', 'hello': 'world'}
ls = []
for key in test.keys():
    ls.append(key)
print(ls[0])

Conventional way of appending the keys to a statically defined list and then indexing it for same

getting the error: expected identifier or ‘(’ before ‘{’ token

you need to place the opening brace after main , not before it

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{

laravel foreach loop in controller

Actually your $product has no data because the Eloquent model returns NULL. It's probably because you have used whereOwnerAndStatus which seems wrong and if there were data in $product then it would not work in your first example because get() returns a collection of multiple models but that is not the case. The second example throws error because foreach didn't get any data. So I think it should be something like this:

$owner = Input::get('owner');
$count = Input::get('count');
$products = Product::whereOwner($owner, 0)->take($count)->get();

Further you may also make sure if $products has data:

if($product) {
    return View:make('viewname')->with('products', $products);
}

Then in the view:

foreach ($products as $product) {
    // If Product has sku (collection object, probably related models)
    foreach ($product->sku as $sku) {
        // Code Here        
    }
}

How can I delete a user in linux when the system says its currently used in a process

Only solution that worked for me

$ sudo killall -u username && sudo deluser --remove-home -f username

The killall command is used if multiple processes are used by the user you want to delete.

The -f option forces the removal of the user account, even if the user is still logged in. It also forces deluser to remove the user's home directory and mail spool, even if another user uses the same home directory.

Please confirm that it works in the comments.

Pressed <button> selector

You can do this with php if the button opens a new page.

For example if the button link to a page named pagename.php as, url: www.website.com/pagename.php the button will stay red as long as you stay on that page.

I exploded the url by '/' an got something like:

url[0] = pagename.php

<? $url = explode('/', substr($_SERVER['REQUEST_URI'], strpos('/',$_SERVER['REQUEST_URI'] )+1,strlen($_SERVER['REQUEST_URI']))); ?>


<html>
<head>
  <style>
    .btn{
     background:white;
     }
    .btn:hover,
    .btn-on{
     background:red;
     }
  </style>
</head>
<body>
   <a href="/pagename.php" class="btn <? if (url[0]='pagename.php') {echo 'btn-on';} ?>">Click Me</a>
</body>
</html>

note: I didn't try this code. It might need adjustments.

Remove duplicates from a List<T> in C#

If you don't care about the order you can just shove the items into a HashSet, if you do want to maintain the order you can do something like this:

var unique = new List<T>();
var hs = new HashSet<T>();
foreach (T t in list)
    if (hs.Add(t))
        unique.Add(t);

Or the Linq way:

var hs = new HashSet<T>();
list.All( x =>  hs.Add(x) );

Edit: The HashSet method is O(N) time and O(N) space while sorting and then making unique (as suggested by @lassevk and others) is O(N*lgN) time and O(1) space so it's not so clear to me (as it was at first glance) that the sorting way is inferior (my apologies for the temporary down vote...)

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

Accessing dictionary value by index in python

While you can do

value = d.values()[index]

It should be faster to do

value = next( v for i, v in enumerate(d.itervalues()) if i == index )

edit: I just timed it using a dict of len 100,000,000 checking for the index at the very end, and the 1st/values() version took 169 seconds whereas the 2nd/next() version took 32 seconds.

Also, note that this assumes that your index is not negative

Good tutorial for using HTML5 History API (Pushstate?)

I've written a very simple router abstraction on top of History.js, called StateRouter.js. It's in very early stages of development, but I am using it as the routing solution in a single-page application I'm writing. Like you, I found History.js very hard to grasp, especially as I'm quite new to JavaScript, until I understood that you really need (or should have) a routing abstraction on top of it, as it solves a low-level problem.

This simple example code should demonstrate how it's used:

var router = new staterouter.Router();
// Configure routes
router
  .route('/', getHome)
  .route('/persons', getPersons)
  .route('/persons/:id', getPerson);
// Perform routing of the current state
router.perform();

Here's a little fiddle I've concocted in order to demonstrate its usage.

Get IP address of visitors using Flask for Python

The user's IP address can be retrieved using the following snippet:

from flask import request
print(request.remote_addr)

display html page with node.js

but it ONLY shows the index.html file and NOTHING attached to it, so no images, no effects or anything that the html file should display.

That's because in your program that's the only thing that you return to the browser regardless of what the request looks like.

You can take a look at a more complete example that will return the correct files for the most common web pages (HTML, JPG, CSS, JS) in here https://gist.github.com/hectorcorrea/2573391

Also, take a look at this blog post that I wrote on how to get started with node. I think it might clarify a few things for you: http://hectorcorrea.com/blog/introduction-to-node-js

angular-cli server - how to proxy API requests to another server?

  1. add in proxy.conf.json, all request to /api will be redirect to htt://targetIP:targetPort/api.
{
  "/api": {
    "target": "http://targetIP:targetPort",
    "secure": false,
    "pathRewrite": {"^/api" : targeturl/api},
    "changeOrigin": true,
    "logLevel": "debug"
  }
}
  1. in package.json, make "start": "ng serve --proxy-config proxy.conf.json"

  2. in code let url = "/api/clnsIt/dev/78"; this url will be translated to http://targetIP:targetPort/api/clnsIt/dev/78.

  3. You can also force rewrite by filling the pathRewrite. This is the link for details cmd/NPM console will log something like "Rewriting path from "/api/..." to "http://targeturl:targetPort/api/..", while browser console will log "http://loclahost/api"

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

CSS selectors perform far better than Xpath and it is well documented in Selenium community. Here are some reasons,

  • Xpath engines are different in each browser, hence make them inconsistent
  • IE does not have a native xpath engine, therefore selenium injects its own xpath engine for compatibility of its API. Hence we lose the advantage of using native browser features that WebDriver inherently promotes.
  • Xpath tend to become complex and hence make hard to read in my opinion

However there are some situations where, you need to use xpath, for example, searching for a parent element or searching element by its text (I wouldn't recommend the later).

You can read blog from Simon here . He also recommends CSS over Xpath.

If you are testing content then do not use selectors that are dependent on the content of the elements. That will be a maintenance nightmare for every locale. Try talking with developers and use techniques that they used to externalize the text in the application, like dictionaries or resource bundles etc. Here is my blog that explains it in detail.

edit 1

Thanks to @parishodak, here is the link which provides the numbers proving that CSS performance is better

Python integer incrementing with ++

Take a look at Behaviour of increment and decrement operators in Python for an explanation of why this doesn't work.

Python doesn't really have ++ and --, and I personally never felt it was such a loss.

I prefer functions with clear names to operators with non-always clear semantics (hence the classic interview question about ++x vs. x++ and the difficulties of overloading it). I've also never been a huge fan of what post-incrementation does for readability.

You could always define some wrapper class (like accumulator) with clear increment semantics, and then do something like x.increment() or x.incrementAndReturnPrev()

Rails: update_attribute vs update_attributes

To answer your question, update_attribute skips pre save "validations" but it still runs any other callbacks like after_save etc. So if you really want to "just update the column and skip any AR cruft" then you need to use (apparently)

Model.update_all(...) see https://stackoverflow.com/a/7243777/32453

MySQL: How to copy rows, but change a few fields?

If you have loads of columns in your table and don't want to type out each one you can do it using a temporary table, like;

SELECT *
INTO #Temp
FROM Table WHERE Event_ID = "120"
GO

UPDATE #TEMP
SET Column = "Changed"
GO

INSERT INTO Table
SELECT *
FROM #Temp

Writing List of Strings to Excel CSV File in Python

Very simple to fix, you just need to turn the parameter to writerow into a list.

for item in RESULTS:
     wr.writerow([item,])

Is there any boolean type in Oracle databases?

As per Ammoq and kupa's answers, We use number(1) with default of 0 and don't allow nulls.

here's an add column to demonstrate:

ALTER TABLE YourSchema.YourTable ADD (ColumnName NUMBER(1) DEFAULT 0 NOT NULL);

Hope this helps someone.

Check if a variable is a string in JavaScript

I also found that this works fine too, and its a lot shorter than the other examples.

if (myVar === myVar + '') {
   //its string
} else {
   //its something else
}

By concatenating on empty quotes it turns the value into a string. If myVar is already a string then the if statement is successful.

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

SOAP client in .NET - references or examples?

Take a look at "using WCF Services with PHP". It explains the basics of what you need.

As a theory summary:

WCF or Windows Communication Foundation is a technology that allow to define services abstracted from the way - the underlying communication method - they'll be invoked.

The idea is that you define a contract about what the service does and what the service offers and also define another contract about which communication method is used to actually consume the service, be it TCP, HTTP or SOAP.

You have the first part of the article here, explaining how to create a very basic WCF Service.

More resources:

Using WCF with PHP5.

Aslo take a look to NuSOAP. If you now NuSphere this is a toolkit to let you connect from PHP to an WCF service.

How can I get a specific field of a csv file?

import csv
mycsv = csv.reader(open(myfilepath))
for row in mycsv:
   text = row[1]

Following the comments to the SO question here, a best, more robust code would be:

import csv
with open(myfilepath, 'rb') as f:
    mycsv = csv.reader(f)
    for row in mycsv:
        text = row[1]
        ............

Update: If what the OP actually wants is the last string in the last row of the csv file, there are several aproaches that not necesarily needs csv. For example,

fulltxt = open(mifilepath, 'rb').read()
laststring = fulltxt.split(',')[-1]

This is not good for very big files because you load the complete text in memory but could be ok for small files. Note that laststring could include a newline character so strip it before use.

And finally if what the OP wants is the second string in line n (for n=2):

Update 2: This is now the same code than the one in the answer from J.F.Sebastian. (The credit is for him):

import csv
line_number = 2     
with open(myfilepath, 'rb') as f:
    mycsv = csv.reader(f)
    mycsv = list(mycsv)
    text = mycsv[line_number][1]
    ............

Using find command in bash script

You can use this:

list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp')

Besides, you might want to use -iname instead of -name to catch files with ".PDF" (upper-case) extension as well.

Could not open a connection to your authentication agent

Here is the solution I came up with when using PowerShell.

Add the below function to your Microsoft.PowerShell_profile.ps1

function RunSsh($userIdentity ) {
   $agent=ssh-agent
   $position=$agent[0].IndexOf("=")
   $ending=$agent[0].IndexOf(";")

   $variableStartPosition=$agent[0].IndexOf("export")
   $variableEndPosition=$agent[0].LastIndexOf(";")
   $variableName=$agent[0].Substring($variableStartPosition+7,$variableEndPosition-$variableStartPosition-7)
   [Environment]::SetEnvironmentVariable($variableName, $agent[0].Substring($position+1,$ending-$position-1))

   $position=$agent[1].IndexOf("=")
   $ending=$agent[1].IndexOf(";")

   $variableStartPosition=$agent[1].IndexOf("export")
   $variableEndPosition=$agent[1].LastIndexOf(";")
   $variableName=$agent[1].Substring($variableStartPosition+7,$variableEndPosition-$variableStartPosition-7)
   [Environment]::SetEnvironmentVariable($variableName, $agent[1].Substring($position+1,$ending-$position-1))

   if($userIdentity.Length -eq 0) {
      ssh-add
   } else {
      ssh-add $userIdentity
   }
}

Now from the command line you can run RunSsh which uses identity file in ~\.ssh folder or pass in the identity file with RunSsh C:\ssh\id_rsa where C:\ssh\id_rsa is your identity file.

For this to work you need to have ssh-add and ssh-agent in your path environment variable.

SQL Server Management Studio, how to get execution time down to milliseconds

Include Client Statistics by pressing Ctrl+Alt+S. Then you will have all execution information in the statistics tab below.

How to change Label Value using javascript

This will work in Chrome

// get your input
var input = document.getElementById('txt206451');
// get it's (first) label
var label = input.labels[0];
// change it's content
label.textContent = 'thanks'

But after looking, labels doesn't seem to be widely supported..


You can use querySelector

// get txt206451's (first) label
var label = document.querySelector('label[for="txt206451"]');
// change it's content
label.textContent = 'thanks'

Entity Framework throws exception - Invalid object name 'dbo.BaseCs'

For what it is worth, I wanted to mention that in my case, the problem was coming from an AFTER INSERT Trigger!

These are not super visible so you might be searching for a while!

CSS3 Continuous Rotate Animation (Just like a loading sundial)

You also might notice a little lag because 0deg and 360deg are the same spot, so it is going from spot 1 in a circle back to spot 1. It is really insignificant, but to fix it, all you have to do is change 360deg to 359deg

my jsfiddle illustrates your animation:

#myImg {
    -webkit-animation: rotation 2s infinite linear;
}

@-webkit-keyframes rotation {
    from {-webkit-transform: rotate(0deg);}
    to   {-webkit-transform: rotate(359deg);}
}

Also what might be more resemblant of the apple loading icon would be an animation that transitions the opacity/color of the stripes of gray instead of rotating the icon.

Best way to compare 2 XML documents in Java

I'm using Altova DiffDog which has options to compare XML files structurally (ignoring string data).

This means that (if checking the 'ignore text' option):

<foo a="xxx" b="xxx">xxx</foo>

and

<foo b="yyy" a="yyy">yyy</foo> 

are equal in the sense that they have structural equality. This is handy if you have example files that differ in data, but not structure!

Skip over a value in the range function in python

for i in range(0, 101):
if i != 50:
    do sth
else:
    pass

Run PHP function on html button click

If you want to make a server request you should use AJAX, so you can send your desired parameters to the server and it can run whatever php you want with these parameters.

Example with pure javascript:

<input type="text" id="name" value="..."/>
<input type="text" id="location" value="..."/>
<input type="button" onclick="ajaxFunction();" value="Submit" />
<div id="ajaxDiv"></div>
<script type="text/javascript">    
    function ajaxFunction(){
        var ajaxRequest;  // The variable that makes Ajax possible!

        try{
            // Opera 8.0+, Firefox, Safari
            ajaxRequest = new XMLHttpRequest();
        } catch (e){
            // Internet Explorer Browsers
            try{
                ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
            } catch (e) {
                try{
                    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                } catch (e){
                    // Something went wrong
                    alert("Your browser broke!");
                    return false;
                }
            }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
            if(ajaxRequest.readyState == 4){
                var ajaxDisplay = document.getElementById('ajaxDiv');
                ajaxDisplay.innerHTML = ajaxRequest.responseText;
            }
        }
        var name = document.getElementById('name').value;
        var location = document.getElementById('location').value;
        var queryString = "?name=" + name + "&location=" + location;
        ajaxRequest.open("POST", "some.php" + queryString, true);
        ajaxRequest.send(null); 
    }
</script>

Example with jQuery Ajax: http://api.jquery.com/jQuery.ajax/

$.ajax({
  type: "POST",
  url: "some.php",
  data: { name: "John", location: "Boston" }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

You can have one file with functions called for example functions.php

functions.php

<?php
  myFunction($Name, $Location) {
      // etc...
  }
  myFunction2() {
  }
  // ... many functions
?>

some.php

<?php include("functions.php");    
$Name = $_POST['name'];
$Location = $_POST['location'];

myFunction($Name, $Location);

// make what you want with these variables...?>

Simplest way to do grouped barplot

I wrote a function wrapper called bar() for barplot() to do what you are trying to do here, since I need to do similar things frequently. The Github link to the function is here. After copying and pasting it into R, you do

bar(dv = Species, 
    factors = c(Category, Reason), 
    dataframe = Reasonstats, 
    errbar = FALSE, 
    ylim=c(0, 140))  #I increased the upper y-limit to accommodate the legend. 

The one convenience is that it will put a legend on the plot using the names of the levels in your categorical variable (e.g., "Decline" and "Improved"). If each of your levels has multiple observations, it can also plot the error bars (which does not apply here, hence errbar=FALSE

enter image description here

How to get all Windows service names starting with a common word?

Save it as a .ps1 file and then execute

powershell -file "path\to your\start stop nation service command file.ps1"

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

How to call a method in another class in Java?

You should capitalize names of your classes. After doing that do this in your school class,

Classroom cls = new Classroom();
cls.setTeacherName(newTeacherName);

Also I'd recommend you use some kind of IDE such as eclipse, which can help you with your code for instance generate getters and setters for you. Ex: right click Source -> Generate getters and setters

What is the maximum value for an int32?

The best rule to memorize it is:
21 (magic number!)
47 (just remember it)
48 (sequential!)
36 (21 + 15, both magics!)
47 again

Also it is easier to remember 5 pairs than 10 digits.

How do I get a decimal value when using the division operator in Python?

Add the following function in your code with its callback.

# Starting of the function
def divide(number_one, number_two, decimal_place = 4):
    quotient = number_one/number_two
    remainder = number_one % number_two
    if remainder != 0:
        quotient_str = str(quotient)
        for loop in range(0, decimal_place):
            if loop == 0:
                quotient_str += "."
            surplus_quotient = (remainder * 10) / number_two
            quotient_str += str(surplus_quotient)
            remainder = (remainder * 10) % number_two
            if remainder == 0:
                break
        return float(quotient_str)
    else:
        return quotient
#Ending of the function

# Calling back the above function
# Structure : divide(<divident>, <divisor>, <decimal place(optional)>)
divide(1, 7, 10) # Output : 0.1428571428
# OR
divide(1, 7) # Output : 0.1428

This function works on the basis of "Euclid Division Algorithm". This function is very useful if you don't want to import any external header files in your project.

Syntex : divide([divident], [divisor], [decimal place(optional))

Code : divide(1, 7, 10) OR divide(1, 7)

Comment below for any queries.

Some dates recognized as dates, some dates not recognized. Why?

It's not that hard...

Check out this forum post:

http://www.pcreview.co.uk/forums/excel-not-recognizing-dates-dates-t3139469.html

The steps in short:

  1. Select only the column of "dates"
  2. Click Data > Text to Columns
  3. Click Next
  4. Click Next
  5. In step 3 of the wizard, check "Date" under Col data format, then choose: "DMY" from the droplist.
  6. Click Finish

How to create checkbox inside dropdown?

_x000D_
_x000D_
var expanded = false;_x000D_
_x000D_
function showCheckboxes() {_x000D_
  var checkboxes = document.getElementById("checkboxes");_x000D_
  if (!expanded) {_x000D_
    checkboxes.style.display = "block";_x000D_
    expanded = true;_x000D_
  } else {_x000D_
    checkboxes.style.display = "none";_x000D_
    expanded = false;_x000D_
  }_x000D_
}
_x000D_
.multiselect {_x000D_
  width: 200px;_x000D_
}_x000D_
_x000D_
.selectBox {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.selectBox select {_x000D_
  width: 100%;_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.overSelect {_x000D_
  position: absolute;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
}_x000D_
_x000D_
#checkboxes {_x000D_
  display: none;_x000D_
  border: 1px #dadada solid;_x000D_
}_x000D_
_x000D_
#checkboxes label {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
#checkboxes label:hover {_x000D_
  background-color: #1e90ff;_x000D_
}
_x000D_
<form>_x000D_
  <div class="multiselect">_x000D_
    <div class="selectBox" onclick="showCheckboxes()">_x000D_
      <select>_x000D_
        <option>Select an option</option>_x000D_
      </select>_x000D_
      <div class="overSelect"></div>_x000D_
    </div>_x000D_
    <div id="checkboxes">_x000D_
      <label for="one">_x000D_
        <input type="checkbox" id="one" />First checkbox</label>_x000D_
      <label for="two">_x000D_
        <input type="checkbox" id="two" />Second checkbox</label>_x000D_
      <label for="three">_x000D_
        <input type="checkbox" id="three" />Third checkbox</label>_x000D_
    </div>_x000D_
  </div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

How to find the operating system version using JavaScript?

I can't comment on @Ian Ippolito answer (because I would have if I had the rep) but according to the document his comment linked, I'm fairly certain you can find the Chrome version for IOS. https://developer.chrome.com/multidevice/user-agent?hl=ja lists the UA as: Mozilla/5.0 (iPhone; CPU iPhone OS 10_3 like Mac OS X) AppleWebKit/602.1.50 (KHTML, like Gecko) CriOS/56.0.2924.75 Mobile/14E5239e Safari/602.1

So this should work:

if ((verOffset = nAgt.indexOf('CriOS')) != -1) {
                //Chrome on iPad spoofing Safari...correct it.
                browser = 'Chrome';
                version = nAgt.substring(verOffset + 6);//should get the criOS ver.
            }

Haven't been able to test (otherwise I would have improved his answer) it to make sure since my iPad is at home and I'm at work, but I thought I'd put it out there.

Images can't contain alpha channels or transparencies

You can remove the alpha channel from a PNG file from the command line with pngcrush, using the flag "-c 2":

$ file input.png
input.png: PNG image data, 1024 x 1024, 8-bit/color RGBA, non-interlaced
$ pngcrush -q -c 2 input.png output.png
libpng warning: iCCP: known incorrect sRGB profile
$ file output.png
output.png: PNG image data, 1024 x 1024, 8-bit/color RGB, non-interlaced

Note the change from RGBA to RGB: the Alpha channel is gone!

pngcrush lives at http://pmt.sourceforge.net/pngcrush/

Easiest way to copy a single file from host to Vagrant guest?

All the above answers might work. But Below is what worked for me. I had multiple vagrant host: host1, host2. I wanted to copy file from ~/Desktop/file.sh to host: host1 I did:

    $vagrant upload ~/Desktop/file.sh host1

This will copy ~/Desktop/file.sh under /home/xxxx where xxx is your vagrant user under host1

Best way to make a shell script daemon?

It really depends on what is the binary itself going to do.

For example I want to create some listener.

The starting Daemon is simple task :

lis_deamon :

#!/bin/bash

# We will start the listener as Deamon process
#    
LISTENER_BIN=/tmp/deamon_test/listener
test -x $LISTENER_BIN || exit 5
PIDFILE=/tmp/deamon_test/listener.pid

case "$1" in
      start)
            echo -n "Starting Listener Deamon .... "
            startproc -f -p $PIDFILE $LISTENER_BIN
            echo "running"
            ;;
          *)
            echo "Usage: $0 start"
            exit 1
            ;;
esac

this is how we start the daemon (common way for all /etc/init.d/ staff)

now as for the listener it self, It must be some kind of loop/alert or else that will trigger the script to do what u want. For example if u want your script to sleep 10 min and wake up and ask you how you are doing u will do this with the

while true ; do sleep 600 ; echo "How are u ? " ; done

Here is the simple listener that u can do that will listen for your commands from remote machine and execute them on local :

listener :

#!/bin/bash

# Starting listener on some port
# we will run it as deamon and we will send commands to it.
#
IP=$(hostname --ip-address)
PORT=1024
FILE=/tmp/backpipe
count=0
while [ -a $FILE ] ; do #If file exis I assume that it used by other program
  FILE=$FILE.$count
  count=$(($count + 1))
done

# Now we know that such file do not exist,
# U can write down in deamon it self the remove for those files
# or in different part of program

mknod $FILE p

while true ; do 
  netcat -l -s $IP -p $PORT < $FILE |/bin/bash > $FILE
done
rm $FILE

So to start UP it : /tmp/deamon_test/listener start

and to send commands from shell (or wrap it to script) :

test_host#netcat 10.184.200.22 1024
uptime
 20:01pm  up 21 days  5:10,  44 users,  load average: 0.62, 0.61, 0.60
date
Tue Jan 28 20:02:00 IST 2014
 punt! (Cntrl+C)

Hope this will help.

Fully custom validation error message with Rails

graywh's answer is the best if it actually locales different in displaying the field name. In the case of a dynamic field name (based on other fields to display), I would do something like this

<% object.errors.each do |attr, msg| %>
<li>
  <% case attr.to_sym %>
  <% when :song_rep_xyz %>
    <%= #display error how you want here %>
  <% else %>
    <%= object.errors.full_message(attr, msg) %>
  <% end %>
</li>
<% end %>

the full_message method on the else is what rails use inside of full_messages method, so it will give out the normal Rails errors for other cases (Rails 3.2 and up)

Getting HTML elements by their attribute names

In jQuery this is so:

$("span['property'=v:name]"); // for selecting your span element

Installing MySQL-python

Python or Python3 with MySQL, you will need these. These libraries use MySQL's connector for C and Python (you need the C libraries installed as well), which overcome some of the limitations of the mysqldb libraries.

   sudo apt-get install libmysqlclient-dev
   sudo apt-get install python-mysql.connector
   sudo apt-get install python3-mysql.connector

How to create a <style> tag with Javascript?

You wrote:

var divNode = document.createElement("div");
divNode.innerHTML = "<br><style>h1 { background: red; }</style>";
document.body.appendChild(divNode);

Why not this?

var styleNode = document.createElement("style");
document.head.appendChild(styleNode);

Henceforward you can append CSS rules easily to the HTML code:

styleNode.innerHTML = "h1 { background: red; }\n";
styleNode.innerHTML += "h2 { background: green; }\n";

...or directly to the DOM:

styleNode.sheet.insertRule("h1 { background: red; }");
styleNode.sheet.insertRule("h2 { background: green; }");

I expect this to work everywhere except archaic browsers.

Definitely works in Chrome in year 2019.

How to take keyboard input in JavaScript?

You should register an event handler on the window or any element that you want to observe keystrokes on, and use the standard key values instead of keyCode. This modified code from MDN will respond to keydown when the left, right, up, or down arrow keys are pressed:

_x000D_
_x000D_
window.addEventListener("keydown", function (event) {_x000D_
  if (event.defaultPrevented) {_x000D_
    return; // Do nothing if the event was already processed_x000D_
  }_x000D_
_x000D_
  switch (event.key) {_x000D_
    case "ArrowDown":_x000D_
      // code for "down arrow" key press._x000D_
      break;_x000D_
    case "ArrowUp":_x000D_
      // code for "up arrow" key press._x000D_
      break;_x000D_
    case "ArrowLeft":_x000D_
      // code for "left arrow" key press._x000D_
      break;_x000D_
    case "ArrowRight":_x000D_
      // code for "right arrow" key press._x000D_
      break;_x000D_
    default:_x000D_
      return; // Quit when this doesn't handle the key event._x000D_
  }_x000D_
_x000D_
  // Cancel the default action to avoid it being handled twice_x000D_
  event.preventDefault();_x000D_
}, true);_x000D_
// the last option dispatches the event to the listener first,_x000D_
// then dispatches event to window
_x000D_
_x000D_
_x000D_

Using strtok with a std::string

I suppose the language is C, or C++...

strtok, IIRC, replace separators with \0. That's what it cannot use a const string. To workaround that "quickly", if the string isn't huge, you can just strdup() it. Which is wise if you need to keep the string unaltered (what the const suggest...).

On the other hand, you might want to use another tokenizer, perhaps hand rolled, less violent on the given argument.

Where to get this Java.exe file for a SQL Developer installation

you can enter the jdk path required as th full path for java.exe in sql developer for oracle 11g.

I found the jdk at the following path in my system.

c:\app\sony\product\11.0.0\db_1\jdk

Vertical Align text in a Label

To do this you should alter the vertical-align property of the input.

<dd><label class="<?=$email_confirm_class;?>" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; border:none;" name="email_confirm" id="email_confirm" size="18" value="<?=$_POST['email_confirm'];?>" tabindex="4" /> *</dd>

Here is a more complete version. It has been tested in IE 8 and it works. see the difference by removing the vertical-align: middle from the input:

<html><head></head><body><dl><dt>test</dt><dd><label class="test" style="text-align:right; padding-right:3px">Confirm Email</label><input class="text" type="text" style="vertical-align: middle; font-size: 22px" name="email_confirm" id="email_confirm" size="28" value="test" tabindex="4" /> *</dd></dl></body></html>

Putting images with options in a dropdown list

You can't do that in plain HTML, but you can do it with jQuery:

JavaScript Image Dropdown

Are you tired with your old fashion dropdown? Try this new one. Image combo box. You can add an icon with each option. It works with your existing "select" element or you can create by JSON object.

R - test if first occurrence of string1 is followed by string2

I think it's worth answering the generic question "R - test if string contains string" here.

For that, use the grep function.

# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"

How to display data from database into textbox, and update it

protected void Page_Load(object sender, EventArgs e)

    {

        DropDownTitle();
    }


protected void DropDownTitle()
{
    if (!Page.IsPostBack)
    {

        string connection = System.Configuration.ConfigurationManager.ConnectionStrings["AuzineConnection"].ConnectionString;

        string selectSQL = "select DISTINCT ForumTitlesID,ForumTitles from ForumTtitle";
        SqlConnection con = new SqlConnection(connection);
        SqlCommand cmd = new SqlCommand(selectSQL, con);
        SqlDataReader reader;
        try
        {

            ListItem newItem = new ListItem();
            newItem.Text = "Select";
            newItem.Value = "0";
            ForumTitleList.Items.Add(newItem);
            con.Open();
            reader = cmd.ExecuteReader();



            while (reader.Read())
            {
                ListItem newItem1 = new ListItem();
                newItem1.Text = reader["ForumTitles"].ToString();
                newItem1.Value = reader["ForumTitlesID"].ToString();
                ForumTitleList.Items.Add(newItem1);



            }
            reader.Close();
            reader.Dispose();
            con.Close();
            con.Dispose();
            cmd.Dispose();


        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }

    }
}

Trying to merge 2 dataframes but get ValueError

In one of your dataframes the year is a string and the other it is an int64 you can convert it first and then join (e.g. df['year']=df['year'].astype(int) or as RafaelC suggested df.year.astype(int))

Edit: Also note the comment by Anderson Zhu: Just in case you have None or missing values in one of your dataframes, you need to use Int64 instead of int. See the reference here.

Looping through all the properties of object php

Here is another way to express the object property.

foreach ($obj as $key=>$value) {
    echo "$key => $obj[$key]\n";
}

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

The correct answer is increasing fastcgi_read_timeout in your Nginx configuration.
Simple as that!

How to backup MySQL database in PHP?

@T.Todua's answer. It's cool. However, it failed to backup my database correctly. Hence, I've modified it. Please use like so: Backup_Mysql_Db::init("localhost","user","pass","db_name","/usr/var/output_dir" ); Thank you.

 <?php            
/**========================================================+
 *                                                         +
 * Static class with functions for backing up database.    +
 *                                                         +
 * PHP Version 5.6.31                                      +
 *=========================================================+*/ 
class Backup_Mysql_Db
{ 
private function __construct() {}  
/**Initializes the database backup
 * @param String $host mysql hostname
 * @param String $user mysql user
 * @param String $pass mysql password
 * @param String $name name of database
 * @param String $outputDir the path to the output directory for storing the backup file
 * @param Array $tables (optional) to backup specific tables only,like: array("mytable1","mytable2",...)  
 * @param String $backup_name (optional) backup filename (otherwise, it creates random name) 
 * EXAMPLE: Backup_Mysql_Db::init("localhost","user","pass","db_name","/usr/var/output_dir" );  
*/  
public static function init($host,$user,$pass,$name, $outputDir, $tables=false, $backup_name=false)
{
    set_time_limit(3000); 
    $mysqli = new mysqli($host,$user,$pass,$name); 
    /* check connection */
    if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        exit();
    }
    //change database to $name
    $mysqli->select_db($name);  
    /* change character set to utf8 */
    if (!$mysqli->set_charset("utf8")) 
    {
        printf("Error loading character set utf8: %s\n", $mysqli->error);
        exit();
    }  
    //list all tables in the database
    $queryTables = $mysqli->query('SHOW TABLES'); 
    while($row = $queryTables->fetch_row()) 
    { 
        $target_tables[] = $row[0];  
    }
    //if user opted to backup specific tables only
    if($tables !== false) 
    { 
        $target_tables = array_intersect( $target_tables, $tables); 
    }  
    date_default_timezone_set('Africa/Accra');//set your timezone
    //$content is the text data to be written to the file for backup
    $content = "-- phpMyAdmin SQL Dump\r\n-- version 4.7.4". //insert your phpMyAdmin version 
           "\r\n-- https://www.phpmyadmin.net/\r\n--\r\n-- Host: ".$host.
           "\r\n-- Generation Time: ".date('M d, Y \a\t h:i A',strtotime(date('Y-m-d H:i:s', time()))).
           "\r\n-- Server version: ".$mysqli->server_info.
           "\r\n-- PHP Version: ". phpversion();
    $content .= "\r\n\r\nSET SQL_MODE = \"NO_AUTO_VALUE_ON_ZERO\";\r\nSET AUTOCOMMIT = 0;\r\nSTART TRANSACTION;\r\nSET time_zone = \"+00:00\";\r\n\r\n\r\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;\r\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;\r\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;\r\n/*!40101 SET NAMES utf8mb4 */;\r\n\r\n--\r\n-- Database: `".
                $name."`\r\n--\r\nCREATE DATABASE IF NOT EXISTS `".
                $name."` DEFAULT CHARACTER SET latin1 COLLATE latin1_swedish_ci;\r\nUSE `".
                $name."`;"; 
    //traverse through every table in the database
    foreach($target_tables as $table)
    {
        if (empty($table)){ continue; } 
        $result = $mysqli->query('SELECT * FROM `'.$table.'`');     
        //get the number of columns
        $fields_amount=$result->field_count;
        //get the number of affected rows in the MySQL operation
        $rows_num=$mysqli->affected_rows;   
        //Retrieve the Table Definition of the existing table 
        $res = $mysqli->query('SHOW CREATE TABLE '.$table); 
        $TableMLine=$res->fetch_row(); 
        $content .= "\r\n\r\n-- --------------------------------------------------------\r\n\r\n"."--\r\n-- Table structure for table `".$table."`\r\n--\r\n\r\n";
        //if the table is not empty
        if(!self::table_is_empty($table,$mysqli))  
        {   $content .= $TableMLine[1].";\n\n";//append the Table Definition 
            //replace, case insensitively
            $content =str_ireplace("CREATE TABLE `".$table."`",//wherever you find this
                                    "DROP TABLE IF EXISTS `".$table."`;\r\nCREATE TABLE IF NOT EXISTS `".$table."`",//replace with that
                                    $content);//in this  
            $content .= "--\r\n-- Dumping data for table `".$table."`\r\n--\r\n"; 
            $content .= "\nINSERT INTO `".$table."` (".self::get_columns_from_table($table, $mysqli)." ) VALUES\r\n".self::get_values_from_table($table,$mysqli); 
        } 
        else//otherwise if the table is empty
        {
            $content .= $TableMLine[1].";";  
            //replace, case insensitively
            $content =str_ireplace("CREATE TABLE `".$table."`",//wherever you find this
                                    "DROP TABLE IF EXISTS `".$table."`;\r\nCREATE TABLE IF NOT EXISTS `".$table."`",//replace with that
                                    $content);//in this  
        } 
    }
    $content .= "\r\n\r\n/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\r\n/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\r\n/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;";
    date_default_timezone_set('Africa/Accra');
    //format the time at this very moment and get rid of the colon ( windows doesn't allow colons in filenames)
    $date = str_replace(":", "-", date('jS M, y. h:i:s A.',strtotime(date('Y-m-d H:i:s', time())))); 
    //if there's a backup name, use it , otherwise device one
    $backup_name = $backup_name ? $backup_name : $name.'___('.$date.').sql'; 
    //Get current buffer contents and delete current output buffer
    ob_get_clean();     
    self::saveFile($content, $backup_name, $outputDir); 
    exit; 
}

/** Save data to file. 
 * @param String $data The text data to be stored in the file 
 * @param String $backup_name The name of the backup file 
 * @param String $outputDir (optional) The directory to save the file to. 
 * If unspecified, will save in the current directory. 
 * */ 
private static function saveFile(&$data,$backup_name, $outputDir = '.') 
{
    if (!$data)
    {
        return false; 
    } 
    try 
    { 
        $handle = fopen($outputDir . '/'. $backup_name , 'w+');
        fwrite($handle, $data);
        fclose($handle);
    } catch (Exception $e) 
    {
      var_dump($e->getMessage());
      return false;
    }
    return true;
}
/**Checks if table is empty
 * @param String $table table in mysql database
 * @return Boolean true if table is empty, false otherwise   
*/ 
private static function table_is_empty($table,$mysqli)
{
    $sql = "SELECT * FROM $table";
    $result = mysqli_query($mysqli, $sql);  
    if($result) 
    {    
        if(mysqli_num_rows($result) > 0)
        {  
            return false; 
        }
        else 
        {    
            return true; 
        }
    }
    return false;  
}
/**Retrieves the columns in the table 
 * @param String $table table in mysql database
 * @return String a list of all the columns in the right format    
*/ 
private static function get_columns_from_table($table, $mysqli)
{ 
    $column_header = "";
    $result = mysqli_query($mysqli, "SHOW COLUMNS FROM $table");  
    while($row = $result->fetch_row()) 
    { 
        $column_header .= "`".$row[0]."`, "; 
    }
    //remove leading and trailing whitespace, and remove the last comma in the string
    return rtrim(trim($column_header),','); 
} 

/**Retrieves the values in the table row by row in the table 
 * @param String $table table in mysql database
 * @return String a list of all the values in the table in the right format    
*/
private static function get_values_from_table($table, $mysqli)
{
    $values = ""; 
    $columns = [];
    //get all the columns in the table
    $result = mysqli_query($mysqli, "SHOW COLUMNS FROM $table");  
    while($row = $result->fetch_row()) 
    { 
        array_push($columns,$row[0] ); 
    } 

    $result1 = mysqli_query($mysqli, "SELECT * FROM $table");  
    //while traversing every row in the table(row by row)
    while($row = mysqli_fetch_array($result1))
    {   $values .= "("; 
        //get the values in each column
        foreach($columns as $col)
        {               //if the value is an Integer
            $values .=  (self::column_is_of_int_type($table, $col,$mysqli)? 
                    $row["$col"].", "://do not surround it with single quotes
                    "'".$row["$col"]."', "); //otherwise, surround it with single quotes 
        }   
        $values = rtrim(trim($values),','). "),\r\n";  
    }  
    return rtrim(trim($values),',').";"; 
}

/**Checks if the data type in the column is an integer
 * @param String $table table in mysql database
 * @return Boolean true if it is an integer, false otherwise. 
*/
private static function column_is_of_int_type($table, $column,$mysqli)
{
    $q = mysqli_query($mysqli,"DESCRIBE $table");  
    while($row = mysqli_fetch_array($q)) 
    {
        if ($column === "{$row['Field']}")
        {
            if (strpos("{$row['Type']}", 'int') !== false) 
            {
                return true;
            }
        } 
    }
    return false; 
} 

}

How to list all Git tags?

To list tags I prefer:

git tag -n

The -n flag displays the first line of the annotation message along with the tag, or the first commit message line if the tag is not annotated.

You can also do git tag -n5 to show the first 5 lines of the annotation.

Printing Python version in output

import sys  

expanded version

sys.version_info  
sys.version_info(major=3, minor=2, micro=2, releaselevel='final', serial=0)

specific

maj_ver = sys.version_info.major  
repr(maj_ver) 
'3'  

or

print(sys.version_info.major)
'3'

or

version = ".".join(map(str, sys.version_info[:3]))
print(version)
'3.2.2'

Calling Non-Static Method In Static Method In Java

You can't get around this restriction directly, no. But there may be some reasonable things you can do in your particular case.

For example, you could just "new up" an instance of your class in the static method, then call the non-static method.

But you might get even better suggestions if you post your class(es) -- or a slimmed-down version of them.

How to launch jQuery Fancybox on page load?

You can also use the native JavaScript function setTimeout() to delay the display of the box after the DOM is ready.

<a id="reference-first" href="#reference-first-message">Test the Popup</a>

<div style="display: none;">
    <div id="reference-first-message" style="width:400px;height:100px;overflow:auto;">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam quis mi eu elit tempor facilisis id et neque. Nulla sit amet sem sapien. Vestibulum imperdiet porta ante ac ornare. Nulla et lorem eu nibh adipiscing ultricies nec at lacus. Cras laoreet ultricies sem, at blandit mi eleifend aliquam. Nunc enim ipsum, vehicula non pretium varius, cursus ac tortor. Vivamus fringilla congue laoreet. Quisque ultrices sodales orci, quis rhoncus justo auctor in. Phasellus dui eros, bibendum eu feugiat ornare, faucibus eu mi. Nunc aliquet tempus sem, id aliquam diam varius ac. Maecenas nisl nunc, molestie vitae eleifend vel, iaculis sed magna. Aenean tempus lacus vitae orci posuere porttitor eget non felis. Donec lectus elit, aliquam nec eleifend sit amet, vestibulum sed nunc.
    </div>
</div>

<script type="text/javascript">
    $(document).ready(function() {
        $("#reference-first").fancybox({
            'titlePosition'         : 'inside',
            'transitionIn'          : 'fade',
            'transitionOut'         : 'fade',
            'overlayColor'          : '#333',
            'overlayOpacity'        : 0.9
        }).trigger("click");

        //launch on load after 5 second delay
        window.setTimeout('$("#reference-first")', 5000);
    });
</script>

This Row already belongs to another table error when trying to add rows?

you can give some id to the columns and name it uniquely.

Spring 3 RequestMapping: Get path value

Non-matched part of the URL is exposed as a request attribute named HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE:

@RequestMapping("/{id}/**")
public void foo(@PathVariable("id") int id, HttpServletRequest request) {
    String restOfTheUrl = (String) request.getAttribute(
        HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    ...
}

ORA-12505, TNS:listener does not currently know of SID given in connect descriptor

Faced similar error, any of the above solutions didn't help. There was a problem in the listner.ora file. By mistake I had added SID out of the SID_LIST see below(section between the stars *).

 SID_LIST_LISTENER =
      (SID_LIST =

        (SID_DESC =
          (SID_NAME = PLSExtProc)
          (ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server)
          (PROGRAM = extproc)
        )
        (SID_DESC =
          (SID_NAME = CLRExtProc)
          (ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server)
          (PROGRAM = extproc)
        )
        )

 *(SID_DESC =
           (SID_NAME = XE)
           (ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server)
         )*
    LISTENER =
      (DESCRIPTION_LIST =
        (DESCRIPTION =
          (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
          (ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521))
        )
      )


    DEFAULT_SERVICE_LISTENER = (XE)

Corrected this error as below:

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
       (SID_NAME = XE)
       (ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server)
     )
    (SID_DESC =
      (SID_NAME = PLSExtProc)
      (ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server)
      (PROGRAM = extproc)
    )
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = C:\oraclexe\app\oracle\product\11.2.0\server)
      (PROGRAM = extproc)
    )
    )
LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1))
      (ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521))
    )
  )


DEFAULT_SERVICE_LISTENER = (XE)

Stopped and the database enter image description here

Stopped the listeners OracleServiceXE and OracleXETNSListener manually as it did not stop automatically by going to Control Panel\All Control Panel Items\Administrative Tools\Services. Restarted the database and it worked like a charm.

cURL error 60: SSL certificate: unable to get local issuer certificate

Have you tried..

curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);

If you are consuming a trusted source you can skip the verify.

What does $_ mean in PowerShell?

$_ is a variable created by the system usually inside block expressions that are referenced by cmdlets that are used with pipe such as Where-Object and ForEach-Object.

But it can be used also in other types of expressions, for example with Select-Object combined with expression properties. Get-ChildItem | Select-Object @{Name="Name";Expression={$_.Name}}. In this case the $_ represents the item being piped but multiple expressions can exist.

It can also be referenced by custom parameter validation, where a script block is used to validate a value. In this case the $_ represents the parameter value as received from the invocation.

The closest analogy to c# and java is the lamda expression. If you break down powershell to basics then everything is a script block including a script file a, functions and cmdlets. You can define your own parameters but in some occasions one is created by the system for you that represents the input item to process/evaluate. In those situations the automatic variable is $_.

What is SYSNAME data type in SQL Server?

Another use case is when using the SQL Server 2016+ functionality of AT TIME ZONE

The below statement will return a date converted to GMT

SELECT 
CONVERT(DATETIME, SWITCHOFFSET([ColumnA], DATEPART(TZOFFSET, [ColumnA] AT TIME ZONE 'GMT Standard Time')))

If you want to pass the time zone as a variable, say:

SELECT 
CONVERT(DATETIME, SWITCHOFFSET([ColumnA], DATEPART(TZOFFSET, [ColumnA] AT TIME ZONE @TimeZone)))

then that variable needs to be of the type sysname (declaring it as varchar will cause an error).

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

I have also faced this issue. I resolved this following step.

Check android sdk path in Environment Veritable.

Add ANDROID_HOME = C:\Users\user_name\AppData\Local\Android\Sdk in System Variable
and C:\Users\user_name\AppData\Local\Android\Sdk\platform-tools path in System Variable

replace sharedBlacklist as below code segment,

var sharedBlacklist = [
  /node_modules[\/\\]react[\/\\]dist[\/\\].*/,
  /website\/node_modules\/.*/,
  /heapCapture\/bundle\.js/,
  /.*\/__tests__\/.*/
];

in node_modules/metro-config/src/default/blacklist.js

Then run npx react-native run-android --port 9001

Happy Coding..!

Checking if a variable exists in javascript

I'm writing an answer only because I do not have enough reputations to comment the accepted answer from apsillers. I agree with his answer, but

If you really want to test if a variable is undeclared, you'll need to catch the ReferenceError ...

is not the only way. One can do just:

this.hasOwnProperty("bar")

to check if there is a variable bar declared in the current context. (I'm not sure, but calling the hasOwnProperty could also be more fast/effective than raising an exception) This works only for the current context (not for the whole current scope).

How to sort an object array by date property?

I personally use following approach to sort dates.

let array = ["July 11, 1960", "February 1, 1974", "July 11, 1615", "October 18, 1851", "November 12, 1995"];

array.sort(function(date1, date2) {
   date1 = new Date(date1);
   date2 = new Date(date2);
   if (date1 > date2) return 1;
   if (date1 < date2) return -1;
})

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

Actually, you need to update your repo first, then an upgrade of your Glibc can fix this issue.

how to console.log result of this ajax call?

try something like this :

$.ajax({
    type: 'POST',
    url: 'loginCheck',
    data: $(formLogin).serialize(),
    dataType: 'json',
    success: function (textStatus, status) {
        console.log(textStatus);
        console.log(status);
    },
    error: function(xhr, textStatus, error) {
        console.log(xhr.responseText);
        console.log(xhr.statusText);
        console.log(textStatus);
        console.log(error);
    }
});

Eclipse - java.lang.ClassNotFoundException

The solution to my problem which was similar: the libs were invalid. If you look in the .classpath file of the project, you'll see classpathentry tags with the key/value kind="lib". Some of mine were incorrect.

I didn't discover this until I turned off Validation settings. That is, there were so many errors in the JSP files, etc, that the classpath errors weren't evident (or possibly even showing up). As a result, nothing was being compiled into the destination output folders, but no helpful errors on why.

Global variables in c#.net

You can create a base class in your application that inherits from System.Web.UI.Page. Let all your pages inherit from the newly created base class. Add a property or a variable to your base class with propected access modifier, so that it will be accessed from all your pages in the application.

Javascript - User input through HTML input tag to set a Javascript variable?

I tried to send/add input tag's values into JavaScript variable which worked well for me, here is the code:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function changef()
            {
            var ctext=document.getElementById("c").value;

            document.writeln(ctext);
            }

        </script>
    </head>
    <body>
        <input type="text" id="c" onchange="changef"();>

        <button type="button" onclick="changef()">click</button>
    </body> 
</html>

Difference between System.DateTime.Now and System.DateTime.Today

DateTime.Today is DateTime.Now with time set to zero.

It is important to note that there is a difference between a DateTime value, which represents the number of ticks that have elapsed since midnight of January 1, 0000, and the string representation of that DateTime value, which expresses a date and time value in a culture-specific-specific format: https://msdn.microsoft.com/en-us/library/system.datetime.now%28v=vs.110%29.aspx

DateTime.Now.Ticks is the actual time stored by .net (essentially UTC time), the rest are just representations (which are important for display purposes).

If the Kind property is DateTimeKind.Local it implicitly includes the time zone information of the local computer. When sending over a .net web service, DateTime values are by default serialized with time zone information included, e.g. 2008-10-31T15:07:38.6875000-05:00, and a computer in another time zone can still exactly know what time is being referred to.

So, using DateTime.Now and DateTime.Today is perfectly OK.

You usually start running into trouble when you begin confusing the string representation with the actual value and try to "fix" the DateTime, when it isn't broken.

How to use local docker images with Minikube?

In addition to the accepted answer, you can also achieve what you originally wanted (creating a deployment using the run command) with the following command:

kubectl run hdfs --image=fluxcapacitor/hdfs:latest --port=8989 --generator=run-pod/v1 

I found the information about the generator on the Kubernetes-dev forum:

If you're using kubectl run, it generates a manifest for you that happens to have imagePullPolicy set to Always by default. You can use this command to get an imagePullPolicy of IfNotPresent, which will work for minikube:

kubectl run --image=<container> --generator=run-pod/v1

Dan Lorenc

https://groups.google.com/forum/#!topic/kubernetes-dev/YfvWuFr_XOM

MySql Query Replace NULL with Empty String in Select

I know this is old question but i got best solution without change query and also support for SELECT * statement

foreach ($row as &$value) {
  if($value==null){
     $value="";
  }
}

MySQL search and replace some text in a field

 UPDATE table SET field = replace(field, text_needs_to_be_replaced, text_required);

Like for example, if I want to replace all occurrences of John by Mark I will use below,

UPDATE student SET student_name = replace(student_name, 'John', 'Mark');

Angular2 Material Dialog css, dialog size

You can also let angular material solve the size itself depending on the content. This means you don't have to cloud your TS files with sizes that depend on your UI. You can keep these in the HTML/CSS.

my-dialog.html

<div class="myContent">
  <h1 mat-dialog-title fxLayoutAlign="center">Your title</h1>
  <form [formGroup]="myForm" fxLayout="column">
    <div mat-dialog-content>
    </div mat-dialog-content>
  </form>
</div>

my-dialog.scss

.myContent {
    width: 300px;
    height: 150px;
}

my-component.ts

const myInfo = {};
this.dialog.open(MyDialogComponent, { data: myInfo });

How to get the IP address of the server on which my C# application is running on?

Here is how i solved it. i know if you have several physical interfaces this might not select the exact eth you want.

private string FetchIP()
{
    //Get all IP registered
    List<string> IPList = new List<string>();
    IPHostEntry host;
    host = Dns.GetHostEntry(Dns.GetHostName());
    foreach (IPAddress ip in host.AddressList)
    {
        if (ip.AddressFamily == AddressFamily.InterNetwork)
        {
            IPList.Add(ip.ToString());
        }
    }

    //Find the first IP which is not only local
    foreach (string a in IPList)
    {
        Ping p = new Ping();
        string[] b = a.Split('.');
        string ip2 = b[0] + "." + b[1] + "." + b[2] + ".1";
        PingReply t = p.Send(ip2);
        p.Dispose();
        if (t.Status == IPStatus.Success && ip2 != a)
        {
            return a;
        }
    }
    return null;
}

how to display data values on Chart.js

From chart.js samples (file Chart.js-2.4.0/samples/data_labelling.html) :

``` // Define a plugin to provide data labels

    Chart.plugins.register({
        afterDatasetsDraw: function(chartInstance, easing) {
            // To only draw at the end of animation, check for easing === 1
            var ctx = chartInstance.chart.ctx;

            chartInstance.data.datasets.forEach(function (dataset, i) {
                var meta = chartInstance.getDatasetMeta(i);
                if (!meta.hidden) {
                    meta.data.forEach(function(element, index) {
                        // Draw the text in black, with the specified font
                        ctx.fillStyle = 'rgb(0, 0, 0)';

                        var fontSize = 16;
                        var fontStyle = 'normal';
                        var fontFamily = 'Helvetica Neue';
                        ctx.font = Chart.helpers.fontString(fontSize, fontStyle, fontFamily);

                        // Just naively convert to string for now
                        var dataString = dataset.data[index].toString();

                        // Make sure alignment settings are correct
                        ctx.textAlign = 'center';
                        ctx.textBaseline = 'middle';

                        var padding = 5;
                        var position = element.tooltipPosition();
                        ctx.fillText(dataString, position.x, position.y - (fontSize / 2) - padding);
                    });
                }
            });
        }
    });

```

How do I clear all options in a dropdown box?

If you are using JQuery and your select control has ID "DropList" you can remove its options doing this way:

$('#DropList option').remove();

Actually it works for me with any option list, like datalist.

Hope it helps.

Can you blur the content beneath/behind a div?

you can do this with css3, this blurs the whole element

div (or whatever element) {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
}

Fiddle: http://jsfiddle.net/H4DU4/

Check if program is running with bash shell script?

If you want to execute that command, you should probably change:

PROCESS_NUM='ps -ef | grep "$1" | grep -v "grep" | wc -l'

to:

PROCESS_NUM=$(ps -ef | grep "$1" | grep -v "grep" | wc -l)

Format a message using MessageFormat.format() in Java

For everyone that has Android problems in the string.xml, use \'\' instead of single quote.

Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

Generic

C code. Using 1 byte input data num as example.

    unsigned char num = 0xaa;   // 1010 1010 (aa) -> 0101 0101 (55)
    int s = sizeof(num) * 8;    // get number of bits
    int i, x, y, p;
    int var = 0;                // make var data type to be equal or larger than num

    for (i = 0; i < (s / 2); i++) {
        // extract bit on the left, from MSB
        p = s - i - 1;
        x = num & (1 << p);
        x = x >> p;
        printf("x: %d\n", x);

        // extract bit on the right, from LSB
        y = num & (1 << i);
        y = y >> i;
        printf("y: %d\n", y);

        var = var | (x << i);       // apply x
        var = var | (y << p);       // apply y
    }

    printf("new: 0x%x\n", new);

Is it possible to disable scrolling on a ViewPager

The best solution that worked for me is:

public class DeactivatedViewPager extends ViewPager {

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

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

    @Override
    public boolean canScrollHorizontally(int direction) {
        return false;
    }
}

After this the scroll will be disabled by touch and then you can still use setCurrentItem method to change page.

Angular-cli from css to scss

For existing projects:

In angular.json file

  1. In build part and in test part, replace:

    "styles": ["src/styles.css"], by "styles": ["src/styles.scss"],

  2. Replace:

    "schematics": {}, by "schematics": { "@schematics/angular:component": { "style": "scss" } },

Using ng config schematics.@schematics/angular:component.styleext scss command works but it does not place the configuration in the same place.

In your project rename your .css files to .scss

For a new project, this command do all the work:

ng n project-name --style=scss

For global configuration

New versions seems to not have a global command

Command not found when using sudo

Permission denied

In order to run a script the file must have an executable permission bit set.

In order to fully understand Linux file permissions you can study the documentation for the chmod command. chmod, an abbreviation of change mode, is the command that is used to change the permission settings of a file.

To read the chmod documentation for your local system , run man chmod or info chmod from the command line. Once read and understood you should be able to understand the output of running ...

ls -l foo.sh

... which will list the READ, WRITE and EXECUTE permissions for the file owner, the group owner and everyone else who is not the file owner or a member of the group to which the file belongs (that last permission group is sometimes referred to as "world" or "other")

Here's a summary of how to troubleshoot the Permission Denied error in your case.

$ ls -l foo.sh                    # Check file permissions of foo
-rw-r--r-- 1 rkielty users 0 2012-10-21 14:47 foo.sh 
    ^^^ 
 ^^^ | ^^^   ^^^^^^^ ^^^^^
  |  |  |       |       | 
Owner| World    |       |
     |          |    Name of
   Group        |     Group
             Name of 
              Owner 

Owner has read and write access rw but the - indicates that the executable permission is missing

The chmod command fixes that. (Group and other only have read permission set on the file, they cannot write to it or execute it)

$ chmod +x foo.sh               # The owner can set the executable permission on foo.sh
$ ls -l foo.sh                  # Now we see an x after the rw 
-rwxr-xr-x 1 rkielty users 0 2012-10-21 14:47 foo.sh
   ^  ^  ^

foo.sh is now executable as far as Linux is concerned.

Using sudo results in Command not found

When you run a command using sudo you are effectively running it as the superuser or root.

The reason that the root user is not finding your command is likely that the PATH environment variable for root does not include the directory where foo.sh is located. Hence the command is not found.

The PATH environment variable contains a list of directories which are searched for commands. Each user sets their own PATH variable according to their needs. To see what it is set to run

env | grep ^PATH

Here's some sample output of running the above env command first as an ordinary user and then as the root user using sudo

rkielty@rkielty-laptop:~$ env | grep ^PATH
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games

rkielty@rkielty-laptop:~$ sudo env | grep ^PATH
[sudo] password for rkielty: 
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/X11R6/bin

Note that, although similar, in this case the directories contained in the PATH the non-privileged user (rkielty) and the super user are not the same.

The directory where foo.sh resides is not present in the PATH variable of the root user, hence the command not found error.

What is the largest possible heap size with a 64-bit JVM?

In theory everything is possible but reality you find the numbers much lower than you might expect. I have been trying to address huge spaces on servers often and found that even though a server can have huge amounts of memory it surprised me that most software actually never can address it in real scenario's simply because the cpu's are not fast enough to really address them. Why would you say right ?! . Timings thats the endless downfall of every enormous machine which i have worked on. So i would advise to not go overboard by addressing huge amounts just because you can, but use what you think could be used. Actual values are often much lower than what you expected. Ofcourse non of us really uses hp 9000 systems at home and most of you actually ever will go near the capacity of your home system ever. For instance most users do not have more than 16 Gb of memory in their system. Ofcourse some of the casual gamers use work stations for a game once a month but i bet that is a very small percentage. So coming down to earth means i would address on a 8 Gb 64 bit system not much more than 512 mb for heapspace or if you go overboard try 1 Gb. I am pretty sure its even with these numbers pure overkill. I have constant monitored the memory usage during gaming to see if the addressing would make any difference but did not notice any difference at all when i addressed much lower values or larger ones. Even on the server/workstations there was no visible change in performance no matter how large i set the values. That does not say some jave users might be able to make use of more space addressed, but this far i have not seen any of the applications needing so much ever. Ofcourse i assume that their would be a small difference in performance if java instances would run out of enough heapspace to work with. This far i have not found any of it at all, however lack of real installed memory showed instant drops of performance if you set too much heapspace. When you have a 4 Gb system you run quickly out of heapspace and then you will see some errors and slowdowns because people address too much space which actually is not free in the system so the os starts to address drive space to make up for the shortage hence it starts to swap.

Can I execute a function after setState is finished updating?

render will be called every time you setState to re-render the component if there are changes. If you move your call to drawGrid there rather than calling it in your update* methods, you shouldn't have a problem.

If that doesn't work for you, there is also an overload of setState that takes a callback as a second parameter. You should be able to take advantage of that as a last resort.

Simple example for Intent and Bundle

For example :

In MainActivity :

Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra(OtherActivity.KEY_EXTRA, yourDataObject);
startActivity(intent);

In OtherActivity :

public static final String KEY_EXTRA = "com.example.yourapp.KEY_BOOK";

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);

  String yourDataObject = null;

  if (getIntent().hasExtra(KEY_EXTRA)) {
      yourDataObject = getIntent().getStringExtra(KEY_EXTRA);
  } else {
      throw new IllegalArgumentException("Activity cannot find  extras " + KEY_EXTRA);
  }
  // do stuff
}

More informations here : http://developer.android.com/reference/android/content/Intent.html

SQL Server: use CASE with LIKE

Add an END at last before alias name.

CASE WHEN countries LIKE '%'+@selCountry+'%' 
     THEN 'national' ELSE 'regional' 
END AS validity

For example:

SELECT CASE WHEN countries LIKE '%'+@selCountry+'%' 
       THEN 'national' ELSE 'regional' 
       END AS validity
FROM TableName

How to change the hosts file on android

You have root, but you still need to remount /system to be read/write

$ adb shell
$ su
$ mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system

Go here for more information: Mount a filesystem read-write.

Two arrays in foreach loop

Instead of foreach loop, try this (only when your arrays have same length).

$number = COUNT($_POST["codes "]);//count how many arrays available
if($number > 0)  
{  
  for($i=0; $i<$number; $i++)//loop thru each arrays
  {
    $codes =$_POST['codes'][$i];
    $names =$_POST['names'][$i];
    //ur code in here
  }
}

Maintain image aspect ratio when changing height

No need to add a containing div.

The default for the css "align-items" property is "stretch" which is what is causing your images to be stretched to its full original height. Setting the css "align-items" property to "flex-start" fixes your issue.

.slider {
    display: flex;
    align-items: flex-start;  /* ADD THIS! */
}

Difference between char* and const char*?

The first you can actually change if you want to, the second you can't. Read up about const correctness (there's some nice guides about the difference). There is also char const * name where you can't repoint it.

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

Useful link here: Access Tomcat Manager App from different host

From Tomcat version 8 onward's, manager/html url won't be accessible to anyone except localhost.

In order to access /manager/html url, you need to do below change in context.xml of manager app. 1. Go to /apache-tomcat-8.5.23/webapps/manager/META-INF location, then edit context.xml

<Context antiResourceLocking="false" privileged="true" >
  <Valve className="org.apache.catalina.valves.RemoteAddrValve"
         allow="^.*$" />
 ......
</Context>
  1. Restart the server.

Disabling Chrome cache for website development

In addition to the disable cache option (which you get to via a button in the lower right corner of the developer tools window -- Tools | Developer Tools, or Ctrl + Shift + I), on the network pane of the developer tools you can now right click and choose "Clear Cache" from the popup menu.

How can I remove punctuation from input text in Java?

This first removes all non-letter characters, folds to lowercase, then splits the input, doing all the work in a single line:

String[] words = instring.replaceAll("[^a-zA-Z ]", "").toLowerCase().split("\\s+");

Spaces are initially left in the input so the split will still work.

By removing the rubbish characters before splitting, you avoid having to loop through the elements.

Should URL be case sensitive?

According to W3's "HTML and URLs" they should:

There may be URLs, or parts of URLs, where case doesn't matter, but identifying these may not be easy. Users should always consider that URLs are case-sensitive.

django templates: include and extends

When you use the extends template tag, you're saying that the current template extends another -- that it is a child template, dependent on a parent template. Django will look at your child template and use its content to populate the parent.

Everything that you want to use in a child template should be within blocks, which Django uses to populate the parent. If you want use an include statement in that child template, you have to put it within a block, for Django to make sense of it. Otherwise it just doesn't make sense and Django doesn't know what to do with it.

The Django documentation has a few really good examples of using blocks to replace blocks in the parent template.

https://docs.djangoproject.com/en/dev/ref/templates/language/#template-inheritance

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function

From what you've said so far, it sounds like a problem where the MySQL driver in PHP5.3 has trouble connecting to the older MySQL version 4.1. Have a look on http://www.bitshop.com/Blogs/tabid/95/EntryId/67/PHP-mysqlnd-cannot-connect-to-MySQL-4-1-using-old-authentication.aspx

There's a similar question here with some useful answers, Cannot connect to MySQL 4.1+ using old authentication

SELECT `User`, `Host`, Length(`Password`) FROM mysql.user

This will return 16 for accounts with old passwords and 41 for accounts with new passwords (and 0 for accounts with no password at all, you might want to take care of those as well). Either use the user managements tools of the MySQL front end (if there are any) or

SET PASSWORD FOR 'User'@'Host'=PASSWORD('yourpassword');
FLUSH Privileges

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

In my case, the local loopback interface wasn't started, so "localhost" couldn't be resolved. You can check this by running "ifconfig" and you should see an interface called "lo". If it is not up, you can activate it by running "ifup lo" or "ifconfig lo up".

Latex Multiple Linebreaks

Maybe try inserting lines with only a space?

\ \\
\ \\

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

Using domain Name may solve the problem (get domain name using powershell: $env:userdomain):

    Hashtable<String, Object> env = new Hashtable<String, Object>();
    String principalName = "domainName\\userName";
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "ldap://URL:389/OU=ou-xx,DC=fr,DC=XXXXXX,DC=com");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, principalName);
    env.put(Context.SECURITY_CREDENTIALS, "Your Password");

    try {
        DirContext authContext = new InitialDirContext(env);
        // user is authenticated
        System.out.println("USER IS AUTHETICATED");
    } catch (AuthenticationException ex) {
        // Authentication failed
        System.out.println("AUTH FAILED : " + ex);

    } catch (NamingException ex) {
        ex.printStackTrace();
    }

How to hide a div from code (c#)

In code behind:

{
    yourDiv.Visible = false;
}