Programs & Examples On #Text parsing

Text parsing is a variation of parsing which refers to the action of breaking a stream of text into different components, and capturing the relationship between those components.

How to delete from a text file, all lines that contain a specific string?

You can also use this:

 grep -v 'pattern' filename

Here -v will print only other than your pattern (that means invert match).

Can .NET load and parse a properties file equivalent to Java Properties class?

No there is not : But I have created one easy class to help :

public class PropertiesUtility
{
    private static Hashtable ht = new Hashtable();
    public void loadProperties(string path)
    {
        string[] lines = System.IO.File.ReadAllLines(path);
        bool readFlag = false;
        foreach (string line in lines)
        {
            string text = Regex.Replace(line, @"\s+", "");
            readFlag =  checkSyntax(text);
            if (readFlag)
            {
                string[] splitText = text.Split('=');
                ht.Add(splitText[0].ToLower(), splitText[1]);
            }
        }
    }

    private bool checkSyntax(string line)
    {
        if (String.IsNullOrEmpty(line) || line[0].Equals('['))
        {
            return false;
        }

        if (line.Contains("=") && !String.IsNullOrEmpty(line.Split('=')[0]) && !String.IsNullOrEmpty(line.Split('=')[1]))
        {
            return true;
        }
        else
        {
            throw new Exception("Can not Parse Properties file please verify the syntax");
        }
    }

    public string getProperty(string key)
    {
        if (ht.Contains(key))
        {
            return ht[key].ToString();
        }
        else
        {
            throw new Exception("Property:" + key + "Does not exist");
        }

    }
}

Hope this helps.

How do I correct this Illegal String Offset?

if(isset($rule["type"]) && ($rule["type"] == "radio") || ($rule["type"] == "checkbox") )
{
    if(!isset($data[$field]))
        $data[$field]="";
}

What are these ^M's that keep showing up in my files in emacs?

If you don't have dos2unix utility installed on your system, you can create your own to get rid of Windows endline characters:

vi ~/dos2unix.bash:

with the following content

#!/bin/bash
tr -d '\r' < $1 > repl.tmp
mv -f repl.tmp $1

In your ~/.bashrc, add the line:

alias 'dos2unix=~/dos2unix.bash'

Applying

dos2unix file_from_PC.txt

will remove ^M characters at lines ends in file_from_PC.txt. You can check if you have those or not by using cat:

cat -v file_from_PC.txt

Regular expression for exact match of a string

A more straight forward way is to check for equality

if string1 == string2
  puts "match"
else
  puts "not match"
end

however, if you really want to stick to regular expression,

string1 =~ /^123456$/

Delete first character of a string in Javascript

_x000D_
_x000D_
String.prototype.trimStartWhile = function(predicate) {_x000D_
    if (typeof predicate !== "function") {_x000D_
     return this;_x000D_
    }_x000D_
    let len = this.length;_x000D_
    if (len === 0) {_x000D_
        return this;_x000D_
    }_x000D_
    let s = this, i = 0;_x000D_
    while (i < len && predicate(s[i])) {_x000D_
     i++;_x000D_
    }_x000D_
    return s.substr(i)_x000D_
}_x000D_
_x000D_
let str = "0000000000ABC",_x000D_
    r = str.trimStartWhile(c => c === '0');_x000D_
    _x000D_
console.log(r);
_x000D_
_x000D_
_x000D_

pandas three-way joining multiple dataframes on columns

You could try this if you have 3 dataframes

# Merge multiple dataframes
df1 = pd.DataFrame(np.array([
    ['a', 5, 9],
    ['b', 4, 61],
    ['c', 24, 9]]),
    columns=['name', 'attr11', 'attr12'])
df2 = pd.DataFrame(np.array([
    ['a', 5, 19],
    ['b', 14, 16],
    ['c', 4, 9]]),
    columns=['name', 'attr21', 'attr22'])
df3 = pd.DataFrame(np.array([
    ['a', 15, 49],
    ['b', 4, 36],
    ['c', 14, 9]]),
    columns=['name', 'attr31', 'attr32'])

pd.merge(pd.merge(df1,df2,on='name'),df3,on='name')

alternatively, as mentioned by cwharland

df1.merge(df2,on='name').merge(df3,on='name')

Converting characters to integers in Java

Try any one of the below. These should work:

int a = Character.getNumericValue('3');
int a = Integer.parseInt(String.valueOf('3');

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

Java Revisited

  1. Resource included by include directive is loaded during jsp translation time, while resource included by include action is loaded during request time.
  2. Any change on included resource will not be visible in case of include directive until jsp file compiles again. While in case of include action, any change in included resource will be visible in next request.
  3. Include directive is static import, while include action is dynamic import
  4. Include directive uses file attribute to specify resource to be included while include action use page attribute for same purpose.

What is the best way to conditionally apply attributes in AngularJS?

In the latest version of Angular (1.1.5), they have included a conditional directive called ngIf. It is different from ngShow and ngHide in that the elements aren't hidden, but not included in the DOM at all. They are very useful for components which are costly to create but aren't used:

<h1 ng-if="editMode" contenteditable=true>{{content.title}}</h1>

How to make an HTTP request + basic auth in Swift

go plain for SWIFT 3 and APACHE simple Auth:

func urlSession(_ session: URLSession, task: URLSessionTask,
                didReceive challenge: URLAuthenticationChallenge,
                completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

    let credential = URLCredential(user: "test",
                                   password: "test",
                                   persistence: .none)

    completionHandler(.useCredential, credential)


}

Tried to Load Angular More Than Once

I had this problem when missing a closing tag in the html.

enter image description here

So instead of:

<table></table> 

..my HTML was

<table>...<table>

Tried to load jQuery after angular as mentioned above. This prevented the error message, but didn't really fix the problem. And jQuery '.find' didn't really work afterwards..

Solution was to fix the missing closing tag.

Android Studio does not show layout preview

Choose another theme (other than Holo, for example Theme)

Solution Image

When you create the style incorrectly or from an existing style, this problem usually occurs. So select the "Graphical Layout" select "AppTheme" (The tab with a blue star). And select any of the predefined style. In my case "Light" which should resolve the problem.

Try to 'Invalidate caches & restart'.

how to invalidate cache & restart

Restart your Android Studio by choosing this option. It may take some time.

Then, if still doesn't work try to rebuild your project.

Remove Project from Android Studio

If it's Windows, all you need to do is delete the root of that project within the file explorer. Just right click on the name of the app in Android Studio, and then "show in file explorer". Then just delete the project folder all in all.

How can I use async/await at the top level?

i like this clever syntax to do async work from an entrypoint

void async function main() {
  await doSomeWork()
  await doMoreWork()
}()

relative path in require_once doesn't work

In my case it doesn't work, even with __DIR__ or getcwd() it keeps picking the wrong path, I solved by defining a costant in every file I need with the absolute base path of the project:

if(!defined('THISBASEPATH')){ define('THISBASEPATH', '/mypath/'); }
require_once THISBASEPATH.'cache/crud.php';
/*every other require_once you need*/

I have MAMP with php 5.4.10 and my folder hierarchy is basilar:

q.php 
w.php 
e.php 
r.php 
cache/a.php 
cache/b.php 
setting/a.php 
setting/b.php

....

React Native Error: ENOSPC: System limit for number of file watchers reached

As already pointed out by @snishalaka, you can increase the number of inotify watchers.

However, I think the default number is high enough and is only reached when processes are not cleaned up properly. Hence, I simply restarted my computer as proposed on a related github issue and the error message was gone.

How to automatically select all text on focus in WPF TextBox?

Try this extension method to add the desired behaviour to any TextBox control. I havn't tested it extensively yet, but it seems to fulfil my needs.

public static class TextBoxExtensions
{
    public static void SetupSelectAllOnGotFocus(this TextBox source)
    {
        source.GotFocus += SelectAll;
        source.PreviewMouseLeftButtonDown += SelectivelyIgnoreMouseButton;
    }

    private static void SelectAll(object sender, RoutedEventArgs e)
    {
        var textBox = e.OriginalSource as TextBox;
        if (textBox != null)
            textBox.SelectAll();
    }

    private static void SelectivelyIgnoreMouseButton(object sender, MouseButtonEventArgs e)
    {
        var textBox = (sender as TextBox);
        if (textBox != null)
        {
            if (!textBox.IsKeyboardFocusWithin)
            {
                e.Handled = true;
                textBox.Focus();
            }
        }
    }
}

HTML5 - mp4 video does not play in IE9

I have a base profile .mp4 video which plays on one server, and does not on another.

The only difference is:
one gives a header "Content-Length: ..."
the other "Trasfer-Encoding: chunked".

I found out that Content-Length is not needed, it is only important, that there should be NO chunked header. This can be done by turning off compression (deflate or gzip) for .mp4 files. How this can be done is another issue and another topic: How to disable Apache gzip compression for some media files in .htaccess file?

There can be another server issue:
it has to give "Content-Type: video/mp4"
and NOT "Content-Type: text/plain"

Example of multipart/form-data

Many thanks to @Ciro Santilli answer! I found that his choice for boundary is quite "unhappy" because all of thoose hyphens: in fact, as @Fake Name commented, when you are using your boundary inside request it comes with two more hyphens on front:

Example:

POST / HTTP/1.1
HOST: host.example.com
Cookie: some_cookies...
Connection: Keep-Alive
Content-Type: multipart/form-data; boundary=12345

--12345
Content-Disposition: form-data; name="sometext"

some text that you wrote in your html form ...
--12345
Content-Disposition: form-data; name="name_of_post_request" filename="filename.xyz"

content of filename.xyz that you upload in your form with input[type=file]
--12345
Content-Disposition: form-data; name="image" filename="picture_of_sunset.jpg"

content of picture_of_sunset.jpg ...
--12345--

I found on this w3.org page that is possible to incapsulate multipart/mixed header in a multipart/form-data, simply choosing another boundary string inside multipart/mixed and using that one to incapsulate data. At the end, you must "close" all boundary used in FILO order to close the POST request (like:

POST / HTTP/1.1
...
Content-Type: multipart/form-data; boundary=12345

--12345
Content-Disposition: form-data; name="sometext"

some text sent via post...
--12345
Content-Disposition: form-data; name="files"
Content-Type: multipart/mixed; boundary=abcde

--abcde
Content-Disposition: file; file="picture.jpg"

content of jpg...
--abcde
Content-Disposition: file; file="test.py"

content of test.py file ....
--abcde--
--12345--

Take a look at the link above.

Getting a random value from a JavaScript array

Prototype Method

If you plan on getting a random value a lot, you might want to define a function for it.

First, put this in your code somewhere:

Array.prototype.sample = function(){
  return this[Math.floor(Math.random()*this.length)];
}

Now:

[1,2,3,4].sample() //=> a random element

Code released into the public domain under the terms of the CC0 1.0 license.

Extract Month and Year From Date in R

This will add a new column to your data.frame with the specified format.

df$Month_Yr <- format(as.Date(df$Date), "%Y-%m")

df
#>   ID       Date Month_Yr
#> 1  1 2004-02-06  2004-02
#> 2  2 2006-03-14  2006-03
#> 3  3 2007-07-16  2007-07

# your data sample
  df <- data.frame( ID=1:3,Date = c("2004-02-06" , "2006-03-14" , "2007-07-16") )

a simple example:

dates <- "2004-02-06"

format(as.Date(dates), "%Y-%m")
> "2004-02"

side note: the data.table approach can be quite faster in case you're working with a big dataset.

library(data.table)
setDT(df)[, Month_Yr := format(as.Date(Date), "%Y-%m") ]

Go doing a GET request and building the Querystring

As a commenter mentioned you can get Values from net/url which has an Encode method. You could do something like this (req.URL.Query() returns the existing url.Values)

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
)

func main() {
    req, err := http.NewRequest("GET", "http://api.themoviedb.org/3/tv/popular", nil)
    if err != nil {
        log.Print(err)
        os.Exit(1)
    }

    q := req.URL.Query()
    q.Add("api_key", "key_from_environment_or_flag")
    q.Add("another_thing", "foo & bar")
    req.URL.RawQuery = q.Encode()

    fmt.Println(req.URL.String())
    // Output:
    // http://api.themoviedb.org/3/tv/popular?another_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}

http://play.golang.org/p/L5XCrw9VIG

how to get login option for phpmyadmin in xampp

Step 1:

Locate phpMyAdmin installation path.

Step 2:

Open phpMyAdmin/config.inc.php in your favourite text editor. Copy config.sample.inc.php to config.inc.php if it's missing.

Step 3:

Search for $cfg['Servers'][$i]['auth_type'] = 'config';

Replace it with $cfg['Servers'][$i]['auth_type'] = 'cookie';

How to store an output of shell script to a variable in Unix?

You need to start the script with a preceding dot, this will put the exported variables in the current environment.

#!/bin/bash
...
export output="SUCCESS"

Then execute it like so

chmod +x /tmp/test.sh
. /tmp/test.sh

When you need the entire output and not just a single value, just put the output in a variable like the other answers indicate

How to set specific window (frame) size in java swing?

Well, you are using both frame.setSize() and frame.pack().

You should use one of them at one time.

Using setSize() you can give the size of frame you want but if you use pack(), it will automatically change the size of the frames according to the size of components in it. It will not consider the size you have mentioned earlier.

Try removing frame.pack() from your code or putting it before setting size and then run it.

Check if table exists in SQL Server

In SQL Server 2000 you can try:

IF EXISTS(SELECT 1 FROM sysobjects WHERE type = 'U' and name = 'MYTABLENAME')
BEGIN
   SELECT 1 AS 'res' 
END

VBA, if a string contains a certain letter

Try using the InStr function which returns the index in the string at which the character was found. If InStr returns 0, the string was not found.

If InStr(myString, "A") > 0 Then

InStr MSDN Website

For the error on the line assigning to newStr, convert oldStr.IndexOf to that InStr function also.

Left(oldStr, InStr(oldStr, "A"))

Query an XDocument for elements by name at any depth

We know the above is true. Jon is never wrong; real life wishes can go a little further.

<ota:OTA_AirAvailRQ
    xmlns:ota="http://www.opentravel.org/OTA/2003/05" EchoToken="740" Target=" Test" TimeStamp="2012-07-19T14:42:55.198Z" Version="1.1">
    <ota:OriginDestinationInformation>
        <ota:DepartureDateTime>2012-07-20T00:00:00Z</ota:DepartureDateTime>
    </ota:OriginDestinationInformation>
</ota:OTA_AirAvailRQ>

For example, usually the problem is, how can we get EchoToken in the above XML document? Or how to blur the element with the name attribute.

  1. You can find them by accessing with the namespace and the name like below

     doc.Descendants().Where(p => p.Name.LocalName == "OTA_AirAvailRQ").Attributes("EchoToken").FirstOrDefault().Value
    
  2. You can find it by the attribute content value, like this one.

How to get records randomly from the oracle database?

SELECT * FROM table SAMPLE(10) WHERE ROWNUM <= 20;

This is more efficient as it doesn't need to sort the Table.

How to know the size of the string in bytes?

You can use encoding like ASCII to get a character per byte by using the System.Text.Encoding class.

or try this

  System.Text.ASCIIEncoding.Unicode.GetByteCount(string);
  System.Text.ASCIIEncoding.ASCII.GetByteCount(string);

How to parse JSON with VBA without external libraries?

I've found this script example useful (from http://www.mrexcel.com/forum/excel-questions/898899-json-api-excel.html#post4332075 ):

Sub getData()

    Dim Movie As Object
    Dim scriptControl As Object

    Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
    scriptControl.Language = "JScript"

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json", False
        .send
        Set Movie = scriptControl.Eval("(" + .responsetext + ")")
        .abort
        With Sheets(2)
            .Cells(1, 1).Value = Movie.Title
            .Cells(1, 2).Value = Movie.Year
            .Cells(1, 3).Value = Movie.Rated
            .Cells(1, 4).Value = Movie.Released
            .Cells(1, 5).Value = Movie.Runtime
            .Cells(1, 6).Value = Movie.Director
            .Cells(1, 7).Value = Movie.Writer
            .Cells(1, 8).Value = Movie.Actors
            .Cells(1, 9).Value = Movie.Plot
            .Cells(1, 10).Value = Movie.Language
            .Cells(1, 11).Value = Movie.Country
            .Cells(1, 12).Value = Movie.imdbRating
        End With
    End With

End Sub

How to use the 'og' (Open Graph) meta tag for Facebook share

Facebook uses what's called the Open Graph Protocol to decide what things to display when you share a link. The OGP looks at your page and tries to decide what content to show. We can lend a hand and actually tell Facebook what to take from our page.

The way we do that is with og:meta tags.

The tags look something like this -

  <meta property="og:title" content="Stuffed Cookies" />
  <meta property="og:image" content="http://fbwerks.com:8000/zhen/cookie.jpg" />
  <meta property="og:description" content="The Turducken of Cookies" />
  <meta property="og:url" content="http://fbwerks.com:8000/zhen/cookie.html">

You'll need to place these or similar meta tags in the <head> of your HTML file. Don't forget to substitute the values for your own!

For more information you can read all about how Facebook uses these meta tags in their documentation. Here is one of the tutorials from there - https://developers.facebook.com/docs/opengraph/tutorial/


Facebook gives us a great little tool to help us when dealing with these meta tags - you can use the Debugger to see how Facebook sees your URL, and it'll even tell you if there are problems with it.

One thing to note here is that every time you make a change to the meta tags, you'll need to feed the URL through the Debugger again so that Facebook will clear all the data that is cached on their servers about your URL.

Cannot resolve symbol AppCompatActivity - Support v7 libraries aren't recognized?

For me, Even after upgrading to appcompat-v7:22.1.0, in which AppCompatActivty is added, the problem was not resolved for me, Android Studio was giving same problem

Cannot resolve symbol 'AppCompatActivity'

Sometimes clearing the android studio caches help.

In android studio I just cleared the caches and restarted with the following option--

File->Invalidate Caches/Restart

Mapping a JDBC ResultSet to an object

Use Statement Fetch Size , if you are retrieving more number of records. like this.

Statement statement = connection.createStatement();
statement.setFetchSize(1000); 

Apart from that i dont see an issue with the way you are doing in terms of performance

In terms of Neat. Always use seperate method delegate to map the resultset to POJO object. which can be reused later in the same class

like

private User mapResultSet(ResultSet rs){
     User user = new User();
     // Map Results
     return user;
}

If you have the same name for both columnName and object's fieldName , you could also write reflection utility to load the records back to POJO. and use MetaData to read the columnNames . but for small scale projects using reflection is not an problem. but as i said before there is nothing wrong with the way you are doing.

ImportError: No module named six

Ubuntu 18.04.5 LTS (Bionic Beaver):

apt --reinstall install python3-debian
apt --reinstall install python3-six

If /usr/bin/chardet3 fails with error "ModuleNotFoundError: No module named 'pkg_resources'":

apt --reinstall install python3-pkg-resources

Compiling a java program into an executable

You can convert .jar file to .exe on these ways:
alt text
(source: viralpatel.net)

1- JSmooth .exe wrapper:
JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself. When no VM is available, the wrapper can automatically download and install a suitable JVM, or simply display a message or redirect the user to a web site.

JSmooth provides a variety of wrappers for your java application, each of them having their own behaviour: Choose your flavour!

Download: http://jsmooth.sourceforge.net/

2- JarToExe 1.8
Jar2Exe is a tool to convert jar files into exe files. Following are the main features as describe in their website:

  • Can generate “Console”, “Windows GUI”, “Windows Service” three types of exe files.
  • Generated exe files can add program icons and version information.
  • Generated exe files can encrypt and protect java programs, no temporary files will be generated when program runs.
  • Generated exe files provide system tray icon support.
  • Generated exe files provide record system event log support.
  • Generated windows service exe files are able to install/uninstall itself, and support service pause/continue.
  • New release of x64 version, can create 64 bits executives. (May 18, 2008)
  • Both wizard mode and command line mode supported. (May 18, 2008)

Download: http://www.brothersoft.com/jartoexe-75019.html

3- Executor
Package your Java application as a jar, and Executor will turn the jar into a Windows exe file, indistinguishable from a native application. Simply double-clicking the exe file will invoke the Java Runtime Environment and launch your application.

Download: http://mpowers.net/executor/

EDIT: The above link is broken, but here is the page (with working download) from the Internet Archive. http://web.archive.org/web/20090316092154/http://mpowers.net/executor/

4- Advanced Installer
Advanced Installer lets you create Windows MSI installs in minutes. This also has Windows Vista support and also helps to create MSI packages in other languages.
Download: http://www.advancedinstaller.com/ Let me know other tools that you have used to convert JAR to EXE.

Get column value length, not column max length of value

LENGTH() does return the string length (just verified). I suppose that your data is padded with blanks - try

SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;

instead.

As OraNob mentioned, another cause could be that CHAR is used in which case LENGTH() would also return the column width, not the string length. However, the TRIM() approach also works in this case.

Calculating a 2D Vector's Cross Product

Another useful property of the cross product is that its magnitude is related to the sine of the angle between the two vectors:

| a x b | = |a| . |b| . sine(theta)

or

sine(theta) = | a x b | / (|a| . |b|)

So, in implementation 1 above, if a and b are known in advance to be unit vectors then the result of that function is exactly that sine() value.

How to add a primary key to a MySQL table?

Not sure if this matters to anyone else, but I prefer the id for the table to be the first column in the database. The syntax for that is:

ALTER TABLE your_db.your_table ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT FIRST;

Which is just a slight improvement over the first answer. If you wanted it to be in a different position, then

ALTER TABLE unique_address ADD COLUMN `id` int(10) UNSIGNED PRIMARY KEY AUTO_INCREMENT AFTER some_other_column;

HTH, -ft

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

How to load a controller from another controller in codeigniter?

I had a similar problem. I wanted to have two controllers:

homepage.php - public facing homepage

home.php - home screen once a user was logged in

and I wanted them both to read from 'mydomain.com'

I was able to accomplish this by setting 'hompepage' as the default controller in my routes config and adding a remap function to homepage.php

function _remap()
{
  if(user_is_logged_in())
  {
    require_once(APPPATH.'controllers/home.php'); 
    $oHome =  new Home();
    $oHome->index();
  }
  else
  {
    $this->index();
  }
}

Where to place JavaScript in an HTML file?

The best place for it is just before you need it and no sooner.

Also, depending on your users' physical location, using a service like Amazon's S3 service may help users download it from a server physically closer to them than your server.

Is your js script a commonly used lib like jQuery or prototype? If so, there are a number of companies, like Google and Yahoo, that have tools to provide these files for you on a distributed network.

Method call if not null in C#

This article by Ian Griffiths gives two different solutions to the problem that he concludes are neat tricks that you should not use.

Accessing the index in 'for' loops?

According to this discussion: http://bytes.com/topic/python/answers/464012-objects-list-index

Loop counter iteration

The current idiom for looping over the indices makes use of the built-in range function:

for i in range(len(sequence)):
    # work with index i

Looping over both elements and indices can be achieved either by the old idiom or by using the new zip built-in function:

for i in range(len(sequence)):
    e = sequence[i]
    # work with index i and element e

or

for i, e in zip(range(len(sequence)), sequence):
    # work with index i and element e

via http://www.python.org/dev/peps/pep-0212/

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

I was facing the same issue. I was missing DriverManager.registerDriver() call, before getting the connection using the connection URL and user credentials.

It got fixed on Linux as below:

DriverManager.registerDriver(new org.apache.derby.jdbc.ClientDriver());
connection = DriverManager.getConnection("jdbc:derby://localhost:1527//tmp/Test/DB_Name", user, pass);

For Windows:

DriverManager.registerDriver(new org.apache.derby.jdbc.ClientDriver());
connection = DriverManager.getConnection("jdbc:derby://localhost:1527/C:/Users/Test/DB_Name", user, pass);

ls command: how can I get a recursive full-path listing, one line per file?

The realpath command prints the resolved path:

realpath *

To include dot files, pipe the output of ls -a to realpath:

ls -a | xargs realpath

To list subdirectories recursively:

ls -aR | xargs realpath

In case you have spaces in file names, man xargs recommends using the -o option to prevent file names from being processed incorrectly, this works best with the output of find -print0 and it starts to look a lot more complex than other answers:

find -print0 |xargs -0 realpath

See also Unix and Linux stackexchange question on how to list all files in a directory with absolute path.

SQL Count for each date

CREATE PROCEDURE [dbo].[sp_Myforeach_Date]
    -- Add the parameters for the stored procedure here
    @SatrtDate as DateTime,
    @EndDate as dateTime,
    @DatePart as varchar(2),
    @OutPutFormat as int 
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    Declare @DateList Table
    (Date varchar(50))

    WHILE @SatrtDate<= @EndDate
    BEGIN
    INSERT @DateList (Date) values(Convert(varchar,@SatrtDate,@OutPutFormat))
    IF Upper(@DatePart)='DD'
    SET @SatrtDate= DateAdd(dd,1,@SatrtDate)
    IF Upper(@DatePart)='MM'
    SET @SatrtDate= DateAdd(mm,1,@SatrtDate)
    IF Upper(@DatePart)='YY'
    SET @SatrtDate= DateAdd(yy,1,@SatrtDate)
    END 
    SELECT * FROM @DateList
END

Just put this Code and call the SP in This way

exec sp_Myforeach_Date @SatrtDate='03 Jan 2010',@EndDate='03 Mar 2010',@DatePart='dd',@OutPutFormat=106

Thanks Suvabrata Roy ICRA Online Ltd. Kolkata

SQL Server: Maximum character length of object names

128 characters. This is the max length of the sysname datatype (nvarchar(128)).

Difference between & and && in Java?

&& == logical AND

& = bitwise AND

Setting the default page for ASP.NET (Visual Studio) server configuration

One way to achieve this is to add a DefaultDocument settings in the Web.config.

  <system.webServer>
   <defaultDocument>
    <files>
      <clear />
      <add value="DefaultPage.aspx" />
    </files>
   </defaultDocument>
  </system.webServer>

How to change text color and console color in code::blocks?

I Know, I am very late but, May be my answer can help someone. Basically it's very Simple. Here is my Code.

#include<iostream>
#include<windows.h>
using namespace std;
int main()
{
    HANDLE colors=GetStdHandle(STD_OUTPUT_HANDLE);

    string text;
    int k;
    cout<<" Enter your Text : ";
    getline(cin,text);
    for(int i=0;i<text.length();i++)
    {
        k>9 ? k=0 : k++;

        if(k==0)
        {
            SetConsoleTextAttribute(colors,1);
        }else
        {
            SetConsoleTextAttribute(colors,k);
        }
        cout<<text.at(i);
    }
}

OUTPUT

This Image will show you how it works

If you want the full tutorial please see my video here: How to change Text color in C++

Import Google Play Services library in Android Studio

//gradle.properties

systemProp.http.proxyHost=www.somehost.org

systemProp.http.proxyPort=8080

systemProp.http.proxyUser=userid

systemProp.http.proxyPassword=password

systemProp.http.nonProxyHosts=*.nonproxyrepos.com|localhost

Jenkins/Hudson - accessing the current build number?

I've just come across this question too and found out that if anytime the build number gets corrupt because of any error-triggered hard shutdown of the jenkins instance you can set back the build number manually by just editing the file nextBuildNumber (pathToJenkins\jobs\jobxyz\nextBuildNumber) and then make a reload by using the option
Reload Configuration from Disk from the Manage Jenkins View.

Connect Android Studio with SVN

Go to File->Settings->Version Control->Subversion enter the path for your SVN executable in the General tab under Subversion configuration directory. Also, you can download a latest SVN client such as VisualSVN and point the path to the executable as mentioned above. That will most likely solve your problem.

What is an instance variable in Java?

An instance variable is a variable that is a member of an instance of a class (i.e., associated with something created with a new), whereas a class variable is a member of the class itself.

Every instance of a class will have its own copy of an instance variable, whereas there is only one of each static (or class) variable, associated with the class itself.

What’s the difference between a class variable and an instance variable?

This test class illustrates the difference:

public class Test {
   
    public static String classVariable = "I am associated with the class";
    public String instanceVariable = "I am associated with the instance";
    
    public void setText(String string){
        this.instanceVariable = string;
    }
    
    public static void setClassText(String string){
        classVariable = string;
    }
    
    public static void main(String[] args) {
        Test test1 = new Test();
        Test test2 = new Test();
        
        // Change test1's instance variable
        test1.setText("Changed");
        System.out.println(test1.instanceVariable); // Prints "Changed"
        // test2 is unaffected
        System.out.println(test2.instanceVariable); // Prints "I am associated with the instance"
        
        // Change class variable (associated with the class itself)
        Test.setClassText("Changed class text");
        System.out.println(Test.classVariable); // Prints "Changed class text"
        
        // Can access static fields through an instance, but there still is only one
        // (not best practice to access static variables through instance)
        System.out.println(test1.classVariable); // Prints "Changed class text"
        System.out.println(test2.classVariable); // Prints "Changed class text"
    }
}

SQL "between" not inclusive

It is inclusive. You are comparing datetimes to dates. The second date is interpreted as midnight when the day starts.

One way to fix this is:

SELECT *
FROM Cases
WHERE cast(created_at as date) BETWEEN '2013-05-01' AND '2013-05-01'

Another way to fix it is with explicit binary comparisons

SELECT *
FROM Cases
WHERE created_at >= '2013-05-01' AND created_at < '2013-05-02'

Aaron Bertrand has a long blog entry on dates (here), where he discusses this and other date issues.

How do I customize Facebook's sharer.php

Sharer.php no longer allows you to customize. The page you share will be scraped for OG Tags and that data will be shared.

To properly customize, use FB.UI which comes with the JS-SDK.

How to avoid Sql Query Timeout

Although there is clearly some kind of network instability or something interfering with your connection (15 minutes is possible that you could be crossing a NAT boundary or something in your network is dropping the session), I would think you want such a simple?) query to return well within any anticipated timeoue (like 1s).

I would talk to your DBA and get an index created on the underlying tables on MemberType, Status. If there isn't a single underlying table or these are more complex and created by the view or UDF, and you are running SQL Server 2005 or above, have him consider indexing the view (basically materializing the view in an indexed fashion).

Different ways of adding to Dictionary

Given the, most than probable similarities in performance, use whatever feel more correct and readable to the piece of code you're using.

I feel an operation that describes an addition, being the presence of the key already a really rare exception is best represented with the add. Semantically it makes more sense.

The dict[key] = value represents better a substitution. If I see that code I half expect the key to already be in the dictionary anyway.

How can I get a List from some class properties with Java 8 Stream?

You can use map :

List<String> names = 
    personList.stream()
              .map(Person::getName)
              .collect(Collectors.toList());

EDIT :

In order to combine the Lists of friend names, you need to use flatMap :

List<String> friendNames = 
    personList.stream()
              .flatMap(e->e.getFriends().stream())
              .collect(Collectors.toList());

How to put a link on a button with bootstrap?

You can just simply add the following code;

<a class="btn btn-primary" href="http://localhost:8080/Home" role="button">Home Page</a>

MySQL stored procedure return value

You have done the stored procedure correctly but I think you have not referenced the valido variable properly. I was looking at some examples and they have put an @ symbol before the parameter like this @Valido

This statement SELECT valido; should be like this SELECT @valido;

Look at this link mysql stored-procedure: out parameter. Notice the solution with 7 upvotes. He has reference the parameter with an @ sign, hence I suggested you add an @ sign before your parameter valido

I hope that works for you. if it does vote up and mark it as the answer. If not, tell me.

How can I convert string to datetime with format specification in JavaScript?

Date.parse() is fairly intelligent but I can't guarantee that format will parse correctly.

If it doesn't, you'd have to find something to bridge the two. Your example is pretty simple (being purely numbers) so a touch of REGEX (or even string.split() -- might be faster) paired with some parseInt() will allow you to quickly make a date.

Simple PowerShell LastWriteTime compare

Try the following.

$d = [datetime](Get-ItemProperty -Path $source -Name LastWriteTime).lastwritetime

This is part of the item property weirdness. When you run Get-ItemProperty it does not return the value but instead the property. You have to use one more level of indirection to get to the value.

Razor Views not seeing System.Web.Mvc.HtmlHelper

I was dealing with this issue after upgrading from Visual Studio 2013 to Visual Studio 2015 After trying most of the advice found in this and other similar SO posts, I finally found the problem. The first part of the fix was to update all of my NuGet stuff to the latest version (you might need to do this in VS13 if you are experiencing the Nuget bug) after, I had to, as you may need to, fix the versions listed in the Views Web.config. This includes:

  1. Fix MVC versions and its child libraries to the new version (expand the References then right click onSytem.Web.MVC then Properties to get your version)
  2. Fix the Razor version.

Mine looked like this:

<configuration>
  <configSections>
    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

  <system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Optimization"/>
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
  </system.web.webPages.razor>

  <appSettings>
    <add key="webpages:Enabled" value="false" />
  </appSettings>

  <system.web>
    <httpHandlers>
      <add path="*" verb="*" type="System.Web.HttpNotFoundHandler"/>
    </httpHandlers>
    <pages
      validateRequest="false"
      pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
      pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
      userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <controls>
        <add assembly="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
      </controls>
    </pages>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />

    <handlers>
      <remove name="BlockViewHandler"/>
      <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
    </handlers>
  </system.webServer>
</configuration>

Fill Combobox from database

private void StudentForm_Load(object sender, EventArgs e)

{
         string q = @"SELECT [BatchID] FROM [Batch]"; //BatchID column name of Batch table
         SqlDataReader reader = DB.Query(q);

         while (reader.Read())
         {
             cbsb.Items.Add(reader["BatchID"].ToString()); //cbsb is the combobox name
         }
  }

When to use StringBuilder in Java

The Microsoft certification material addresses this same question. In the .NET world, the overhead for the StringBuilder object makes a simple concatenation of 2 String objects more efficient. I would assume a similar answer for Java strings.

Eclipse 3.5 Unable to install plugins

I had a similar problem setting up eclipse in the office. I had set up the for HTTP, HTTPS and SOCKS in:

Window>pref>general>network connections

Clearing the proxy settings for SOCKS fixed the problem for me.

Best method for reading newline delimited files and discarding the newlines?

for line in file('/tmp/foo'):
    print line.strip('\n')

find all unchecked checkbox in jquery

$(".clscss-row").each(function () {
if ($(this).find(".po-checkbox").not(":checked")) {
               // enter your code here
            } });

Generating a UUID in Postgres for Insert statement?

ALTER TABLE table_name ALTER COLUMN id SET DEFAULT uuid_in((md5((random())::text))::cstring);

After reading @ZuzEL's answer, i used the above code as the default value of the column id and it's working fine.

Object of custom type as dictionary key

An alternative in Python 2.6 or above is to use collections.namedtuple() -- it saves you writing any special methods:

from collections import namedtuple
MyThingBase = namedtuple("MyThingBase", ["name", "location"])
class MyThing(MyThingBase):
    def __new__(cls, name, location, length):
        obj = MyThingBase.__new__(cls, name, location)
        obj.length = length
        return obj

a = MyThing("a", "here", 10)
b = MyThing("a", "here", 20)
c = MyThing("c", "there", 10)
a == b
# True
hash(a) == hash(b)
# True
a == c
# False

How to force Selenium WebDriver to click on element which is not currently visible?

You can't force accessing/changing element to which the user normally doesn't have access, as Selenium is designed to imitate user interaction.

If this error happens, check if:

  • element is visible in your viewport, try to maximize the current window that webdriver is using (e.g. maximize() in node.js, maximize_window() in Python),
  • your element is not appearing twice (under the same selector), and you're selecting the wrong one,
  • if your element is hidden, then consider making it visible,
  • if you'd like to access/change value of hidden element despite of the limitation, then use Javascript for that (e.g. executeScript() in node.js, execute_script() in Python).

Creating a UIImage from a UIColor to use as a background image for UIButton

Xamarin.iOS solution

 public UIImage CreateImageFromColor()
 {
     var imageSize = new CGSize(30, 30);
     var imageSizeRectF = new CGRect(0, 0, 30, 30);
     UIGraphics.BeginImageContextWithOptions(imageSize, false, 0);
     var context = UIGraphics.GetCurrentContext();
     var red = new CGColor(255, 0, 0);
     context.SetFillColor(red);
     context.FillRect(imageSizeRectF);
     var image = UIGraphics.GetImageFromCurrentImageContext();
     UIGraphics.EndImageContext();
     return image;
 }

how to print an exception using logger?

Use: LOGGER.log(Level.INFO, "Got an exception.", e);
or LOGGER.info("Got an exception. " + e.getMessage());

selecting unique values from a column

Depends on what you need.

In this case I suggest:

SELECT DISTINCT(Date) AS Date FROM buy ORDER BY Date DESC;

because there are few fields and the execution time of DISTINCT is lower than the execution of GROUP BY.

In other cases, for example where there are many fields, I prefer:

SELECT * FROM buy GROUP BY date ORDER BY date DESC;

Simple parse JSON from URL on Android and display in listview

You could use AsyncTask, you'll have to customize to fit your needs, but something like the following


Async task has three primary methods:

  1. onPreExecute() - most commonly used for setting up and starting a progress dialog

  2. doInBackground() - Makes connections and receives responses from the server (Do NOT try to assign response values to GUI elements, this is a common mistake, that cannot be done in a background thread).

  3. onPostExecute() - Here we are out of the background thread, so we can do user interface manipulation with the response data, or simply assign the response to specific variable types.

First we will start the class, initialize a String to hold the results outside of the methods but inside the class, then run the onPreExecute() method setting up a simple progress dialog.

class MyAsyncTask extends AsyncTask<String, String, Void> {

    private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
    InputStream inputStream = null;
    String result = ""; 

    protected void onPreExecute() {
        progressDialog.setMessage("Downloading your data...");
        progressDialog.show();
        progressDialog.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface arg0) {
                MyAsyncTask.this.cancel(true);
            }
        });
    }

Then we need to set up the connection and how we want to handle the response:

    @Override
    protected Void doInBackground(String... params) {

        String url_select = "http://yoururlhere.com";

        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

        try {
            // Set up HTTP post

            // HttpClient is more then less deprecated. Need to change to URLConnection
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url_select);
            httpPost.setEntity(new UrlEncodedFormEntity(param));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            // Read content & Log
            inputStream = httpEntity.getContent();
        } catch (UnsupportedEncodingException e1) {
            Log.e("UnsupportedEncodingException", e1.toString());
            e1.printStackTrace();
        } catch (ClientProtocolException e2) {
            Log.e("ClientProtocolException", e2.toString());
            e2.printStackTrace();
        } catch (IllegalStateException e3) {
            Log.e("IllegalStateException", e3.toString());
            e3.printStackTrace();
        } catch (IOException e4) {
            Log.e("IOException", e4.toString());
            e4.printStackTrace();
        }
        // Convert response to string using String Builder
        try {
            BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
            StringBuilder sBuilder = new StringBuilder();

            String line = null;
            while ((line = bReader.readLine()) != null) {
                sBuilder.append(line + "\n");
            }

            inputStream.close();
            result = sBuilder.toString();

        } catch (Exception e) {
            Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
        }
    } // protected Void doInBackground(String... params)

Lastly, here we will parse the return, in this example it was a JSON Array and then dismiss the dialog:

    protected void onPostExecute(Void v) {
        //parse JSON data
        try {
            JSONArray jArray = new JSONArray(result);    
            for(i=0; i < jArray.length(); i++) {

                JSONObject jObject = jArray.getJSONObject(i);

                String name = jObject.getString("name");
                String tab1_text = jObject.getString("tab1_text");
                int active = jObject.getInt("active");

            } // End Loop
            this.progressDialog.dismiss();
        } catch (JSONException e) {
            Log.e("JSONException", "Error: " + e.toString());
        } // catch (JSONException e)
    } // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>

How does collections.defaultdict work?

In short:

defaultdict(int) - the argument int indicates that the values will be int type.

defaultdict(list) - the argument list indicates that the values will be list type.

How to parse XML to R data frame

Here's a partial solution using xml2. Breaking the solution up into smaller pieces generally makes it easier to ensure everything is lined up:

library(xml2)
data <- read_xml("http://forecast.weather.gov/MapClick.php?lat=29.803&lon=-82.411&FcstType=digitalDWML")

# Point locations
point <- data %>% xml_find_all("//point")
point %>% xml_attr("latitude") %>% as.numeric()
point %>% xml_attr("longitude") %>% as.numeric()

# Start time
data %>% 
  xml_find_all("//start-valid-time") %>% 
  xml_text()

# Temperature
data %>% 
  xml_find_all("//temperature[@type='hourly']/value") %>% 
  xml_text() %>% 
  as.integer()

Gridview get Checkbox.Checked value

For run all lines of GridView don't use for loop, use foreach loop like:

foreach (GridViewRow row in yourGridName.Rows) //Running all lines of grid
{
    if (row.RowType == DataControlRowType.DataRow)
    {
         CheckBox chkRow = (row.Cells[0].FindControl("chkRow") as CheckBox);

         if (chkRow.Checked)
         {
              //if checked do something
         }
    }
}

Execute Shell Script after post build in Jenkins

You should be able to do that with the Batch Task plugin.

  1. Create a batch task in the project.
  2. Add a "Invoke batch tasks" post-build option selecting the same project.

An alternative can also be Post build task plugin.

Histogram using gnuplot?

With respect to binning functions, I didn't expect the result of the functions offered so far. Namely, if my binwidth is 0.001, these functions were centering the bins on 0.0005 points, whereas I feel it's more intuitive to have the bins centered on 0.001 boundaries.

In other words, I'd like to have

Bin 0.001 contain data from 0.0005 to 0.0014
Bin 0.002 contain data from 0.0015 to 0.0024
...

The binning function I came up with is

my_bin(x,width)     = width*(floor(x/width+0.5))

Here's a script to compare some of the offered bin functions to this one:

rint(x) = (x-int(x)>0.9999)?int(x)+1:int(x)
bin(x,width)        = width*rint(x/width) + width/2.0
binc(x,width)       = width*(int(x/width)+0.5)
mitar_bin(x,width)  = width*floor(x/width) + width/2.0
my_bin(x,width)     = width*(floor(x/width+0.5))

binwidth = 0.001

data_list = "-0.1386 -0.1383 -0.1375 -0.0015 -0.0005 0.0005 0.0015 0.1375 0.1383 0.1386"

my_line = sprintf("%7s  %7s  %7s  %7s  %7s","data","bin()","binc()","mitar()","my_bin()")
print my_line
do for [i in data_list] {
    iN = i + 0
    my_line = sprintf("%+.4f  %+.4f  %+.4f  %+.4f  %+.4f",iN,bin(iN,binwidth),binc(iN,binwidth),mitar_bin(iN,binwidth),my_bin(iN,binwidth))
    print my_line
}

and here's the output

   data    bin()   binc()  mitar()  my_bin()
-0.1386  -0.1375  -0.1375  -0.1385  -0.1390
-0.1383  -0.1375  -0.1375  -0.1385  -0.1380
-0.1375  -0.1365  -0.1365  -0.1375  -0.1380
-0.0015  -0.0005  -0.0005  -0.0015  -0.0010
-0.0005  +0.0005  +0.0005  -0.0005  +0.0000
+0.0005  +0.0005  +0.0005  +0.0005  +0.0010
+0.0015  +0.0015  +0.0015  +0.0015  +0.0020
+0.1375  +0.1375  +0.1375  +0.1375  +0.1380
+0.1383  +0.1385  +0.1385  +0.1385  +0.1380
+0.1386  +0.1385  +0.1385  +0.1385  +0.1390

How to update parent's state in React?

When ever you require to communicate between child to parent at any level down, then it's better to make use of context. In parent component define the context that can be invoked by the child such as

In parent component in your case component 3

static childContextTypes = {
        parentMethod: React.PropTypes.func.isRequired
      };

       getChildContext() {
        return {
          parentMethod: (parameter_from_child) => this.parentMethod(parameter_from_child)
        };
      }

parentMethod(parameter_from_child){
// update the state with parameter_from_child
}

Now in child component (component 5 in your case) , just tell this component that it want to use context of its parent.

 static contextTypes = {
       parentMethod: React.PropTypes.func.isRequired
     };
render(){
    return(
      <TouchableHighlight
        onPress={() =>this.context.parentMethod(new_state_value)}
         underlayColor='gray' >   

            <Text> update state in parent component </Text>              

      </TouchableHighlight>
)}

you can find Demo project at repo

How to grab substring before a specified character jQuery or JavaScript

var newString = string.substr(0,string.indexOf(','));

ProgressDialog in AsyncTask

Don't know what parameter should I use?

A lot of Developers including have hard time at the beginning writing an AsyncTask because of the ambiguity of the parameters. The big reason is we try to memorize the parameters used in the AsyncTask. The key is Don't memorize. If you can visualize what your task really needs to do then writing the AsyncTask with the correct signature would be a piece of cake.

What is an AsyncTask?

AsyncTask are background task which run in the background thread. It takes an Input, performs Progress and gives Output.

ie AsyncTask<Input,Progress,Output>

Just figure out what your Input, Progress and Output are and you will be good to go.

For example

enter image description here

How does doInbackground() changes with AsyncTask parameters?

enter image description here

How doInBackground() and onPostExecute(),onProgressUpdate() are related?

enter image description here

How can You write this in a code?

 DownloadTask extends AsyncTask<String,Integer,String>{

    @Override
    public void onPreExecute(){
    }

    @Override
    public String doInbackGround(String... params)
    {
         // Download code
         int downloadPerc = // calculate that
         publish(downloadPerc);

         return "Download Success";
    }

    @Override
    public void onPostExecute(String result)
    {
         super.onPostExecute(result);
    }

    @Override
    public void onProgressUpdate(Integer... params)
    {
         // show in spinner, access UI elements
    }

}

How will you run this Task in Your Activity?

new DownLoadTask().execute("Paradise.mp3");

How to use the COLLATE in a JOIN in SQL Server?

Correct syntax looks like this. See MSDN.

SELECT *
  FROM [FAEB].[dbo].[ExportaComisiones] AS f
  JOIN [zCredifiel].[dbo].[optPerson] AS p

  ON p.vTreasuryId COLLATE Latin1_General_CI_AS = f.RFC COLLATE Latin1_General_CI_AS 

How to apply bold text style for an entire row using Apache POI?

This work for me

I set style's font before and make rowheader normally then i set in loop for the style with font bolded on each cell of rowhead. Et voilà first row is bolded.

HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("FirstSheet");
HSSFRow rowhead = sheet.createRow(0); 
HSSFCellStyle style = wb.createCellStyle();
HSSFFont font = wb.createFont();
font.setFontName(HSSFFont.FONT_ARIAL);
font.setFontHeightInPoints((short)10);
font.setBold(true);
style.setFont(font);
rowhead.createCell(0).setCellValue("ID");
rowhead.createCell(1).setCellValue("First");
rowhead.createCell(2).setCellValue("Second");
rowhead.createCell(3).setCellValue("Third");
for(int j = 0; j<=3; j++)
rowhead.getCell(j).setCellStyle(style);

C programming in Visual Studio

Yes it is, none of the Visual Stdio editions have C mentioned, but it is included with the C++ compiler (you therefore need to look under C++). The main difference between using C and C++ is the naming system (i.e. using .c and not .cpp).

You do have to be careful not to create a C++ project and rename it to C though, that does not work.

Coding C from the command line:

Much like you can use gcc on Linux (or if you have MinGW installed) Visual Studio has a command to be used from command prompt (it must be the Visual Studio Developer Command Prompt though). As mentioned in the other answer you can use cl to compile your c file (make sure it is named .c)

Example:

cl myfile.c

Or to check all the accepted commands:

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>cl
Microsoft (R) C/C++ Optimizing Compiler Version 19.16.27030.1 for x86
Copyright (C) Microsoft Corporation.  All rights reserved.

usage: cl [ option... ] filename... [ /link linkoption... ]

C:\Program Files (x86)\Microsoft Visual Studio\2017\Community>

Coding C from the IDE:

Without doubt one of the best features of Visual Studio is the convenient IDE.

Although it takes more configuring, you get bonuses such as basic debugging before compiling (for example if you forget a ;)

To create a C project do the following:

Start a new project, go under C++ and select Empty Project, enter the Name of your project and the Location you want it to install to, then click Ok. Now wait for the project to be created.

enter image description here

Next under Solutions Explorer right click Source Files, select Add then New Item. You should see something like this:

enter image description here

Rename Source.cpp to include a .c extension (Source.c for example). Select the location you want to keep it in, I would recommend always keeping it within the project folder itself (in this case C:\Users\Simon\Desktop\Learn\My First C Code)

It should open up the .c file, ready to be modified. Visual Studio can now be used as normal, happy coding!

unsigned APK can not be installed

Just follow these steps to transfer the apk onto the real device(with debugger key) and which is just for testing purpose. (Note: For proper distribution to the market you may need to sign your app with your keys and follow all the steps.)

  1. Install your app onto the emulator.
  2. Once it is installed goto DDMS, select the current running app under the devices window. This will then show all the files related to it under the file explorer.
  3. Under file explorer go to data->app and select your APK (which is the package name of the app).
  4. Select it and click on 'Pull a file from the device' button (the one with the save symbol).
  5. This copies the APK to your system. From there you can copy the file to your real device, install and test it.

Good luck !

pip or pip3 to install packages for Python 3?

If you had python 2.x and then installed python3, your pip will be pointing to pip3. you can verify that by typing pip --version which would be the same as pip3 --version.

On your system you have now pip, pip2 and pip3.

If you want you can change pip to point to pip2 instead of pip3.

Using If/Else on a data frame

Use ifelse:

frame$twohouses <- ifelse(frame$data>=2, 2, 1)
frame
   data twohouses
1     0         1
2     1         1
3     2         2
4     3         2
5     4         2
...
16    0         1
17    2         2
18    1         1
19    2         2
20    0         1
21    4         2

The difference between if and ifelse:

  • if is a control flow statement, taking a single logical value as an argument
  • ifelse is a vectorised function, taking vectors as all its arguments.

The help page for if, accessible via ?"if" will also point you to ?ifelse

Compare two files and write it to "match" and "nomatch" files

In Eztrieve it's really easy, below is an example how you could code it:

//STEP01   EXEC PGM=EZTPA00                                        
//FILEA    DD DSN=FILEA,DISP=SHR   
//FILEB    DD DSN=FILEB,DISP=SHR
//FILEC    DD DSN=FILEC.DIF,    
//            DISP=(NEW,CATLG,DELETE),                             
//            SPACE=(CYL,(100,50),RLSE),                           
//            UNIT=PRMDA,                                          
//            DCB=(RECFM=FB,LRECL=5200,BLKSIZE=0)                  
//SYSOUT   DD SYSOUT=*                                             
//SRTMSG   DD SYSOUT=*                                             
//SYSPRINT DD SYSOUT=*                                             
//SYSIN    DD *                                                    
 FILE FILEA                                                        
   FA-KEY       1   7 A                                         
   FA-REC1      8  10 A
   FA-REC2     18   5 A

 FILE FILEB                                                        
   FB-KEY       1   7 A                                         
   FB-REC1      8  10 A                                         
   FB-REC2     18   5 A                                         

 FILE FILEC                                                        

 FILE FILED                                                        
   FD-KEY       1   7 A                                         
   FD-REC1      8  10 A                                         
   FD-REC2     18   5 A                                         


 JOB INPUT (FILEA KEY FA-KEY FILEB KEY FB-KEY)                     
   IF MATCHED            
      FD-KEY   =  FB-KEY                                      
      FD-REC1  =  FA-REC1
      FD-REC2  =  FB-REC2
      PUT FILED
   ELSE
      IF FILEA
         PUT FILEC FROM FILEA                                         
      ELSE
         PUT FILEC FROM FILEB
      END-IF                                         
   END-IF                                                          
/*                       

Using ls to list directories and their total sizes

These are all great suggestions, but the one I use is:

du -ksh * | sort -n -r

-ksh makes sure the files and folders are listed in a human-readable format and in megabytes, kilobytes, etc. Then you sort them numerically and reverse the sort so it puts the bigger ones first.

The only downside to this command is that the computer does not know that Gigabyte is bigger than Megabyte so it will only sort by numbers and you will often find listings like this:

120K
12M
4G

Just be careful to look at the unit.

This command also works on the Mac (whereas sort -h does not for example).

What is an HttpHandler in ASP.NET

An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page via the page handler.

The ASP.NET page handler is only one type of handler. ASP.NET comes with several other built-in handlers such as the Web service handler for .asmx files.

You can create custom HTTP handlers when you want special handling that you can identify using file name extensions in your application. For example, the following scenarios would be good uses of custom HTTP handlers:

RSS feeds To create an RSS feed for a site, you can create a handler that emits RSS-formatted XML. You can then bind the .rss extension (for example) in your application to the custom handler. When users send a request to your site that ends in .rss, ASP.NET will call your handler to process the request.

Image server If you want your Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them back to the user as the handler's response.

HTTP handlers have access to the application context, including the requesting user's identity (if known), application state, and session information. When an HTTP handler is requested, ASP.NET calls the ProcessRequest method on the appropriate handler. The handler's ProcessRequest method creates a response, which is sent back to the requesting browser. As with any page request, the response goes through any HTTP modules that have subscribed to events that occur after the handler has run.

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

Thread.sleep can throw an InterruptedException which is a checked exception. All checked exceptions must either be caught and handled or else you must declare that your method can throw it. You need to do this whether or not the exception actually will be thrown. Not declaring a checked exception that your method can throw is a compile error.

You either need to catch it:

try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
    // handle the exception...        
    // For example consider calling Thread.currentThread().interrupt(); here.
}

Or declare that your method can throw an InterruptedException:

public static void main(String[]args) throws InterruptedException

Related

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);
}

How to get the Touch position in android?

@Override
    public boolean onTouch(View v, MotionEvent event) {
       float x = event.getX();
       float y = event.getY();
       return true;
    }

Signed to unsigned conversion in C - is it always safe?

Horrible Answers Galore

Ozgur Ozcitak

When you cast from signed to unsigned (and vice versa) the internal representation of the number does not change. What changes is how the compiler interprets the sign bit.

This is completely wrong.

Mats Fredriksson

When one unsigned and one signed variable are added (or any binary operation) both are implicitly converted to unsigned, which would in this case result in a huge result.

This is also wrong. Unsigned ints may be promoted to ints should they have equal precision due to padding bits in the unsigned type.

smh

Your addition operation causes the int to be converted to an unsigned int.

Wrong. Maybe it does and maybe it doesn't.

Conversion from unsigned int to signed int is implementation dependent. (But it probably works the way you expect on most platforms these days.)

Wrong. It is either undefined behavior if it causes overflow or the value is preserved.

Anonymous

The value of i is converted to unsigned int ...

Wrong. Depends on the precision of an int relative to an unsigned int.

Taylor Price

As was previously answered, you can cast back and forth between signed and unsigned without a problem.

Wrong. Trying to store a value outside the range of a signed integer results in undefined behavior.

Now I can finally answer the question.

Should the precision of int be equal to unsigned int, u will be promoted to a signed int and you will get the value -4444 from the expression (u+i). Now, should u and i have other values, you may get overflow and undefined behavior but with those exact numbers you will get -4444 [1]. This value will have type int. But you are trying to store that value into an unsigned int so that will then be cast to an unsigned int and the value that result will end up having would be (UINT_MAX+1) - 4444.

Should the precision of unsigned int be greater than that of an int, the signed int will be promoted to an unsigned int yielding the value (UINT_MAX+1) - 5678 which will be added to the other unsigned int 1234. Should u and i have other values, which make the expression fall outside the range {0..UINT_MAX} the value (UINT_MAX+1) will either be added or subtracted until the result DOES fall inside the range {0..UINT_MAX) and no undefined behavior will occur.

What is precision?

Integers have padding bits, sign bits, and value bits. Unsigned integers do not have a sign bit obviously. Unsigned char is further guaranteed to not have padding bits. The number of values bits an integer has is how much precision it has.

[Gotchas]

The macro sizeof macro alone cannot be used to determine precision of an integer if padding bits are present. And the size of a byte does not have to be an octet (eight bits) as defined by C99.

[1] The overflow may occur at one of two points. Either before the addition (during promotion) - when you have an unsigned int which is too large to fit inside an int. The overflow may also occur after the addition even if the unsigned int was within the range of an int, after the addition the result may still overflow.

PHP Call to undefined function

Your function is probably in a different namespace than the one you're calling it from.

http://php.net/manual/en/language.namespaces.basics.php

if statement checks for null but still throws a NullPointerException

The | and & check both the sides everytime.

if (str == null | str.length() == 0)

here we have high possibility to get NullPointerException

Logical || and && check the right hand side only if necessary.

but with logical operator

no chance to get NPE because it will not check RHS

How do I create a file at a specific path?

The file is created wherever the root of the python interpreter was started.

Eg, you start python in /home/user/program, then the file "test.py" would be located at /home/user/program/test.py

How do I turn off Unicode in a VC++ project?

project properities -> configuration properities -> general -> charater set

How to "add existing frameworks" in Xcode 4?

I would like to point out that if you can't find "Link Binaries With Libraries" in your build phases tab click the "Add build phase" button in the lower right corner.

Fatal error: Call to undefined function sqlsrv_connect()

When you install third-party extensions you need to make sure that all the compilation parameters match:

  • PHP version
  • Architecture (32/64 bits)
  • Compiler (VC9, VC10, VC11...)
  • Thread safety

Common glitches includes:

  • Editing the wrong php.ini file (that's typical with bundles); the right path is shown in phpinfo().
  • Forgetting to restart Apache.
  • Not being able to see the startup errors; those should show up in Apache logs, but you can also use the command line to diagnose it, e.g.:

    php -d display_startup_errors=1 -d error_reporting=-1 -d display_errors -c "C:\Path\To\php.ini" -m
    

If everything's right you should see sqlsrv in the command output and/or phpinfo() (depending on what SAPI you're configuring):

[PHP Modules]
bcmath
calendar
Core
[...]
SPL
sqlsrv
standard
[...]

phpinfo()

Refreshing all the pivot tables in my excel workbook with a macro

There is a refresh all option in the Pivot Table tool bar. That is enough. Dont have to do anything else.

Press ctrl+alt+F5

What I can do to resolve "1 commit behind master"?

If your branch is behind by master then do:

git checkout master (you are switching your branch to master)
git pull 
git checkout yourBranch (switch back to your branch)
git merge master

After merging it, check if there is a conflict or not.
If there is NO CONFLICT then:

git push

If there is a conflict then fix your file(s), then:

git add yourFile(s)
git commit -m 'updating my branch'
git push

Alter table to modify default value of column

For Sql Azure the following query works :

ALTER TABLE [TableName] ADD  DEFAULT 'DefaultValue' FOR ColumnName
GO

What is the Python equivalent for a case/switch statement?

The direct replacement is if/elif/else.

However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".

How to semantically add heading to a list

In this case I would use a definition list as so:

<dl>
  <dt>Fruits I like:</dt>
  <dd>Apples</dd>
  <dd>Bananas</dd>
  <dd>Oranges</dd>
</dl>

How to Validate Google reCaptcha on Form Submit

Verify Google reCapcha is valid or not after form submit

if ($post['g-recaptcha-response']) {
      $captcha = $post['g-recaptcha-response'];
      $secretKey = 'type here private key';
      $response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=" . $secretKey . "&response=" . $captcha);
        $responseKeys = json_decode($response, true);
        if (intval($responseKeys["success"]) !== 1) {
            return "failed";
        } else {
            return "success";
        }
    }
    else {
        return "failed";
    }

VBA using ubound on a multidimensional array

[This is a late answer addressing the title of the question (since that is what people would encounter when searching) rather than the specifics of OP's question which has already been answered adequately]

Ubound is a bit fragile in that it provides no way to know how many dimensions an array has. You can use error trapping to determine the full layout of an array. The following returns a collection of arrays, one for each dimension. The count property can be used to determine the number of dimensions and their lower and upper bounds can be extracted as needed:

Function Bounds(A As Variant) As Collection
    Dim C As New Collection
    Dim v As Variant, i As Long

    On Error GoTo exit_function
    i = 1
    Do While True
        v = Array(LBound(A, i), UBound(A, i))
        C.Add v
        i = i + 1
    Loop
exit_function:
    Set Bounds = C
End Function

Used like this:

Sub test()
    Dim i As Long
    Dim A(1 To 10, 1 To 5, 4 To 10) As Integer
    Dim B(1 To 5) As Variant
    Dim C As Variant
    Dim sizes As Collection

    Set sizes = Bounds(A)
    Debug.Print "A has " & sizes.Count & " dimensions:"
    For i = 1 To sizes.Count
        Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
    Next i

    Set sizes = Bounds(B)
    Debug.Print vbCrLf & "B has " & sizes.Count & " dimensions:"
    For i = 1 To sizes.Count
        Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
    Next i

    Set sizes = Bounds(C)
    Debug.Print vbCrLf & "C has " & sizes.Count & " dimensions:"
    For i = 1 To sizes.Count
        Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
    Next i
End Sub

Output:

A has 3 dimensions:
1 to 10
1 to 5
4 to 10

B has 1 dimensions:
1 to 5

C has 0 dimensions:

How to use MD5 in javascript to transmit a password

You might want to check out this page: http://pajhome.org.uk/crypt/md5/

However, if protecting the password is important, you should really be using something like SHA256 (MD5 is not cryptographically secure iirc). Even more, you might want to consider using TLS and getting a cert so you can use https.

How to allocate aligned memory only using the standard library?

Original answer

{
    void *mem = malloc(1024+16);
    void *ptr = ((char *)mem+16) & ~ 0x0F;
    memset_16aligned(ptr, 0, 1024);
    free(mem);
}

Fixed answer

{
    void *mem = malloc(1024+15);
    void *ptr = ((uintptr_t)mem+15) & ~ (uintptr_t)0x0F;
    memset_16aligned(ptr, 0, 1024);
    free(mem);
}

Explanation as requested

The first step is to allocate enough spare space, just in case. Since the memory must be 16-byte aligned (meaning that the leading byte address needs to be a multiple of 16), adding 16 extra bytes guarantees that we have enough space. Somewhere in the first 16 bytes, there is a 16-byte aligned pointer. (Note that malloc() is supposed to return a pointer that is sufficiently well aligned for any purpose. However, the meaning of 'any' is primarily for things like basic types — long, double, long double, long long, and pointers to objects and pointers to functions. When you are doing more specialized things, like playing with graphics systems, they can need more stringent alignment than the rest of the system — hence questions and answers like this.)

The next step is to convert the void pointer to a char pointer; GCC notwithstanding, you are not supposed to do pointer arithmetic on void pointers (and GCC has warning options to tell you when you abuse it). Then add 16 to the start pointer. Suppose malloc() returned you an impossibly badly aligned pointer: 0x800001. Adding the 16 gives 0x800011. Now I want to round down to the 16-byte boundary — so I want to reset the last 4 bits to 0. 0x0F has the last 4 bits set to one; therefore, ~0x0F has all bits set to one except the last four. Anding that with 0x800011 gives 0x800010. You can iterate over the other offsets and see that the same arithmetic works.

The last step, free(), is easy: you always, and only, return to free() a value that one of malloc(), calloc() or realloc() returned to you — anything else is a disaster. You correctly provided mem to hold that value — thank you. The free releases it.

Finally, if you know about the internals of your system's malloc package, you could guess that it might well return 16-byte aligned data (or it might be 8-byte aligned). If it was 16-byte aligned, then you'd not need to dink with the values. However, this is dodgy and non-portable — other malloc packages have different minimum alignments, and therefore assuming one thing when it does something different would lead to core dumps. Within broad limits, this solution is portable.

Someone else mentioned posix_memalign() as another way to get the aligned memory; that isn't available everywhere, but could often be implemented using this as a basis. Note that it was convenient that the alignment was a power of 2; other alignments are messier.

One more comment — this code does not check that the allocation succeeded.

Amendment

Windows Programmer pointed out that you can't do bit mask operations on pointers, and, indeed, GCC (3.4.6 and 4.3.1 tested) does complain like that. So, an amended version of the basic code — converted into a main program, follows. I've also taken the liberty of adding just 15 instead of 16, as has been pointed out. I'm using uintptr_t since C99 has been around long enough to be accessible on most platforms. If it wasn't for the use of PRIXPTR in the printf() statements, it would be sufficient to #include <stdint.h> instead of using #include <inttypes.h>. [This code includes the fix pointed out by C.R., which was reiterating a point first made by Bill K a number of years ago, which I managed to overlook until now.]

#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void memset_16aligned(void *space, char byte, size_t nbytes)
{
    assert((nbytes & 0x0F) == 0);
    assert(((uintptr_t)space & 0x0F) == 0);
    memset(space, byte, nbytes);  // Not a custom implementation of memset()
}

int main(void)
{
    void *mem = malloc(1024+15);
    void *ptr = (void *)(((uintptr_t)mem+15) & ~ (uintptr_t)0x0F);
    printf("0x%08" PRIXPTR ", 0x%08" PRIXPTR "\n", (uintptr_t)mem, (uintptr_t)ptr);
    memset_16aligned(ptr, 0, 1024);
    free(mem);
    return(0);
}

And here is a marginally more generalized version, which will work for sizes which are a power of 2:

#include <assert.h>
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

static void memset_16aligned(void *space, char byte, size_t nbytes)
{
    assert((nbytes & 0x0F) == 0);
    assert(((uintptr_t)space & 0x0F) == 0);
    memset(space, byte, nbytes);  // Not a custom implementation of memset()
}

static void test_mask(size_t align)
{
    uintptr_t mask = ~(uintptr_t)(align - 1);
    void *mem = malloc(1024+align-1);
    void *ptr = (void *)(((uintptr_t)mem+align-1) & mask);
    assert((align & (align - 1)) == 0);
    printf("0x%08" PRIXPTR ", 0x%08" PRIXPTR "\n", (uintptr_t)mem, (uintptr_t)ptr);
    memset_16aligned(ptr, 0, 1024);
    free(mem);
}

int main(void)
{
    test_mask(16);
    test_mask(32);
    test_mask(64);
    test_mask(128);
    return(0);
}

To convert test_mask() into a general purpose allocation function, the single return value from the allocator would have to encode the release address, as several people have indicated in their answers.

Problems with interviewers

Uri commented: Maybe I am having [a] reading comprehension problem this morning, but if the interview question specifically says: "How would you allocate 1024 bytes of memory" and you clearly allocate more than that. Wouldn't that be an automatic failure from the interviewer?

My response won't fit into a 300-character comment...

It depends, I suppose. I think most people (including me) took the question to mean "How would you allocate a space in which 1024 bytes of data can be stored, and where the base address is a multiple of 16 bytes". If the interviewer really meant how can you allocate 1024 bytes (only) and have it 16-byte aligned, then the options are more limited.

  • Clearly, one possibility is to allocate 1024 bytes and then give that address the 'alignment treatment'; the problem with that approach is that the actual available space is not properly determinate (the usable space is between 1008 and 1024 bytes, but there wasn't a mechanism available to specify which size), which renders it less than useful.
  • Another possibility is that you are expected to write a full memory allocator and ensure that the 1024-byte block you return is appropriately aligned. If that is the case, you probably end up doing an operation fairly similar to what the proposed solution did, but you hide it inside the allocator.

However, if the interviewer expected either of those responses, I'd expect them to recognize that this solution answers a closely related question, and then to reframe their question to point the conversation in the correct direction. (Further, if the interviewer got really stroppy, then I wouldn't want the job; if the answer to an insufficiently precise requirement is shot down in flames without correction, then the interviewer is not someone for whom it is safe to work.)

The world moves on

The title of the question has changed recently. It was Solve the memory alignment in C interview question that stumped me. The revised title (How to allocate aligned memory only using the standard library?) demands a slightly revised answer — this addendum provides it.

C11 (ISO/IEC 9899:2011) added function aligned_alloc():

7.22.3.1 The aligned_alloc function

Synopsis

#include <stdlib.h>
void *aligned_alloc(size_t alignment, size_t size);

Description
The aligned_alloc function allocates space for an object whose alignment is specified by alignment, whose size is specified by size, and whose value is indeterminate. The value of alignment shall be a valid alignment supported by the implementation and the value of size shall be an integral multiple of alignment.

Returns
The aligned_alloc function returns either a null pointer or a pointer to the allocated space.

And POSIX defines posix_memalign():

#include <stdlib.h>

int posix_memalign(void **memptr, size_t alignment, size_t size);

DESCRIPTION

The posix_memalign() function shall allocate size bytes aligned on a boundary specified by alignment, and shall return a pointer to the allocated memory in memptr. The value of alignment shall be a power of two multiple of sizeof(void *).

Upon successful completion, the value pointed to by memptr shall be a multiple of alignment.

If the size of the space requested is 0, the behavior is implementation-defined; the value returned in memptr shall be either a null pointer or a unique pointer.

The free() function shall deallocate memory that has previously been allocated by posix_memalign().

RETURN VALUE

Upon successful completion, posix_memalign() shall return zero; otherwise, an error number shall be returned to indicate the error.

Either or both of these could be used to answer the question now, but only the POSIX function was an option when the question was originally answered.

Behind the scenes, the new aligned memory function do much the same job as outlined in the question, except they have the ability to force the alignment more easily, and keep track of the start of the aligned memory internally so that the code doesn't have to deal with specially — it just frees the memory returned by the allocation function that was used.

CSS list-style-image size

Thanks to Chris for the starting point here is a improvement which addresses the resizing of the images used, the use of first-child is just to indicate you could use a variety of icons within the list to give you full control.

ul li:first-child:before {
    content: '';
    display: inline-block;
    height: 25px;
    width: 35px;
    background-image: url('../images/Money.png');
    background-size: contain;
    background-repeat: no-repeat;
    margin-left: -35px;
}

This seems to work well in all modern browsers, you will need to ensure that the width and the negative margin left have the same value, hope it helps

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

What is the difference between private and protected members of C++ classes?

Since no public member function is needed to fetch and update protected members in the derived class, this increases the efficiency of code and reduces the amount of code we need to write. However, programmer of the derived class is supposed to be aware of what he is doing.

Order a MySQL table by two columns

The following will order your data depending on both column in descending order.

ORDER BY article_rating DESC, article_time DESC

top -c command in linux to filter processes listed based on processname

I ended up using a shell script with the following code:

#!/bin/bash

while [ 1 == 1 ]
do
    clear
    ps auxf |grep -ve "grep" |grep -E "MSG[^\ ]*" --color=auto
    sleep 5
done

Find the most popular element in int[] array

import java.util.Scanner;


public class Mostrepeatednumber
{
    public static void main(String args[])
    {
        int most = 0;
        int temp=0;
        int count=0,tempcount;
        Scanner in=new Scanner(System.in);
        System.out.println("Enter any number");
        int n=in.nextInt();
        int arr[]=new int[n];
        System.out.print("Enter array value:");
        for(int i=0;i<=n-1;i++)
        {
            int n1=in.nextInt();
            arr[i]=n1;
        }
        //!!!!!!!! user input concept closed
        //logic can be started
        for(int j=0;j<=n-1;j++)
        {
        temp=arr[j];
        tempcount=0;
            for(int k=1;k<=n-1;k++)
                {
                if(temp==arr[k])
                    {
                        tempcount++;
                    }   
                        if(count<tempcount)
                            {
                                most=arr[k];
                                    count=tempcount;
                            }
                }

        }
        System.out.println(most);
    }

}

I want to show all tables that have specified column name

SELECT      T.TABLE_NAME, C.COLUMN_NAME
FROM        INFORMATION_SCHEMA.COLUMNS C
            INNER JOIN INFORMATION_SCHEMA.TABLES T ON T.TABLE_NAME = C.TABLE_NAME
WHERE       TABLE_TYPE = 'BASE TABLE'
            AND COLUMN_NAME = 'ColName'

This returns tables only and ignores views for anyone who is interested!

Where is the Postgresql config file: 'postgresql.conf' on Windows?

On my machine:

C:\Program Files\PostgreSQL\8.4\data\postgresql.conf

Xcode 10 Error: Multiple commands produce

Before I begin note that my project utilizes Carthage as a dependency manager.

None of the existing answers here resolved my issue. What did resolve the issue for me was the following.

First, I noticed that the build error pointed out one framework in particular. Next I filtered App Target > Build Phases for that framework. I noticed that that framework was present in both "Link Binary With Libraries" and "Embed Frameworks". Noting that none of the frameworks listed under "Embed Frameworks" were ones managed by Carthage I removed the framework in question from "Embed Frameworks". I then re-built my project and everything works fine including the functionality enabled by the framework in question.

Is it necessary to assign a string to a variable before comparing it to another?

Do I really have to create an NSString for "Wrong"?

No, why not just do:

if([statusString isEqualToString:@"Wrong"]){
    //doSomething;
}

Using @"" simply creates a string literal, which is a valid NSString.

Also, can I compare the value of a UILabel.text to a string without assigning the label value to a string?

Yes, you can do something like:

UILabel *label = ...;
if([someString isEqualToString:label.text]) {
    // Do stuff here 
}

How to navigate back to the last cursor position in Visual Studio Code?

The Keyboard Shortcut Commands are Go Forward and Go Back.


On Windows:

Alt+? .. navigate back

Alt+? .. navigate forward

On Mac:

Ctrl+- .. navigate back

Ctrl+Shift+- .. navigate forward

On Ubuntu Linux:

Ctrl+Alt+- .. navigate back

Ctrl+Shift+- .. navigate forward

How to use default Android drawables

Better to use android.R.drawable because it is public and documented.

What is the difference between `sorted(list)` vs `list.sort()`?

The main difference is that sorted(some_list) returns a new list:

a = [3, 2, 1]
print sorted(a) # new list
print a         # is not modified

and some_list.sort(), sorts the list in place:

a = [3, 2, 1]
print a.sort() # in place
print a         # it's modified

Note that since a.sort() doesn't return anything, print a.sort() will print None.


Can a list original positions be retrieved after list.sort()?

No, because it modifies the original list.

Maven fails to find local artifact

In my case I needed project Y to be a WAR to be deployed through Tomcat, as well as it needed to be a JAR to be able to add it as a dependency in project X.

So in project Y's pom.xml, I added this plugin to create a JAR along with the WAR:

            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.2</version>
                <configuration>
                    <attachClasses>true</attachClasses>
                    <classesClassifier>classes</classesClassifier>
                </configuration>
            </plugin>

And while adding the dependency of project Y in project X's pom.xml, I had to add a classifier:

        <dependency>
            <groupId>groupId.of.project.Y</groupId>
            <artifactId>project.Y</artifactId>
            <version>1.0-SNAPSHOT</version>
            <classifier>classes</classifier>
        </dependency>

Note: when you build project Y, you will see 2 packagings in the target folder: project-Y.war and project-Y-classes.jar, so that's why while importing you are specifying the classes classifier to import the JAR and not the WAR.

How do I include image files in Django templates?

Try this,

settings.py

# typically, os.path.join(os.path.dirname(__file__), 'media')
MEDIA_ROOT = '<your_path>/media'
MEDIA_URL = '/media/'

urls.py

urlpatterns = patterns('',
               (r'^media/(?P<path>.*)$', 'django.views.static.serve',
                 {'document_root': settings.MEDIA_ROOT}),
              )

.html

<img src="{{ MEDIA_URL }}<sub-dir-under-media-if-any>/<image-name.ext>" />

Caveat

Beware! using Context() will yield you an empty value for {{MEDIA_URL}}. You must use RequestContext(), instead.

I hope, this will help.

What is the best method to merge two PHP objects?

This snippet of code will recursively convert that data to a single type (array or object) without the nested foreach loops. Hope it helps someone!

Once an Object is in array format you can use array_merge and convert back to Object if you need to.

abstract class Util {
    public static function object_to_array($d) {
        if (is_object($d))
            $d = get_object_vars($d);

        return is_array($d) ? array_map(__METHOD__, $d) : $d;
    }

    public static function array_to_object($d) {
        return is_array($d) ? (object) array_map(__METHOD__, $d) : $d;
    }
}

Procedural way

function object_to_array($d) {
    if (is_object($d))
        $d = get_object_vars($d);

    return is_array($d) ? array_map(__FUNCTION__, $d) : $d;
}

function array_to_object($d) {
    return is_array($d) ? (object) array_map(__FUNCTION__, $d) : $d;
}

All credit goes to: Jason Oakley

how to set select element as readonly ('disabled' doesnt pass select value on server)

To be able to pass the select, I just set it back to :

  $('#selectID').prop('disabled',false);

or

  $('#selectID').attr('disabled',false);

when passing the request.

What is the difference between i++ and ++i?

Just for the record, in C++, if you can use either (i.e.) you don't care about the ordering of operations (you just want to increment or decrement and use it later) the prefix operator is more efficient since it doesn't have to create a temporary copy of the object. Unfortunately, most people use posfix (var++) instead of prefix (++var), just because that is what we learned initially. (I was asked about this in an interview). Not sure if this is true in C#, but I assume it would be.

How do I print an IFrame from javascript in Safari/Chrome

The 'framePartsList.contentWindow.print();' was not working in IE 11 ver11.0.43

Therefore I have used framePartsList.contentWindow.document.execCommand('print', false, null);

Write HTML to string

It really depends what you are going for, and specifically, what kind of performance you really need to offer.

I've seen admirable solutions for strongly-typed HTML development (complete control models, be it ASP.NET Web Controls, or similar to it) that just add amazing complexity to a project. In other situations, it is perfect.

In order of preference in the C# world,

  • ASP.NET Web Controls
  • ASP.NET primitives and HTML controls
  • XmlWriter and/or HtmlWriter
  • If doing Silverlight development with HTML interoperability, consider something strongly typed like link text
  • StringBuilder and other super primitives

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

Easiest way is use this way

my_var=`echo 2` echo $my_var output : 2

note that is not simple single quote is back quote ( ` ).

How to find specific lines in a table using Selenium?

if you want to access table cell

WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[1]")); 

If you want to access nested table cell -

WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[2]"+//table/tbody/tr[1]/td[2]));

For more details visit this Tutorial

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

I used a proxy url to solve a similar problem when I want to post data to my apache solr hosted in another server. (This may not be the perfect answer but it solves my problem.)

Follow this URL: Using Mode-Rewrite for proxying, I add this line to my httpd.conf:

 RewriteRule ^solr/(.*)$ http://ip:8983/solr$1 [P]

Therefore, I can just post data to /solr instead of posting data to http://ip:8983/solr/*. Then it will be posting data in the same origin.

AlertDialog.Builder with custom layout and EditText; cannot access view

editText is a part of alertDialog layout so Just access editText with reference of alertDialog

EditText editText = (EditText) alertDialog.findViewById(R.id.label_field);

Update:

Because in code line dialogBuilder.setView(inflater.inflate(R.layout.alert_label_editor, null));

inflater is Null.

update your code like below, and try to understand the each code line

AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);

EditText editText = (EditText) dialogView.findViewById(R.id.label_field);
editText.setText("test label");
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();

Update 2:

As you are using View object created by Inflater to update UI components else you can directly use setView(int layourResId) method of AlertDialog.Builder class, which is available from API 21 and onwards.

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

After debugging and spending a lot of time, in my case, the issue was with the access_key_id and secret_access_key, just double check your credentials or generate new one if possible and make sure you are passing the credentials in params.

How to convert string representation of list to a list?

You may run into such problem while dealing with scraped data stored as Pandas DataFrame.

This solution works like charm if the list of values is present as text.

def textToList(hashtags):
    return hashtags.strip('[]').replace('\'', '').replace(' ', '').split(',')

hashtags = "[ 'A','B','C' , ' D']"
hashtags = textToList(hashtags)

Output: ['A', 'B', 'C', 'D']

No external library required.

How to print the value of a Tensor object in TensorFlow?

Basically, in tensorflow when you create a tensor of any sort they are created and stored inside which can be accessed only when you run a tensorflow session. Say you have created a constant tensor
c = tf.constant([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])
Without running a session, you can get
- op: An Operation. Operation that computes this tensor.
- value_index: An int. Index of the operation's endpoint that produces this tensor.
- dtype: A DType. Type of elements stored in this tensor.

To get the values you can run a session with the tensor you require as:

with tf.Session() as sess:
    print(sess.run(c))
    sess.close()

The output will be something like this:

array([[1., 2., 3.], [4., 5., 6.]], dtype=float32)

How to include bootstrap css and js in reactjs app?

Just in case if you can use yarn which is recommended for React apps,

you can do,

yarn add [email protected] // this is to add bootstrap with a specific  version

This will add the bootstrap as a dependency to your package.json as well.

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "bootstrap": "4.1.1", // it will add an entry here
    "react": "^16.5.2",
    "react-dom": "^16.5.2",
    "react-scripts": "1.1.5"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  }
}

After that just import bootstrap in your index.js file.

import 'bootstrap/dist/css/bootstrap.css';

if else in a list comprehension

You can also put the conditional expression in brackets inside the list comprehension:

    l = [22, 13, 45, 50, 98, 69, 43, 44, 1]
    print [[x+5,x+1][x >= 45] for x in l]

[false,true][condition] is the syntax

MySQL "NOT IN" query

The subquery option has already been answered, but note that in many cases a LEFT JOIN can be a faster way to do this:

SELECT table1.*
FROM table1 LEFT JOIN table2 ON table2.principal=table1.principal
WHERE table2.principal IS NULL

If you want to check multiple tables to make sure it's not present in any of the tables (like in SRKR's comment), you can use this:

SELECT table1.*
FROM table1
LEFT JOIN table2 ON table2.name=table1.name
LEFT JOIN table3 ON table3.name=table1.name
WHERE table2.name IS NULL AND table3.name IS NULL

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

Npm Error - No matching version found for

If none of this did not help, then try to swap ^ in "^version" to ~ "~version".

Force an SVN checkout command to overwrite current files

svn checkout --force svn://repo website.dir

then

svn revert -R website.dir

Will check out on top of existing files in website.dir, but not overwrite them. Then the revert will overwrite them. This way you do not need to take the site down to complete it.

How to find a user's home directory on linux or unix?

If you want to find a specific user's home directory, I don't believe you can do it directly.

When I've needed to do this before from Java I had to write some JNI native code that wrapped the UNIX getpwXXX() family of calls.

JavaScript: How to pass object by value?

You're a little confused about how objects work in JavaScript. The object's reference is the value of the variable. There is no unserialized value. When you create an object, its structure is stored in memory and the variable it was assigned to holds a reference to that structure.

Even if what you're asking was provided in some sort of easy, native language construct it would still technically be cloning.

JavaScript is really just pass-by-value... it's just that the value passed might be a reference to something.

Subtracting Dates in Oracle - Number or Interval Datatype?

Ok, I don't normally answer my own questions but after a bit of tinkering, I have figured out definitively how Oracle stores the result of a DATE subtraction.

When you subtract 2 dates, the value is not a NUMBER datatype (as the Oracle 11.2 SQL Reference manual would have you believe). The internal datatype number of a DATE subtraction is 14, which is a non-documented internal datatype (NUMBER is internal datatype number 2). However, it is actually stored as 2 separate two's complement signed numbers, with the first 4 bytes used to represent the number of days and the last 4 bytes used to represent the number of seconds.

An example of a DATE subtraction resulting in a positive integer difference:

select date '2009-08-07' - date '2008-08-08' from dual;

Results in:

DATE'2009-08-07'-DATE'2008-08-08'
---------------------------------
                              364

select dump(date '2009-08-07' - date '2008-08-08') from dual;

DUMP(DATE'2009-08-07'-DATE'2008
-------------------------------
Typ=14 Len=8: 108,1,0,0,0,0,0,0

Recall that the result is represented as a 2 seperate two's complement signed 4 byte numbers. Since there are no decimals in this case (364 days and 0 hours exactly), the last 4 bytes are all 0s and can be ignored. For the first 4 bytes, because my CPU has a little-endian architecture, the bytes are reversed and should be read as 1,108 or 0x16c, which is decimal 364.

An example of a DATE subtraction resulting in a negative integer difference:

select date '1000-08-07' - date '2008-08-08' from dual;

Results in:

DATE'1000-08-07'-DATE'2008-08-08'
---------------------------------
                          -368160

select dump(date '1000-08-07' - date '2008-08-08') from dual;

DUMP(DATE'1000-08-07'-DATE'2008-08-0
------------------------------------
Typ=14 Len=8: 224,97,250,255,0,0,0,0

Again, since I am using a little-endian machine, the bytes are reversed and should be read as 255,250,97,224 which corresponds to 11111111 11111010 01100001 11011111. Now since this is in two's complement signed binary numeral encoding, we know that the number is negative because the leftmost binary digit is a 1. To convert this into a decimal number we would have to reverse the 2's complement (subtract 1 then do the one's complement) resulting in: 00000000 00000101 10011110 00100000 which equals -368160 as suspected.

An example of a DATE subtraction resulting in a decimal difference:

select to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS'
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS') from dual;

TO_DATE('08/AUG/200414:00:00','DD/MON/YYYYHH24:MI:SS')-TO_DATE('08/AUG/20048:00:
--------------------------------------------------------------------------------
                                                                             .25

The difference between those 2 dates is 0.25 days or 6 hours.

select dump(to_date('08/AUG/2004 14:00:00', 'DD/MON/YYYY HH24:MI:SS')
 - to_date('08/AUG/2004 8:00:00', 'DD/MON/YYYY HH24:MI:SS')) from dual;

DUMP(TO_DATE('08/AUG/200414:00:
-------------------------------
Typ=14 Len=8: 0,0,0,0,96,84,0,0

Now this time, since the difference is 0 days and 6 hours, it is expected that the first 4 bytes are 0. For the last 4 bytes, we can reverse them (because CPU is little-endian) and get 84,96 = 01010100 01100000 base 2 = 21600 in decimal. Converting 21600 seconds to hours gives you 6 hours which is the difference which we expected.

Hope this helps anyone who was wondering how a DATE subtraction is actually stored.


You get the syntax error because the date math does not return a NUMBER, but it returns an INTERVAL:

SQL> SELECT DUMP(SYSDATE - start_date) from test;

DUMP(SYSDATE-START_DATE)
-------------------------------------- 
Typ=14 Len=8: 188,10,0,0,223,65,1,0

You need to convert the number in your example into an INTERVAL first using the NUMTODSINTERVAL Function

For example:

SQL> SELECT (SYSDATE - start_date) DAY(5) TO SECOND from test;

(SYSDATE-START_DATE)DAY(5)TOSECOND
----------------------------------
+02748 22:50:04.000000

SQL> SELECT (SYSDATE - start_date) from test;

(SYSDATE-START_DATE)
--------------------
           2748.9515

SQL> select NUMTODSINTERVAL(2748.9515, 'day') from dual;

NUMTODSINTERVAL(2748.9515,'DAY')
--------------------------------
+000002748 22:50:09.600000000

SQL>

Based on the reverse cast with the NUMTODSINTERVAL() function, it appears some rounding is lost in translation.

Android List View Drag and Drop sort

I have been working on this for some time now. Tough to get right, and I don't claim I do, but I'm happy with it so far. My code and several demos can be found at

Its use is very similar to the TouchInterceptor (on which the code is based), although significant implementation changes have been made.

DragSortListView has smooth and predictable scrolling while dragging and shuffling items. Item shuffles are much more consistent with the position of the dragging/floating item. Heterogeneous-height list items are supported. Drag-scrolling is customizable (I demonstrate rapid drag scrolling through a long list---not that an application comes to mind). Headers/Footers are respected. etc.?? Take a look.

How to save a list to a file and read it as a list type?

If you don't want to use pickle, you can store the list as text and then evaluate it:

data = [0,1,2,3,4,5]
with open("test.txt", "w") as file:
    file.write(str(data))

with open("test.txt", "r") as file:
    data2 = eval(file.readline())

# Let's see if data and types are same.
print(data, type(data), type(data[0]))
print(data2, type(data2), type(data2[0]))

[0, 1, 2, 3, 4, 5] class 'list' class 'int'

[0, 1, 2, 3, 4, 5] class 'list' class 'int'

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

Reason: no suitable image found

At the risk of sowing more confusion, I had this issue when updating to XC8.

None of these suggestions, nor from any other thread, solved it. What DID work, was removing EVERYTHING from the "Link Binary with Libraries" build phase, the "Target Dependencies" build phase, and the "Linked Frameworks and Libraries" General setting.

FYI, I'm using Carthage and had added $(PROJECT_DIR)/Carthage/Build/tvOS to the FRAMEWORK_SEARCH_PATHS build setting, so that my frameworks could be found.

FYI 2, this projects and the frameworks, are 100% swift and the frameworks are building DEFINES_MODULE = YES.

Scala Doubles, and Precision

For those how are interested, here are some times for the suggested solutions...

Rounding
Java Formatter: Elapsed Time: 105
Scala Formatter: Elapsed Time: 167
BigDecimal Formatter: Elapsed Time: 27

Truncation
Scala custom Formatter: Elapsed Time: 3 

Truncation is the fastest, followed by BigDecimal. Keep in mind these test were done running norma scala execution, not using any benchmarking tools.

object TestFormatters {

  val r = scala.util.Random

  def textFormatter(x: Double) = new java.text.DecimalFormat("0.##").format(x)

  def scalaFormatter(x: Double) = "$pi%1.2f".format(x)

  def bigDecimalFormatter(x: Double) = BigDecimal(x).setScale(2, BigDecimal.RoundingMode.HALF_UP).toDouble

  def scalaCustom(x: Double) = {
    val roundBy = 2
    val w = math.pow(10, roundBy)
    (x * w).toLong.toDouble / w
  }

  def timed(f: => Unit) = {
    val start = System.currentTimeMillis()
    f
    val end = System.currentTimeMillis()
    println("Elapsed Time: " + (end - start))
  }

  def main(args: Array[String]): Unit = {

    print("Java Formatter: ")
    val iters = 10000
    timed {
      (0 until iters) foreach { _ =>
        textFormatter(r.nextDouble())
      }
    }

    print("Scala Formatter: ")
    timed {
      (0 until iters) foreach { _ =>
        scalaFormatter(r.nextDouble())
      }
    }

    print("BigDecimal Formatter: ")
    timed {
      (0 until iters) foreach { _ =>
        bigDecimalFormatter(r.nextDouble())
      }
    }

    print("Scala custom Formatter (truncation): ")
    timed {
      (0 until iters) foreach { _ =>
        scalaCustom(r.nextDouble())
      }
    }
  }

}

CSS list item width/height does not work

Using width/height on inline elements is not always a good idea. You can use display: inline-block instead

SOAP client in .NET - references or examples?

Here you can find a nice tutorial for calling a NuSOAP-based web-service from a .NET client application. But IMO, you should also consider the WSO2 Web Services Framework for PHP (WSO2 WSF/PHP) for servicing. See WSO2 Web Services Framework for PHP 2.0 Significantly Enhances Industry’s Only PHP Library for Creating Both SOAP and REST Services. There is also a webminar about it.

Now, in .NET world I also encourage the use of WCF, taking into account the interoperability issues. An interoperability example can be found here, but this example uses a PHP-client + WCF-service instead of the opposite. Feel free to implement the PHP-service & WFC-client.

There are some WCF's related open source projects on codeplex.com that I found very productive. These projects are very useful to design & implement Win Forms and Windows Presentation Foundation applications: Smart Client, Web Client and Mobile Client. They can be used in combination with WCF to wisely call any kind of Web services.

Generally speaking, the patterns & practices team summarize good practices & designs in various open source projects that dealing with the .NET platform, specially for the web. So I think it's a good starting point for any design decision related to .NET clients.

What is the significance of url-pattern in web.xml and how to configure servlet?

url-pattern is used in web.xml to map your servlet to specific URL. Please see below xml code, similar code you may find in your web.xml configuration file.

<servlet>
    <servlet-name>AddPhotoServlet</servlet-name>  //servlet name
    <servlet-class>upload.AddPhotoServlet</servlet-class>  //servlet class
</servlet>
 <servlet-mapping>
    <servlet-name>AddPhotoServlet</servlet-name>   //servlet name
    <url-pattern>/AddPhotoServlet</url-pattern>  //how it should appear
</servlet-mapping>

If you change url-pattern of AddPhotoServlet from /AddPhotoServlet to /MyUrl. Then, AddPhotoServlet servlet can be accessible by using /MyUrl. Good for the security reason, where you want to hide your actual page URL.

Java Servlet url-pattern Specification:

  1. A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
  2. A string beginning with a '*.' prefix is used as an extension mapping.
  3. A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
  4. All other strings are used for exact matches only.

Reference : Java Servlet Specification

You may also read this Basics of Java Servlet

Simplest two-way encryption using PHP

Important: Unless you have a very particular use-case, do not encrypt passwords, use a password hashing algorithm instead. When someone says they encrypt their passwords in a server-side application, they're either uninformed or they're describing a dangerous system design. Safely storing passwords is a totally separate problem from encryption.

Be informed. Design safe systems.

Portable Data Encryption in PHP

If you're using PHP 5.4 or newer and don't want to write a cryptography module yourself, I recommend using an existing library that provides authenticated encryption. The library I linked relies only on what PHP provides and is under periodic review by a handful of security researchers. (Myself included.)

If your portability goals do not prevent requiring PECL extensions, libsodium is highly recommended over anything you or I can write in PHP.

Update (2016-06-12): You can now use sodium_compat and use the same crypto libsodium offers without installing PECL extensions.

If you want to try your hand at cryptography engineering, read on.


First, you should take the time to learn the dangers of unauthenticated encryption and the Cryptographic Doom Principle.

  • Encrypted data can still be tampered with by a malicious user.
  • Authenticating the encrypted data prevents tampering.
  • Authenticating the unencrypted data does not prevent tampering.

Encryption and Decryption

Encryption in PHP is actually simple (we're going to use openssl_encrypt() and openssl_decrypt() once you have made some decisions about how to encrypt your information. Consult openssl_get_cipher_methods() for a list of the methods supported on your system. The best choice is AES in CTR mode:

  • aes-128-ctr
  • aes-192-ctr
  • aes-256-ctr

There is currently no reason to believe that the AES key size is a significant issue to worry about (bigger is probably not better, due to bad key-scheduling in the 256-bit mode).

Note: We are not using mcrypt because it is abandonware and has unpatched bugs that might be security-affecting. Because of these reasons, I encourage other PHP developers to avoid it as well.

Simple Encryption/Decryption Wrapper using OpenSSL

class UnsafeCrypto
{
    const METHOD = 'aes-256-ctr';

    /**
     * Encrypts (but does not authenticate) a message
     * 
     * @param string $message - plaintext message
     * @param string $key - encryption key (raw binary expected)
     * @param boolean $encode - set to TRUE to return a base64-encoded 
     * @return string (raw binary)
     */
    public static function encrypt($message, $key, $encode = false)
    {
        $nonceSize = openssl_cipher_iv_length(self::METHOD);
        $nonce = openssl_random_pseudo_bytes($nonceSize);

        $ciphertext = openssl_encrypt(
            $message,
            self::METHOD,
            $key,
            OPENSSL_RAW_DATA,
            $nonce
        );

        // Now let's pack the IV and the ciphertext together
        // Naively, we can just concatenate
        if ($encode) {
            return base64_encode($nonce.$ciphertext);
        }
        return $nonce.$ciphertext;
    }

    /**
     * Decrypts (but does not verify) a message
     * 
     * @param string $message - ciphertext message
     * @param string $key - encryption key (raw binary expected)
     * @param boolean $encoded - are we expecting an encoded string?
     * @return string
     */
    public static function decrypt($message, $key, $encoded = false)
    {
        if ($encoded) {
            $message = base64_decode($message, true);
            if ($message === false) {
                throw new Exception('Encryption failure');
            }
        }

        $nonceSize = openssl_cipher_iv_length(self::METHOD);
        $nonce = mb_substr($message, 0, $nonceSize, '8bit');
        $ciphertext = mb_substr($message, $nonceSize, null, '8bit');

        $plaintext = openssl_decrypt(
            $ciphertext,
            self::METHOD,
            $key,
            OPENSSL_RAW_DATA,
            $nonce
        );

        return $plaintext;
    }
}

Usage Example

$message = 'Ready your ammunition; we attack at dawn.';
$key = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');

$encrypted = UnsafeCrypto::encrypt($message, $key);
$decrypted = UnsafeCrypto::decrypt($encrypted, $key);

var_dump($encrypted, $decrypted);

Demo: https://3v4l.org/jl7qR


The above simple crypto library still is not safe to use. We need to authenticate ciphertexts and verify them before we decrypt.

Note: By default, UnsafeCrypto::encrypt() will return a raw binary string. Call it like this if you need to store it in a binary-safe format (base64-encoded):

$message = 'Ready your ammunition; we attack at dawn.';
$key = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');

$encrypted = UnsafeCrypto::encrypt($message, $key, true);
$decrypted = UnsafeCrypto::decrypt($encrypted, $key, true);

var_dump($encrypted, $decrypted);

Demo: http://3v4l.org/f5K93

Simple Authentication Wrapper

class SaferCrypto extends UnsafeCrypto
{
    const HASH_ALGO = 'sha256';

    /**
     * Encrypts then MACs a message
     * 
     * @param string $message - plaintext message
     * @param string $key - encryption key (raw binary expected)
     * @param boolean $encode - set to TRUE to return a base64-encoded string
     * @return string (raw binary)
     */
    public static function encrypt($message, $key, $encode = false)
    {
        list($encKey, $authKey) = self::splitKeys($key);

        // Pass to UnsafeCrypto::encrypt
        $ciphertext = parent::encrypt($message, $encKey);

        // Calculate a MAC of the IV and ciphertext
        $mac = hash_hmac(self::HASH_ALGO, $ciphertext, $authKey, true);

        if ($encode) {
            return base64_encode($mac.$ciphertext);
        }
        // Prepend MAC to the ciphertext and return to caller
        return $mac.$ciphertext;
    }

    /**
     * Decrypts a message (after verifying integrity)
     * 
     * @param string $message - ciphertext message
     * @param string $key - encryption key (raw binary expected)
     * @param boolean $encoded - are we expecting an encoded string?
     * @return string (raw binary)
     */
    public static function decrypt($message, $key, $encoded = false)
    {
        list($encKey, $authKey) = self::splitKeys($key);
        if ($encoded) {
            $message = base64_decode($message, true);
            if ($message === false) {
                throw new Exception('Encryption failure');
            }
        }

        // Hash Size -- in case HASH_ALGO is changed
        $hs = mb_strlen(hash(self::HASH_ALGO, '', true), '8bit');
        $mac = mb_substr($message, 0, $hs, '8bit');

        $ciphertext = mb_substr($message, $hs, null, '8bit');

        $calculated = hash_hmac(
            self::HASH_ALGO,
            $ciphertext,
            $authKey,
            true
        );

        if (!self::hashEquals($mac, $calculated)) {
            throw new Exception('Encryption failure');
        }

        // Pass to UnsafeCrypto::decrypt
        $plaintext = parent::decrypt($ciphertext, $encKey);

        return $plaintext;
    }

    /**
     * Splits a key into two separate keys; one for encryption
     * and the other for authenticaiton
     * 
     * @param string $masterKey (raw binary)
     * @return array (two raw binary strings)
     */
    protected static function splitKeys($masterKey)
    {
        // You really want to implement HKDF here instead!
        return [
            hash_hmac(self::HASH_ALGO, 'ENCRYPTION', $masterKey, true),
            hash_hmac(self::HASH_ALGO, 'AUTHENTICATION', $masterKey, true)
        ];
    }

    /**
     * Compare two strings without leaking timing information
     * 
     * @param string $a
     * @param string $b
     * @ref https://paragonie.com/b/WS1DLx6BnpsdaVQW
     * @return boolean
     */
    protected static function hashEquals($a, $b)
    {
        if (function_exists('hash_equals')) {
            return hash_equals($a, $b);
        }
        $nonce = openssl_random_pseudo_bytes(32);
        return hash_hmac(self::HASH_ALGO, $a, $nonce) === hash_hmac(self::HASH_ALGO, $b, $nonce);
    }
}

Usage Example

$message = 'Ready your ammunition; we attack at dawn.';
$key = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');

$encrypted = SaferCrypto::encrypt($message, $key);
$decrypted = SaferCrypto::decrypt($encrypted, $key);

var_dump($encrypted, $decrypted);

Demos: raw binary, base64-encoded


If anyone wishes to use this SaferCrypto library in a production environment, or your own implementation of the same concepts, I strongly recommend reaching out to your resident cryptographers for a second opinion before you do. They'll be able tell you about mistakes that I might not even be aware of.

You will be much better off using a reputable cryptography library.

How to set ANDROID_HOME path in ubuntu?

In my case it works with a little change. Simply by putting :$PATH at the end.

# andorid paths
export ANDROID_HOME=$HOME/Android/Sdk
export PATH="$ANDROID_HOME/tools:$PATH"
export PATH="$ANDROID_HOME/platform-tools:$PATH"
export PATH="$ANDROID_HOME/emulator:$PATH"

Optimistic vs. Pessimistic locking

In addition to what's been said already:

  • It should be said that optimistic locking tends to improve concurrency at the expense of predictability.
  • Pessimistic locking tends to reduce concurrency, but is more predictable. You pay your money, etc ...

Opening a CHM file produces: "navigation to the webpage was canceled"

Moving to local folder is the quickest solution, nothing else worked for me esp because I was not admin on my system (can't edit registery etc), which is a typical case in a work environment.

Create a folder in C:\help drive, lets call it help and copy the files there and open.

Do not copy to mydocuments or anywhere else, those locations are usually on network drive in office setup and will not work.

Remove spaces from std::string in C++

Removes all whitespace characters such as tabs and line breaks (C++11):

string str = " \n AB cd \t efg\v\n";
str = regex_replace(str,regex("\\s"),"");

How to convert an NSString into an NSNumber

Objective-C

(Note: this method doesn't play nice with difference locales, but is slightly faster than a NSNumberFormatter)

NSNumber *num1 = @([@"42" intValue]);
NSNumber *num2 = @([@"42.42" floatValue]);

Swift

Simple but dirty way

// Swift 1.2
if let intValue = "42".toInt() {
    let number1 = NSNumber(integer:intValue)
}

// Swift 2.0
let number2 = Int("42')

// Swift 3.0
NSDecimalNumber(string: "42.42") 

// Using NSNumber
let number3 = NSNumber(float:("42.42" as NSString).floatValue)

The extension-way This is better, really, because it'll play nicely with locales and decimals.

extension String {

    var numberValue:NSNumber? {
        let formatter = NSNumberFormatter()
        formatter.numberStyle = .DecimalStyle
        return formatter.number(from: self)
    }
}

Now you can simply do:

let someFloat = "42.42".numberValue
let someInt = "42".numberValue

jQuery check if an input is type checkbox?

You can use the pseudo-selector :checkbox with a call to jQuery's is function:

$('#myinput').is(':checkbox')

"for loop" with two variables?

If you really just have lock-step iteration over a range, you can do it one of several ways:

for i in range(x):
  j = i
  …
# or
for i, j in enumerate(range(x)):
  …
# or
for i, j in ((i,i) for i in range(x)):
  …

All of the above are equivalent to for i, j in zip(range(x), range(y)) if x <= y.

If you want a nested loop and you only have two iterables, just use a nested loop:

for i in range(x):
  for i in range(y):
    …

If you have more than two iterables, use itertools.product.

Finally, if you want lock-step iteration up to x and then to continue to y, you have to decide what the rest of the x values should be.

for i, j in itertools.zip_longest(range(x), range(y), fillvalue=float('nan')):
  …
# or
for i in range(min(x,y)):
  j = i
  …
for i in range(min(x,y), max(x,y)):
  j = float('nan')
  …

How to disable Hyper-V in command line?

you can use my script. paste code lines to notepad and save as vbs(for example switch_hypervisor.vbs)

Option Explicit

Dim backupfile
Dim record
Dim myshell
Dim appmyshell
Dim myresult
Dim myline
Dim makeactive
Dim makepassive
Dim reboot
record=""
Set myshell = WScript.CreateObject("WScript.Shell")

If WScript.Arguments.Length = 0 Then
    Set appmyshell  = CreateObject("Shell.Application")
    appmyshell.ShellExecute "wscript.exe", """" & WScript.ScriptFullName & """ RunAsAdministrator", , "runas", 1
    WScript.Quit
End if




Set backupfile = CreateObject("Scripting.FileSystemObject")
If Not (backupfile.FileExists("C:\bcdedit.bak")) Then
    Set myresult = myshell.Exec("cmd /c bcdedit /export c:\bcdedit.bak")
End If

Set myresult = myshell.Exec("cmd /c bcdedit")
Do While Not myresult.StdOut.AtEndOfStream
    myline = myresult.StdOut.ReadLine()

    If myline="The boot configuration data store could not be opened." Then
        record=""
        exit do
    End If
    If Instr(myline, "identifier") > 0 Then
        record=""
        If Instr(myline, "{current}") > 0 Then
            record="current"
        End If
    End If
    If Instr(myline, "hypervisorlaunchtype") > 0 And record = "current" Then
        If Instr(myline, "Auto") > 0 Then
            record="1"
            Exit Do
        End If
        If Instr(myline, "On") > 0 Then
            record="1"
            Exit Do
        End If
        If Instr(myline, "Off") > 0 Then
            record="0"
            Exit Do
        End If
    End If
Loop

If record="1" Then
    makepassive = MsgBox ("Hypervisor status is active, do you want set to passive? ", vbYesNo, "Hypervisor")
    Select Case makepassive
    Case vbYes
        myshell.run "cmd.exe /C  bcdedit /set hypervisorlaunchtype off"
        reboot = MsgBox ("Hypervisor chenged to passive; Computer must reboot. Reboot now? ", vbYesNo, "Hypervisor")
        Select Case reboot
            Case vbYes
                myshell.run "cmd.exe /C  shutdown /r /t 0"
        End Select
    Case vbNo
        MsgBox("Not Changed")
    End Select
End If

If record="0" Then
    makeactive = MsgBox ("Hypervisor status is passive, do you want set active? ", vbYesNo, "Hypervisor")
    Select Case makeactive
    Case vbYes
        myshell.run "cmd.exe /C  bcdedit /set hypervisorlaunchtype auto"
        reboot = MsgBox ("Hypervisor changed to active;  Computer must reboot. Reboot now?", vbYesNo, "Hypervisor")
        Select Case reboot
            Case vbYes
                myshell.run "cmd.exe /C  shutdown /r /t 0"
        End Select
    Case vbNo
        MsgBox("Not Changed")
    End Select
End If

If record="" Then
        MsgBox("Error: record can't find")
End If

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

You can use

$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);

or define auto-size:

$objWorksheet->getRowDimension('1')->setRowHeight(-1);

Undefined reference to `sin`

I have the problem anyway with -lm added

gcc -Wall -lm mtest.c -o mtest.o
mtest.c: In function 'f1':
mtest.c:6:12: warning: unused variable 'res' [-Wunused-variable]
/tmp/cc925Nmf.o: In function `f1':
mtest.c:(.text+0x19): undefined reference to `sin'
collect2: ld returned 1 exit status

I discovered recently that it does not work if you first specify -lm. The order matters:

gcc mtest.c -o mtest.o -lm

Just link without problems

So you must specify the libraries after.

React.js: Wrapping one component into another

In addition to Sophie's answer, I also have found a use in sending in child component types, doing something like this:

var ListView = React.createClass({
    render: function() {
        var items = this.props.data.map(function(item) {
            return this.props.delegate({data:item});
        }.bind(this));
        return <ul>{items}</ul>;
    }
});

var ItemDelegate = React.createClass({
    render: function() {
        return <li>{this.props.data}</li>
    }
});

var Wrapper = React.createClass({    
    render: function() {
        return <ListView delegate={ItemDelegate} data={someListOfData} />
    }
});

JQuery, setTimeout not working

SetTimeout is used to make your set of code to execute after a specified time period so for your requirements its better to use setInterval because that will call your function every time at a specified time interval.

Javascript isnull

return results == null ? 0 : (results[1] || 0);

How do I round to the nearest 0.5?

decimal d = // your number..

decimal t = d - Math.Floor(d);
if(t >= 0.3d && t <= 0.7d)
{
    return Math.Floor(d) + 0.5d;
}
else if(t>0.7d)
    return Math.Ceil(d);
return Math.Floor(d);

How to iterate over a column vector in Matlab?

with many functions in matlab, you don't need to iterate at all.

for example, to multiply by it's position in the list:

m = [1:numel(list)]';
elm = list.*m;

vectorized algorithms in matlab are in general much faster.

How can I load storyboard programmatically from class?

In your storyboard go to the Attributes inspector and set the view controller's Identifier. You can then present that view controller using the following code.

UIStoryboard *sb = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];
UIViewController *vc = [sb instantiateViewControllerWithIdentifier:@"myViewController"];
vc.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentViewController:vc animated:YES completion:NULL];

What's an easy way to read random line from a file in Unix command line?

Single bash line:

sed -n $((1+$RANDOM%`wc -l test.txt | cut -f 1 -d ' '`))p test.txt

Slight problem: duplicate filename.

How to connect to a MS Access file (mdb) using C#?

Here's how to use a Jet OLEDB or Ace OLEDB Access DB:

using System.Data;
using System.Data.OleDb;

string myConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
                           "Data Source=C:\myPath\myFile.mdb;" +                                    
                           "Persist Security Info=True;" +
                           "Jet OLEDB:Database Password=myPassword;";
try
{
    // Open OleDb Connection
    OleDbConnection myConnection = new OleDbConnection();
    myConnection.ConnectionString = myConnectionString;
    myConnection.Open();

    // Execute Queries
    OleDbCommand cmd = myConnection.CreateCommand();
    cmd.CommandText = "SELECT * FROM `myTable`";
    OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); // close conn after complete

    // Load the result into a DataTable
    DataTable myDataTable = new DataTable();
    myDataTable.Load(reader);
}
catch (Exception ex)
{
    Console.WriteLine("OLEDB Connection FAILED: " + ex.Message);
}

Activate a virtualenv with a Python script

To run another Python environment according to the official Virtualenv documentation, in the command line you can specify the full path to the executable Python binary, just that (no need to active the virtualenv before):

/path/to/virtualenv/bin/python

The same applies if you want to invoke a script from the command line with your virtualenv. You don't need to activate it before:

me$ /path/to/virtualenv/bin/python myscript.py

The same for a Windows environment (whether it is from the command line or from a script):

> \path\to\env\Scripts\python.exe myscript.py

How to join (merge) data frames (inner, outer, left, right)

I would recommend checking out Gabor Grothendieck's sqldf package, which allows you to express these operations in SQL.

library(sqldf)

## inner join
df3 <- sqldf("SELECT CustomerId, Product, State 
              FROM df1
              JOIN df2 USING(CustomerID)")

## left join (substitute 'right' for right join)
df4 <- sqldf("SELECT CustomerId, Product, State 
              FROM df1
              LEFT JOIN df2 USING(CustomerID)")

I find the SQL syntax to be simpler and more natural than its R equivalent (but this may just reflect my RDBMS bias).

See Gabor's sqldf GitHub for more information on joins.

What is the difference between Promises and Observables?

Promise vs Observable similarity first

  1. Both used to handle async code.
  2. Please look for promise example. Promise constructor passes a resolve reference function which will get called when it gets called with some value upon completion of some async task.

const promise = new Promise(resolve => {
  setTimeout(() => {
    resolve("Hello from a Promise!");
  }, 2000);
});

promise.then(value => console.log(value));

  1. Observable example now. Here also we pass a function to observable, an observer to handle the async task. Unlike resolve in the promise it has the following method and subscribes in place of then.

  2. So both handles async tasks. Now let's see the difference.


const observable = new Observable(observer => {
  setTimeout(() => {
    observer.next('Hello from a Observable!');
  }, 2000);
});

observable.subscribe(value => console.log(value));

Promise vs Observable difference

Promise

  1. It resolves or reject a single value and can handle a single value async task at a time.
  2. A promise once resolved the async value it completes, can no longer be used.its just one-time use and here it falls short.
  3. Not cancellable
  4. No rxjs support for operators.

Observable

  1. ability to emit multiple asynchronous values.
  2. Used to handle the stream of events or values. Consider you have an array of numerous tasks or values, and you want every time value is inserted into this it should be handled automatically. Anytime you push a value into this array, all of its subscribers will receive the latest value automatically.
  3. Observables are useful for observing input changes, repeated interval, broadcast values to all child components, web socket push notifications etc.
  4. Can be cancelled using unsubscribe method anytime.
  5. One more last good part that promise that has is support for rxjs operators. You have many pipe operators majorly map, filter, switchMap, combineLatest etc. to transform observable data before subscribing.

enter image description here


insert multiple rows into DB2 database

other method

INSERT INTO tableName (col1, col2, col3, col4, col5)
select * from table(                        
                    values                                      
                    (val1, val2, val3, val4, val5),   
                    (val1, val2, val3, val4, val5),   
                    (val1, val2, val3, val4, val5),   
                    (val1, val2, val3, val4, val5)    
                    ) tmp

mongodb, replicates and error: { "$err" : "not master and slaveOk=false", "code" : 13435 }

You have to set "secondary okay" mode to let the mongo shell know that you're allowing reads from a secondary. This is to protect you and your applications from performing eventually consistent reads by accident. You can do this in the shell with:

rs.secondaryOk()

After that you can query normally from secondaries.

A note about "eventual consistency": under normal circumstances, replica set secondaries have all the same data as primaries within a second or less. Under very high load, data that you've written to the primary may take a while to replicate to the secondaries. This is known as "replica lag", and reading from a lagging secondary is known as an "eventually consistent" read, because, while the newly written data will show up at some point (barring network failures, etc), it may not be immediately available.

Edit: You only need to set secondaryOk when querying from secondaries, and only once per session.

add class with JavaScript

Simply add a class name to the beginning of the funciton and the 2nd and 3rd arguments are optional and the magic is done for you!

function getElementsByClass(searchClass, node, tag) {

  var classElements = new Array();

  if (node == null)

    node = document;

  if (tag == null)

    tag = '*';

  var els = node.getElementsByTagName(tag);

  var elsLen = els.length;

  var pattern = new RegExp('(^|\\\\s)' + searchClass + '(\\\\s|$)');

  for (i = 0, j = 0; i < elsLen; i++) {

    if (pattern.test(els[i].className)) {

      classElements[j] = els[i];

      j++;

    }

  }

  return classElements;

}

How to let PHP to create subdomain automatically for each user?

This can be achieved in .htaccess provided your server is configured to allow wildcard subdomains. I achieved that in JustHost by creating a subomain manually named * and specifying a folder called subdomains as the document root for wildcard subdomains. Add this to your .htaccess file:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\.website\.com$
RewriteCond %{HTTP_HOST} ^(\w+)\.website\.com$
RewriteCond %{REQUEST_URI}:%1 !^/([^/]+)/([^:]*):\1
RewriteRule ^(.*)$ /%1/$1 [QSA]

Finally, create a folder for your subdomain and place the subdomains files.

How can I disable the Maven Javadoc plugin from the command line?

It seems, that the simple way

-Dmaven.javadoc.skip=true

does not work with the release-plugin. in this case you have to pass the parameter as an "argument"

mvn release:perform -Darguments="-Dmaven.javadoc.skip=true"

How to do date/time comparison

Use the time package to work with time information in Go.

Time instants can be compared using the Before, After, and Equal methods. The Sub method subtracts two instants, producing a Duration. The Add method adds a Time and a Duration, producing a Time.

Play example:

package main

import (
    "fmt"
    "time"
)

func inTimeSpan(start, end, check time.Time) bool {
    return check.After(start) && check.Before(end)
}

func main() {
    start, _ := time.Parse(time.RFC822, "01 Jan 15 10:00 UTC")
    end, _ := time.Parse(time.RFC822, "01 Jan 16 10:00 UTC")

    in, _ := time.Parse(time.RFC822, "01 Jan 15 20:00 UTC")
    out, _ := time.Parse(time.RFC822, "01 Jan 17 10:00 UTC")

    if inTimeSpan(start, end, in) {
        fmt.Println(in, "is between", start, "and", end, ".")
    }

    if !inTimeSpan(start, end, out) {
        fmt.Println(out, "is not between", start, "and", end, ".")
    }
}

Delete a closed pull request from GitHub

5 step to do what you want if you made the pull request from a forked repository:

  1. reopen the pull request
  2. checkout to the branch which you made the pull request
  3. reset commit to the last master commit(that means remove all you new code)
  4. git push --force
  5. delete your forked repository which made the pull request

And everything is done, good luck!

Insert some string into given string at given index in Python

For the sake of future 'newbies' tackling this problem, I think a quick answer would be fitting to this thread.

Like bgporter said: Python strings are immutable, and so, in order to modify a string you have to make use of the pieces you already have.

In the following example I insert 'Fu' in to 'Kong Panda', to create 'Kong Fu Panda'

>>> line = 'Kong Panda'
>>> index = line.find('Panda')
>>> output_line = line[:index] + 'Fu ' + line[index:]
>>> output_line
'Kong Fu Panda'

In the example above, I used the index value to 'slice' the string in to 2 substrings: 1 containing the substring before the insertion index, and the other containing the rest. Then I simply add the desired string between the two and voilà, we have inserted a string inside another.

Python's slice notation has a great answer explaining the subject of string slicing.

Align div right in Bootstrap 3

Do you mean something like this:

HTML

<div class="row">
  <div class="container">

    <div class="col-md-4">
      left content
    </div>

    <div class="col-md-4 col-md-offset-4">

      <div class="yellow-background">
        text
        <div class="pull-right">right content</div>  
      </div>

    </div>
  </div>
</div>

CSS

.yellow-background {
  background: blue;
}

.pull-right {
  background: yellow;
}

A full example can be found on Codepen.

UILabel - Wordwrap text

In Swift you would do it like this:

    label.lineBreakMode = NSLineBreakMode.ByWordWrapping
    label.numberOfLines = 0

(Note that the way the lineBreakMode constant works is different to in ObjC)

How to create an android app using HTML 5

Here is a starting point for developing Android apps with HTML5. The HTML code will be stored in the "assets/www" folder in your Android project.

https://github.com/jakewp11/HTML5_Android_Template.git

Syntax error on print with Python 3

In Python 3, print became a function. This means that you need to include parenthesis now like mentioned below:

print("Hello World")

The character encoding of the plain text document was not declared - mootool script

In your HTML it is a good pratice to provide the encoding like using the following meta like this for example:

<meta http-equiv="content-type" content="text/html; charset=utf-8" />

But your warning that you see may be trigged by one of multiple files. it might not be your HTML document. It might be something in a javascript file or css file. if you page is made of up multiples php files included together it may be only 1 of those files.

I dont think this error has anything to do with mootools. you see this message in your firefox console window. not mootools script.

maybe you simply need to re-save your html pages using a code editor that lets you specify the correct character encoding.

HTML table with horizontal scrolling (first column fixed)

How about:

_x000D_
_x000D_
table {_x000D_
  table-layout: fixed; _x000D_
  width: 100%;_x000D_
  *margin-left: -100px; /*ie7*/_x000D_
}_x000D_
td, th {_x000D_
  vertical-align: top;_x000D_
  border-top: 1px solid #ccc;_x000D_
  padding: 10px;_x000D_
  width: 100px;_x000D_
}_x000D_
.fix {_x000D_
  position: absolute;_x000D_
  *position: relative; /*ie7*/_x000D_
  margin-left: -100px;_x000D_
  width: 100px;_x000D_
}_x000D_
.outer {_x000D_
  position: relative;_x000D_
}_x000D_
.inner {_x000D_
  overflow-x: scroll;_x000D_
  overflow-y: visible;_x000D_
  width: 400px; _x000D_
  margin-left: 100px;_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="inner">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <th class=fix></th>_x000D_
        <th>Col 1</th>_x000D_
        <th>Col 2</th>_x000D_
        <th>Col 3</th>_x000D_
        <th>Col 4</th>_x000D_
        <th class="fix">Col 5</th>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th class=fix>Header A</th>_x000D_
        <td>col 1 - A</td>_x000D_
        <td>col 2 - A (WITH LONGER CONTENT)</td>_x000D_
        <td>col 3 - A</td>_x000D_
        <td>col 4 - A</td>_x000D_
        <td class=fix>col 5 - A</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th class=fix>Header B</th>_x000D_
        <td>col 1 - B</td>_x000D_
        <td>col 2 - B</td>_x000D_
        <td>col 3 - B</td>_x000D_
        <td>col 4 - B</td>_x000D_
        <td class=fix>col 5 - B</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <th class=fix>Header C</th>_x000D_
        <td>col 1 - C</td>_x000D_
        <td>col 2 - C</td>_x000D_
        <td>col 3 - C</td>_x000D_
        <td>col 4 - C</td>_x000D_
        <td class=fix>col 5 - C</td>_x000D_
      </tr>_x000D_
    </table>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can test it out in this jsbin: http://jsbin.com/uxecel/4/edit

Read a text file in R line by line

You should take care with readLines(...) and big files. Reading all lines at memory can be risky. Below is a example of how to read file and process just one line at time:

processFile = function(filepath) {
  con = file(filepath, "r")
  while ( TRUE ) {
    line = readLines(con, n = 1)
    if ( length(line) == 0 ) {
      break
    }
    print(line)
  }

  close(con)
}

Understand the risk of reading a line at memory too. Big files without line breaks can fill your memory too.

How to create a cron job using Bash automatically without the interactive editor?

No, there is no option in crontab to modify the cron files.

You have to: take the current cron file (crontab -l > newfile), change it and put the new file in place (crontab newfile).

If you are familiar with perl, you can use this module Config::Crontab.

LLP, Andrea

How to set value to form control in Reactive Forms in Angular

The "usual" solution is make a function that return an empty formGroup or a fullfilled formGroup

createFormGroup(data:any)
{
 return this.fb.group({
   user: [data?data.user:null],
   questioning: [data?data.questioning:null, Validators.required],
   questionType: [data?data.questionType, Validators.required],
   options: new FormArray([this.createArray(data?data.options:null])
})
}

//return an array of formGroup
createArray(data:any[]|null):FormGroup[]
{
   return data.map(x=>this.fb.group({
        ....
   })
}

then, in SUBSCRIBE, you call the function

this.qService.editQue([params["id"]]).subscribe(res => {
  this.editqueForm = this.createFormGroup(res);
});

be carefull!, your form must include an *ngIf to avoid initial error

<form *ngIf="editqueForm" [formGroup]="editqueForm">
   ....
</form>

ASP.NET MVC 3 Razor: Include JavaScript file in the head tag

You can use Named Sections.

_Layout.cshtml

<head>
    <script type="text/javascript" src="@Url.Content("/Scripts/jquery-1.6.2.min.js")"></script>
    @RenderSection("JavaScript", required: false)
</head>

_SomeView.cshtml

@section JavaScript
{
   <script type="text/javascript" src="@Url.Content("/Scripts/SomeScript.js")"></script>
   <script type="text/javascript" src="@Url.Content("/Scripts/AnotherScript.js")"></script>
}

Is there a null-coalescing (Elvis) operator or safe navigation operator in javascript?

This was an interesting solution for the safe navigation operator using some mixin..

http://jsfiddle.net/avernet/npcmv/

  // Assume you have the following data structure
  var companies = {
      orbeon: {
          cfo: "Erik",
          cto: "Alex"
      }
  };

  // Extend Underscore.js
  _.mixin({ 
      // Safe navigation
      attr: function(obj, name) { return obj == null ? obj : obj[name]; },
      // So we can chain console.log
      log: function(obj) { console.log(obj); }
  });

  // Shortcut, 'cause I'm lazy
  var C = _(companies).chain();

  // Simple case: returns Erik
  C.attr("orbeon").attr("cfo").log();
  // Simple case too, no CEO in Orbeon, returns undefined
  C.attr("orbeon").attr("ceo").log();
  // IBM unknown, but doesn't lead to an error, returns undefined
  C.attr("ibm").attr("ceo").log();