Programs & Examples On #Workflow activity

iPhone/iOS JSON parsing tutorial

You will love this framework.

And you will love this tool.

For learning about JSON you might like this resource.

And you'll probably love this tutorial.

Set width to match constraints in ConstraintLayout

I found one more answer when there is a constraint layout inside the scroll view then we need to put

android:fillViewport="true"

to the scroll view

and

android:layout_height="0dp"

in the constraint layout

Example:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

    <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="0dp">

// Rest of the views

</androidx.constraintlayout.widget.ConstraintLayout>

</ScrollView>

SQL Server: Best way to concatenate multiple columns?

If the fields are nullable, then you'll have to handle those nulls. Remember that null is contagious, and concat('foo', null) simply results in NULL as well:

SELECT CONCAT(ISNULL(column1, ''),ISNULL(column2,'')) etc...

Basically test each field for nullness, and replace with an empty string if so.

Getting the 'external' IP address in Java

If you are using JAVA based webapp and if you want to grab the client's (One who makes the request via a browser) external ip try deploying the app in a public domain and use request.getRemoteAddr() to read the external IP address.

Angular 2 TypeScript how to find element in Array

You could combine .find with arrow functions and destructuring. Take this example from MDN.

const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

const result = inventory.find( ({ name }) => name === 'cherries' );

console.log(result) // { name: 'cherries', quantity: 5 }

why should I make a copy of a data frame in pandas

The primary purpose is to avoid chained indexing and eliminate the SettingWithCopyWarning.

Here chained indexing is something like dfc['A'][0] = 111

The document said chained indexing should be avoided in Returning a view versus a copy. Here is a slightly modified example from that document:

In [1]: import pandas as pd

In [2]: dfc = pd.DataFrame({'A':['aaa','bbb','ccc'],'B':[1,2,3]})

In [3]: dfc
Out[3]:
    A   B
0   aaa 1
1   bbb 2
2   ccc 3

In [4]: aColumn = dfc['A']

In [5]: aColumn[0] = 111
SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

In [6]: dfc
Out[6]:
    A   B
0   111 1
1   bbb 2
2   ccc 3

Here the aColumn is a view and not a copy from the original DataFrame, so modifying aColumn will cause the original dfc be modified too. Next, if we index the row first:

In [7]: zero_row = dfc.loc[0]

In [8]: zero_row['A'] = 222
SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

In [9]: dfc
Out[9]:
    A   B
0   111 1
1   bbb 2
2   ccc 3

This time zero_row is a copy, so the original dfc is not modified.

From these two examples above, we see it's ambiguous whether or not you want to change the original DataFrame. This is especially dangerous if you write something like the following:

In [10]: dfc.loc[0]['A'] = 333
SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

In [11]: dfc
Out[11]:
    A   B
0   111 1
1   bbb 2
2   ccc 3

This time it didn't work at all. Here we wanted to change dfc, but we actually modified an intermediate value dfc.loc[0] that is a copy and is discarded immediately. It’s very hard to predict whether the intermediate value like dfc.loc[0] or dfc['A'] is a view or a copy, so it's not guaranteed whether or not original DataFrame will be updated. That's why chained indexing should be avoided, and pandas generates the SettingWithCopyWarning for this kind of chained indexing update.

Now is the use of .copy(). To eliminate the warning, make a copy to express your intention explicitly:

In [12]: zero_row_copy = dfc.loc[0].copy()

In [13]: zero_row_copy['A'] = 444 # This time no warning

Since you are modifying a copy, you know the original dfc will never change and you are not expecting it to change. Your expectation matches the behavior, then the SettingWithCopyWarning disappears.

Note, If you do want to modify the original DataFrame, the document suggests you use loc:

In [14]: dfc.loc[0,'A'] = 555

In [15]: dfc
Out[15]:
    A   B
0   555 1
1   bbb 2
2   ccc 3

Webpack not excluding node_modules

If you ran into this issue when using TypeScript, you may need to add skipLibCheck: true in your tsconfig.json file.

jQuery animated number counter from zero to value

This is work for me !

<script type="text/javascript">
$(document).ready(function(){
        countnumber(0,40,"stat1",50);
        function countnumber(start,end,idtarget,duration){
            cc=setInterval(function(){
                if(start==end)
                {
                    $("#"+idtarget).html(start);
                    clearInterval(cc);
                }
                else
                {
                   $("#"+idtarget).html(start);
                   start++;
                }
            },duration);
        }
    });
</script>
<span id="span1"></span>

Validating file types by regular expression

Your regex seems a bit too complex in my opinion. Also, remember that the dot is a special character meaning "any character". The following regex should work (note the escaped dots):

^.*\.(jpg|JPG|gif|GIF|doc|DOC|pdf|PDF)$

You can use a tool like Expresso to test your regular expressions.

Route [login] not defined

You're trying to redirect to a named route whose name is login, but you have no routes with that name:

Route::post('login', [ 'as' => 'login', 'uses' => 'LoginController@do']);

The 'as' portion of the second parameter defines the name of the route. The first string parameter defines its route.

How to use `@ts-ignore` for a block

You can't.

As a workaround you can use a // @ts-nocheck comment at the top of a file to disable type-checking for that file: https://devblogs.microsoft.com/typescript/announcing-typescript-3-7-beta/

So to disable checking for a block (function, class, etc.), you can move it into its own file, then use the comment/flag above. (This isn't as flexible as block-based disabling of course, but it's the best option available at the moment.)

HTML iframe - disable scroll

For this frame:

    <iframe src="" name="" id=""></iframe>

I tried this on my css code:

    iframe#put the value of id here::-webkit-scrollbar {
         display: none;
    }

Ruby replace string with captured regex pattern

If you need to use a regex to filter some results, and THEN use only the capture group, you can do the following:

str = "Leesburg, Virginia  20176"
state_regex = Regexp.new(/,\s*([A-Za-z]{2,})\s*\d{5,}/)
# looks for the comma, possible whitespace, captures alpha,
# looks for possible whitespace, looks for zip

> str[state_regex]
=> ", Virginia  20176"

> str[state_regex, 1] # use the capture group
=> "Virginia"

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

How to filter data in dataview

DataView view = new DataView();
view.Table = DataSet1.Tables["Suppliers"];
view.RowFilter = "City = 'Berlin'";
view.RowStateFilter = DataViewRowState.ModifiedCurrent;
view.Sort = "CompanyName DESC";

// Simple-bind to a TextBox control
Text1.DataBindings.Add("Text", view, "CompanyName");

Ref: http://www.csharp-examples.net/dataview-rowfilter/

http://msdn.microsoft.com/en-us/library/system.data.dataview.rowfilter.aspx

How to change the CHARACTER SET (and COLLATION) throughout a database?

Heres how to change all databases/tables/columns. Run these queries and they will output all of the subsequent queries necessary to convert your entire schema to utf8. Hope this helps!

-- Change DATABASE Default Collation

SELECT DISTINCT concat('ALTER DATABASE `', TABLE_SCHEMA, '` CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.tables
where TABLE_SCHEMA like  'database_name';

-- Change TABLE Collation / Char Set

SELECT concat('ALTER TABLE `', TABLE_SCHEMA, '`.`', table_name, '` CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.tables
where TABLE_SCHEMA like 'database_name';

-- Change COLUMN Collation / Char Set

SELECT concat('ALTER TABLE `', t1.TABLE_SCHEMA, '`.`', t1.table_name, '` MODIFY `', t1.column_name, '` ', t1.data_type , '(' , t1.CHARACTER_MAXIMUM_LENGTH , ')' , ' CHARACTER SET utf8 COLLATE utf8_unicode_ci;')
from information_schema.columns t1
where t1.TABLE_SCHEMA like 'database_name' and t1.COLLATION_NAME = 'old_charset_name';

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

parent() method returns the direct parent element of the selected one. This method only traverse a single level up the DOM tree.

parents() method allows us to search through the ancestors of these elements in the DOM tree. Begin from given selector and move up.

The **.parents()** and **.parent()** methods are almost similar, except that the latter only travels a single level up the DOM tree. Also, **$( "html" ).parent()** method returns a set containing document whereas **$( "html" ).parents()** returns an empty set.

[closest()][3]method returns the first ancestor of the selected element.An ancestor is a parent, grandparent, great-grandparent, and so on.

This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.

According to docs:

**closest()** method is similar to **parents()**, in that they both traverse up the DOM tree. The differences are as follows:

**closest()**

Begins with the current element
Travels up the DOM tree and returns the first (single) ancestor that matches the passed expression
The returned jQuery object contains zero or one element

**parents()**

Begins with the parent element
Travels up the DOM tree and returns all ancestors that matches the passed expression
The returned jQuery object contains zero or more than one element





 

Select info from table where row has max date

SELECT group,MAX(date) as max_date
FROM table
WHERE checks>0
GROUP BY group

That works to get the max date..join it back to your data to get the other columns:

Select group,max_date,checks
from table t
inner join 
(SELECT group,MAX(date) as max_date
FROM table
WHERE checks>0
GROUP BY group)a
on a.group = t.group and a.max_date = date

Inner join functions as the filter to get the max record only.

FYI, your column names are horrid, don't use reserved words for columns (group, date, table).

How to read a list of files from a folder using PHP?

This is what I like to do:

$files = array_values(array_filter(scandir($path), function($file) use ($path) { 
    return !is_dir($path . '/' . $file);
}));

foreach($files as $file){
    echo $file;
}

Convert one date format into another in PHP

You need to convert the $old_date back into a timestamp, as the date function requires a timestamp as its second argument.

Docker official registry (Docker Hub) URL

It's just docker pull busybox, are you using an up to date version of the docker client. I think they stopped supporting clients lower than 1.5.

Incidentally that curl works for me:

$ curl -k https://registry.hub.docker.com/v1/repositories/busybox/tags
[{"layer": "fc0db02f", "name": "latest"}, {"layer": "fc0db02f", "name": "1"}, {"layer": "a6dbc8d6", "name": "1-ubuntu"}, {"layer": "a6dbc8d6", "name": "1.21-ubuntu"}, {"layer": "a6dbc8d6", "name": "1.21.0-ubuntu"}, {"layer": "d7057cb0", "name": "1.23"}, {"layer": "d7057cb0", "name": "1.23.2"}, {"layer": "fc0db02f", "name": "1.24"}, {"layer": "3d5bcd78", "name": "1.24.0"}, {"layer": "fc0db02f", "name": "1.24.1"}, {"layer": "1c677c87", "name": "buildroot-2013.08.1"}, {"layer": "0f864637", "name": "buildroot-2014.02"}, {"layer": "a6dbc8d6", "name": "ubuntu"}, {"layer": "ff8f955d", "name": "ubuntu-12.04"}, {"layer": "633fcd11", "name": "ubuntu-14.04"}]

Interesting enough if you sniff the headers you get a HTTP 405 (Method not allowed). I think this might be to do with the fact that Docker have deprecated their Registry API.

How do I get the current date in Cocoa

You have problems with iOS 4.2? Use this Code:

NSDate *currDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"dd.MM.YY HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:currDate];
NSLog(@"%@",dateString);

-->20.01.2011 10:36:02

Is it possible to use the SELECT INTO clause with UNION [ALL]?

SELECT * INTO tmpFerdeen FROM 
(SELECT top(100)*  
FROM Customers 
UNION All 
SELECT top(100)*  
FROM CustomerEurope 
UNION All 
SELECT top(100)*  
FROM CustomerAsia 
UNION All 
SELECT top(100)*  
FROM CustomerAmericas) AS Blablabal

This "Blablabal" is necessary

Angular ng-if not true

use this

ng-if="area == false"

OR

ng-if="area == true"

this may help someone

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

Run Java with the command-line option -Xmx, which sets the maximum size of the heap.

See here for details.

Making a Windows shortcut start relative to where the folder is?

You could have the batch file change the current working directory (CD).

React - How to pass HTML tags in props?

You can use mixed arrays with strings and JSX elements (see the docs here):

<MyComponent text={["This is ", <strong>not</strong>,  "working."]} />

There's a fiddle here that shows it working: http://jsfiddle.net/7s7dee6L/

Also, as a last resort, you always have the ability to insert raw HTML but be careful because that can open you up to a cross-site scripting (XSS) attack if aren't sanitizing the property values.

How to compare only date components from DateTime in EF?

Just always compare the Date property of DateTime, instead of the full date time.

When you make your LINQ query, use date.Date in the query, ie:

var results = from c in collection
              where c.Date == myDateTime.Date
              select c;

#define macro for debug printing in C?

If you use a C99 or later compiler

#define debug_print(fmt, ...) \
            do { if (DEBUG) fprintf(stderr, fmt, __VA_ARGS__); } while (0)

It assumes you are using C99 (the variable argument list notation is not supported in earlier versions). The do { ... } while (0) idiom ensures that the code acts like a statement (function call). The unconditional use of the code ensures that the compiler always checks that your debug code is valid — but the optimizer will remove the code when DEBUG is 0.

If you want to work with #ifdef DEBUG, then change the test condition:

#ifdef DEBUG
#define DEBUG_TEST 1
#else
#define DEBUG_TEST 0
#endif

And then use DEBUG_TEST where I used DEBUG.

If you insist on a string literal for the format string (probably a good idea anyway), you can also introduce things like __FILE__, __LINE__ and __func__ into the output, which can improve the diagnostics:

#define debug_print(fmt, ...) \
        do { if (DEBUG) fprintf(stderr, "%s:%d:%s(): " fmt, __FILE__, \
                                __LINE__, __func__, __VA_ARGS__); } while (0)

This relies on string concatenation to create a bigger format string than the programmer writes.

If you use a C89 compiler

If you are stuck with C89 and no useful compiler extension, then there isn't a particularly clean way to handle it. The technique I used to use was:

#define TRACE(x) do { if (DEBUG) dbg_printf x; } while (0)

And then, in the code, write:

TRACE(("message %d\n", var));

The double-parentheses are crucial — and are why you have the funny notation in the macro expansion. As before, the compiler always checks the code for syntactic validity (which is good) but the optimizer only invokes the printing function if the DEBUG macro evaluates to non-zero.

This does require a support function — dbg_printf() in the example — to handle things like 'stderr'. It requires you to know how to write varargs functions, but that isn't hard:

#include <stdarg.h>
#include <stdio.h>

void dbg_printf(const char *fmt, ...)
{
    va_list args;
    va_start(args, fmt);
    vfprintf(stderr, fmt, args);
    va_end(args);
}

You can also use this technique in C99, of course, but the __VA_ARGS__ technique is neater because it uses regular function notation, not the double-parentheses hack.

Why is it crucial that the compiler always see the debug code?

[Rehashing comments made to another answer.]

One central idea behind both the C99 and C89 implementations above is that the compiler proper always sees the debugging printf-like statements. This is important for long-term code — code that will last a decade or two.

Suppose a piece of code has been mostly dormant (stable) for a number of years, but now needs to be changed. You re-enable debugging trace - but it is frustrating to have to debug the debugging (tracing) code because it refers to variables that have been renamed or retyped, during the years of stable maintenance. If the compiler (post pre-processor) always sees the print statement, it ensures that any surrounding changes have not invalidated the diagnostics. If the compiler does not see the print statement, it cannot protect you against your own carelessness (or the carelessness of your colleagues or collaborators). See 'The Practice of Programming' by Kernighan and Pike, especially Chapter 8 (see also Wikipedia on TPOP).

This is 'been there, done that' experience — I used essentially the technique described in other answers where the non-debug build does not see the printf-like statements for a number of years (more than a decade). But I came across the advice in TPOP (see my previous comment), and then did enable some debugging code after a number of years, and ran into problems of changed context breaking the debugging. Several times, having the printing always validated has saved me from later problems.

I use NDEBUG to control assertions only, and a separate macro (usually DEBUG) to control whether debug tracing is built into the program. Even when the debug tracing is built in, I frequently do not want debug output to appear unconditionally, so I have mechanism to control whether the output appears (debug levels, and instead of calling fprintf() directly, I call a debug print function that only conditionally prints so the same build of the code can print or not print based on program options). I also have a 'multiple-subsystem' version of the code for bigger programs, so that I can have different sections of the program producing different amounts of trace - under runtime control.

I am advocating that for all builds, the compiler should see the diagnostic statements; however, the compiler won't generate any code for the debugging trace statements unless debug is enabled. Basically, it means that all of your code is checked by the compiler every time you compile - whether for release or debugging. This is a good thing!

debug.h - version 1.2 (1990-05-01)

/*
@(#)File:            $RCSfile: debug.h,v $
@(#)Version:         $Revision: 1.2 $
@(#)Last changed:    $Date: 1990/05/01 12:55:39 $
@(#)Purpose:         Definitions for the debugging system
@(#)Author:          J Leffler
*/

#ifndef DEBUG_H
#define DEBUG_H

/* -- Macro Definitions */

#ifdef DEBUG
#define TRACE(x)    db_print x
#else
#define TRACE(x)
#endif /* DEBUG */

/* -- Declarations */

#ifdef DEBUG
extern  int     debug;
#endif

#endif  /* DEBUG_H */

debug.h - version 3.6 (2008-02-11)

/*
@(#)File:           $RCSfile: debug.h,v $
@(#)Version:        $Revision: 3.6 $
@(#)Last changed:   $Date: 2008/02/11 06:46:37 $
@(#)Purpose:        Definitions for the debugging system
@(#)Author:         J Leffler
@(#)Copyright:      (C) JLSS 1990-93,1997-99,2003,2005,2008
@(#)Product:        :PRODUCT:
*/

#ifndef DEBUG_H
#define DEBUG_H

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */

/*
** Usage:  TRACE((level, fmt, ...))
** "level" is the debugging level which must be operational for the output
** to appear. "fmt" is a printf format string. "..." is whatever extra
** arguments fmt requires (possibly nothing).
** The non-debug macro means that the code is validated but never called.
** -- See chapter 8 of 'The Practice of Programming', by Kernighan and Pike.
*/
#ifdef DEBUG
#define TRACE(x)    db_print x
#else
#define TRACE(x)    do { if (0) db_print x; } while (0)
#endif /* DEBUG */

#ifndef lint
#ifdef DEBUG
/* This string can't be made extern - multiple definition in general */
static const char jlss_id_debug_enabled[] = "@(#)*** DEBUG ***";
#endif /* DEBUG */
#ifdef MAIN_PROGRAM
const char jlss_id_debug_h[] = "@(#)$Id: debug.h,v 3.6 2008/02/11 06:46:37 jleffler Exp $";
#endif /* MAIN_PROGRAM */
#endif /* lint */

#include <stdio.h>

extern int      db_getdebug(void);
extern int      db_newindent(void);
extern int      db_oldindent(void);
extern int      db_setdebug(int level);
extern int      db_setindent(int i);
extern void     db_print(int level, const char *fmt,...);
extern void     db_setfilename(const char *fn);
extern void     db_setfileptr(FILE *fp);
extern FILE    *db_getfileptr(void);

/* Semi-private function */
extern const char *db_indent(void);

/**************************************\
** MULTIPLE DEBUGGING SUBSYSTEMS CODE **
\**************************************/

/*
** Usage:  MDTRACE((subsys, level, fmt, ...))
** "subsys" is the debugging system to which this statement belongs.
** The significance of the subsystems is determined by the programmer,
** except that the functions such as db_print refer to subsystem 0.
** "level" is the debugging level which must be operational for the
** output to appear. "fmt" is a printf format string. "..." is
** whatever extra arguments fmt requires (possibly nothing).
** The non-debug macro means that the code is validated but never called.
*/
#ifdef DEBUG
#define MDTRACE(x)  db_mdprint x
#else
#define MDTRACE(x)  do { if (0) db_mdprint x; } while (0)
#endif /* DEBUG */

extern int      db_mdgetdebug(int subsys);
extern int      db_mdparsearg(char *arg);
extern int      db_mdsetdebug(int subsys, int level);
extern void     db_mdprint(int subsys, int level, const char *fmt,...);
extern void     db_mdsubsysnames(char const * const *names);

#endif /* DEBUG_H */

Single argument variant for C99 or later

Kyle Brandt asked:

Anyway to do this so debug_print still works even if there are no arguments? For example:

    debug_print("Foo");

There's one simple, old-fashioned hack:

debug_print("%s\n", "Foo");

The GCC-only solution shown below also provides support for that.

However, you can do it with the straight C99 system by using:

#define debug_print(...) \
            do { if (DEBUG) fprintf(stderr, __VA_ARGS__); } while (0)

Compared to the first version, you lose the limited checking that requires the 'fmt' argument, which means that someone could try to call 'debug_print()' with no arguments (but the trailing comma in the argument list to fprintf() would fail to compile). Whether the loss of checking is a problem at all is debatable.

GCC-specific technique for a single argument

Some compilers may offer extensions for other ways of handling variable-length argument lists in macros. Specifically, as first noted in the comments by Hugo Ideler, GCC allows you to omit the comma that would normally appear after the last 'fixed' argument to the macro. It also allows you to use ##__VA_ARGS__ in the macro replacement text, which deletes the comma preceding the notation if, but only if, the previous token is a comma:

#define debug_print(fmt, ...) \
            do { if (DEBUG) fprintf(stderr, fmt, ##__VA_ARGS__); } while (0)

This solution retains the benefit of requiring the format argument while accepting optional arguments after the format.

This technique is also supported by Clang for GCC compatibility.


Why the do-while loop?

What's the purpose of the do while here?

You want to be able to use the macro so it looks like a function call, which means it will be followed by a semi-colon. Therefore, you have to package the macro body to suit. If you use an if statement without the surrounding do { ... } while (0), you will have:

/* BAD - BAD - BAD */
#define debug_print(...) \
            if (DEBUG) fprintf(stderr, __VA_ARGS__)

Now, suppose you write:

if (x > y)
    debug_print("x (%d) > y (%d)\n", x, y);
else
    do_something_useful(x, y);

Unfortunately, that indentation doesn't reflect the actual control of flow, because the preprocessor produces code equivalent to this (indented and braces added to emphasize the actual meaning):

if (x > y)
{
    if (DEBUG)
        fprintf(stderr, "x (%d) > y (%d)\n", x, y);
    else
        do_something_useful(x, y);
}

The next attempt at the macro might be:

/* BAD - BAD - BAD */
#define debug_print(...) \
            if (DEBUG) { fprintf(stderr, __VA_ARGS__); }

And the same code fragment now produces:

if (x > y)
    if (DEBUG)
    {
        fprintf(stderr, "x (%d) > y (%d)\n", x, y);
    }
; // Null statement from semi-colon after macro
else
    do_something_useful(x, y);

And the else is now a syntax error. The do { ... } while(0) loop avoids both these problems.

There's one other way of writing the macro which might work:

/* BAD - BAD - BAD */
#define debug_print(...) \
            ((void)((DEBUG) ? fprintf(stderr, __VA_ARGS__) : 0))

This leaves the program fragment shown as valid. The (void) cast prevents it being used in contexts where a value is required — but it could be used as the left operand of a comma operator where the do { ... } while (0) version cannot. If you think you should be able to embed debug code into such expressions, you might prefer this. If you prefer to require the debug print to act as a full statement, then the do { ... } while (0) version is better. Note that if the body of the macro involved any semi-colons (roughly speaking), then you can only use the do { ... } while(0) notation. It always works; the expression statement mechanism can be more difficult to apply. You might also get warnings from the compiler with the expression form that you'd prefer to avoid; it will depend on the compiler and the flags you use.


TPOP was previously at http://plan9.bell-labs.com/cm/cs/tpop and http://cm.bell-labs.com/cm/cs/tpop but both are now (2015-08-10) broken.


Code in GitHub

If you're curious, you can look at this code in GitHub in my SOQ (Stack Overflow Questions) repository as files debug.c, debug.h and mddebug.c in the src/libsoq sub-directory.

Set cURL to use local virtual hosts

Either use a real fully qualified domain name (like dev.yourdomain.com) that pointing to 127.0.0.1 or try editing the proper hosts file (usually /etc/hosts in *nix environments).

How to get the text of the selected value of a dropdown list?

You can use option:selected to get the chosen option of the select element, then the text() method:

$("select option:selected").text();

Here's an example:

_x000D_
_x000D_
console.log($("select option:selected").text());
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<select>_x000D_
    <option value="1">Volvo</option>_x000D_
    <option value="2" selected="selected">Saab</option>_x000D_
    <option value="3">Mercedes</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How to select the last record from MySQL table using SQL syntax

SELECT   *
FROM     table
ORDER BY id DESC
LIMIT    0, 1

Virtualhost For Wildcard Subdomain and Static Subdomain

This also works for https needed a solution to making project directories this was it. because chrome doesn't like non ssl anymore used free ssl. Notice: My Web Server is Wamp64 on Windows 10 so I wouldn't use this config because of variables unless your using wamp.

<VirtualHost *:443>
ServerAdmin [email protected]
ServerName test.com
ServerAlias *.test.com

SSLEngine On
SSLCertificateFile "conf/key/certificatecom.crt"
SSLCertificateKeyFile "conf/key/privatecom.key"

VirtualDocumentRoot "${INSTALL_DIR}/www/subdomains/%1/"

DocumentRoot "${INSTALL_DIR}/www/subdomains"
<Directory "${INSTALL_DIR}/www/subdomains/">
    Options +Indexes +Includes +FollowSymLinks +MultiViews
AllowOverride All
Require all granted
</Directory>

How to uninstall Jenkins?

There is no uninstaller. Therefore, you need to:

  • Delete the directory containing Jenkins (or, if you're deploying the war -- remove the war from your container).

  • Remove ~/.jenkins.

  • Remove you startup scripts.

Is it possible to compile a program written in Python?

Python, as a dynamic language, cannot be "compiled" into machine code statically, like C or COBOL can. You'll always need an interpreter to execute the code, which, by definition in the language, is a dynamic operation.

You can "translate" source code in bytecode, which is just an intermediate process that the interpreter does to speed up the load of the code, It converts text files, with comments, blank spaces, words like 'if', 'def', 'in', etc in binary code, but the operations behind are exactly the same, in Python, not in machine code or any other language. This is what it's stored in .pyc files and it's also portable between architectures.

Probably what you need it's not "compile" the code (which it's not possible) but to "embed" an interpreter (in the right architecture) with the code to allow running the code without an external installation of the interpreter. To do that, you can use all those tools like py2exe or cx_Freeze.

Maybe I'm being a little pedantic on this :-P

Converting Pandas dataframe into Spark dataframe error

Type related errors can be avoided by imposing a schema as follows:

note: a text file was created (test.csv) with the original data (as above) and hypothetical column names were inserted ("col1","col2",...,"col25").

import pyspark
from pyspark.sql import SparkSession
import pandas as pd

spark = SparkSession.builder.appName('pandasToSparkDF').getOrCreate()

pdDF = pd.read_csv("test.csv")

contents of the pandas data frame:

       col1     col2    col3    col4    col5    col6    col7    col8   ... 
0      10000001 1       0       1       12:35   OK      10002   1      ...
1      10000001 2       0       1       12:36   OK      10002   1      ...
2      10000002 1       0       4       12:19   PA      10003   1      ...

Next, create the schema:

from pyspark.sql.types import *

mySchema = StructType([ StructField("col1", LongType(), True)\
                       ,StructField("col2", IntegerType(), True)\
                       ,StructField("col3", IntegerType(), True)\
                       ,StructField("col4", IntegerType(), True)\
                       ,StructField("col5", StringType(), True)\
                       ,StructField("col6", StringType(), True)\
                       ,StructField("col7", IntegerType(), True)\
                       ,StructField("col8", IntegerType(), True)\
                       ,StructField("col9", IntegerType(), True)\
                       ,StructField("col10", IntegerType(), True)\
                       ,StructField("col11", StringType(), True)\
                       ,StructField("col12", StringType(), True)\
                       ,StructField("col13", IntegerType(), True)\
                       ,StructField("col14", IntegerType(), True)\
                       ,StructField("col15", IntegerType(), True)\
                       ,StructField("col16", IntegerType(), True)\
                       ,StructField("col17", IntegerType(), True)\
                       ,StructField("col18", IntegerType(), True)\
                       ,StructField("col19", IntegerType(), True)\
                       ,StructField("col20", IntegerType(), True)\
                       ,StructField("col21", IntegerType(), True)\
                       ,StructField("col22", IntegerType(), True)\
                       ,StructField("col23", IntegerType(), True)\
                       ,StructField("col24", IntegerType(), True)\
                       ,StructField("col25", IntegerType(), True)])

Note: True (implies nullable allowed)

create the pyspark dataframe:

df = spark.createDataFrame(pdDF,schema=mySchema)

confirm the pandas data frame is now a pyspark data frame:

type(df)

output:

pyspark.sql.dataframe.DataFrame

Aside:

To address Kate's comment below - to impose a general (String) schema you can do the following:

df=spark.createDataFrame(pdDF.astype(str)) 

How to read a file byte by byte in Python and how to print a bytelist as a binary?

The code you've shown will read 8 bytes. You could use

with open(filename, 'rb') as f:
   while 1:
      byte_s = f.read(1)
      if not byte_s:
         break
      byte = byte_s[0]
      ...

Passing a callback function to another class

What you need is a delegate and a callback. Here is a nice MSDN article that will show you how to use this technique in C#.

Where can I set path to make.exe on Windows?

I had issues for a whilst not getting Terraform commands to run unless I was in the directory of the exe, even though I set the path correctly.

For anyone else finding this issue, I fixed it by moving the environment variable higher than others!

"ImportError: No module named" when trying to run Python script

Happened to me with the directory utils. I was trying to import this directory as:

from utils import somefile

utils is already a package in python. Just change your directory name to something different and it should work just fine.

Not equal to != and !== in PHP

!== should match the value and data type

!= just match the value ignoring the data type

$num = '1';
$num2 = 1;

$num == $num2; // returns true    
$num === $num2; // returns false because $num is a string and $num2 is an integer

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

Creating a site wrapper div inside the body and applying the overflow->x:hidden to the wrapper INSTEAD of the body or html fixed the issue.

This worked for me after also adding position: relative to the wrapper.

Remove HTML Tags from an NSString on the iPhone

I would imagine the safest way would just be to parse for <>s, no? Loop through the entire string, and copy anything not enclosed in <>s to a new string.

How to properly add include directories with CMake

CMake is more like a script language if comparing it with other ways to create Makefile (e.g. make or qmake). It is not very cool like Python, but still.

There are no such thing like a "proper way" if looking in various opensource projects how people include directories. But there are two ways to do it.

  1. Crude include_directories will append a directory to the current project and all other descendant projects which you will append via a series of add_subdirectory commands. Sometimes people say that such approach is legacy.

  2. A more elegant way is with target_include_directories. It allows to append a directory for a specific project/target without (maybe) unnecessary inheritance or clashing of various include directories. Also allow to perform even a subtle configuration and append one of the following markers for this command.

PRIVATE - use only for this specified build target

PUBLIC - use it for specified target and for targets which links with this project

INTERFACE -- use it only for targets which links with the current project

PS:

  1. Both commands allow to mark a directory as SYSTEM to give a hint that it is not your business that specified directories will contain warnings.

  2. A similar answer is with other pairs of commands target_compile_definitions/add_definitions, target_compile_options/CMAKE_C_FLAGS

How to add a ListView to a Column in Flutter?

Reason for the error:

Column expands to the maximum size in main axis direction (vertical axis), and so does the ListView.

Solutions

So, you need to constrain the height of the ListView. There are many ways of doing it, you can choose that best suits your need.


  1. If you want to allow ListView to take up all remaining space inside Column use Expanded.

    Column(
      children: <Widget>[
        Expanded(
          child: ListView(...),
        )
      ],
    )
    

  1. If you want to limit your ListView to certain height, you can use SizedBox.

    Column(
      children: <Widget>[
        SizedBox(
          height: 200, // constrain height
          child: ListView(),
        )
      ],
    )
    

  1. If your ListView is small, you may try shrinkWrap property on it.

    Column(
      children: <Widget>[
        ListView(
          shrinkWrap: true, // use it
        )
      ],
    )
    

Perform an action in every sub-directory using Bash

Handy one-liners

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

find * -type d ### Option B

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

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

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

How to make child divs always fit inside parent div?

you could use display: inline-block;

hope it is useful.

char initial value in Java

Typically for local variables I initialize them as late as I can. It's rare that I need a "dummy" value. However, if you do, you can use any value you like - it won't make any difference, if you're sure you're going to assign a value before reading it.

If you want the char equivalent of 0, it's just Unicode 0, which can be written as

char c = '\0';

That's also the default value for an instance (or static) variable of type char.

Why did I get the compile error "Use of unassigned local variable"?

The following categories of variables are classified as initially unassigned:

  • Instance variables of initially unassigned struct variables.
  • Output parameters, including the this variable of struct instance constructors.
  • Local variables , except those declared in a catch clause or a foreach statement.

The following categories of variables are classified as initially assigned:

  • Static variables.
  • Instance variables of class instances.
  • Instance variables of initially assigned struct variables.
  • Array elements.
  • Value parameters.
  • Reference parameters.
  • Variables declared in a catch clause or a foreach statement.

Objective-C Static Class Level variables

Issue Description:

  1. You want your ClassA to have a ClassB class variable.
  2. You are using Objective-C as programming language.
  3. Objective-C does not support class variables as C++ does.

One Alternative:

Simulate a class variable behavior using Objective-C features

  1. Declare/Define an static variable within the classA.m so it will be only accessible for the classA methods (and everything you put inside classA.m).

  2. Overwrite the NSObject initialize class method to initialize just once the static variable with an instance of ClassB.

  3. You will be wondering, why should I overwrite the NSObject initialize method. Apple documentation about this method has the answer: "The runtime sends initialize to each class in a program exactly one time just before the class, or any class that inherits from it, is sent its first message from within the program. (Thus the method may never be invoked if the class is not used.)".

  4. Feel free to use the static variable within any ClassA class/instance method.

Code sample:

file: classA.m

static ClassB *classVariableName = nil;

@implementation ClassA

...
 
+(void) initialize
{
    if (! classVariableName)
        classVariableName = [[ClassB alloc] init];
}

+(void) classMethodName
{
    [classVariableName doSomething]; 
}

-(void) instanceMethodName
{
    [classVariableName doSomething]; 
}

...

@end

References:

  1. Class variables explained comparing Objective-C and C++ approaches

How to remove any URL within a string in Python

I wasn't able to find any that handled my particular situation, which was removing urls in the middle of tweets that also have whitespaces in the middle of urls so I made my own:

(https?:\/\/)(\s)*(www\.)?(\s)*((\w|\s)+\.)*([\w\-\s]+\/)*([\w\-]+)((\?)?[\w\s]*=\s*[\w\%&]*)*

here's an explanation:
(https?:\/\/) matches http:// or https://
(\s)* optional whitespaces
(www\.)? optionally matches www.
(\s)* optionally matches whitespaces
((\w|\s)+\.)* matches 0 or more of one or more word characters followed by a period
([\w\-\s]+\/)* matches 0 or more of one or more words(or a dash or a space) followed by '\'
([\w\-]+) any remaining path at the end of the url followed by an optional ending
((\?)?[\w\s]*=\s*[\w\%&]*)* matches ending query params (even with white spaces,etc)

test this out here:https://regex101.com/r/NmVGOo/8

commandButton/commandLink/ajax action/listener method not invoked or input value not set/updated

Introduction

Whenever an UICommand component (<h:commandXxx>, <p:commandXxx>, etc) fails to invoke the associated action method, or an UIInput component (<h:inputXxx>, <p:inputXxxx>, etc) fails to process the submitted values and/or update the model values, and you aren't seeing any googlable exceptions and/or warnings in the server log, also not when you configure an ajax exception handler as per Exception handling in JSF ajax requests, nor when you set below context parameter in web.xml,

<context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
</context-param>

and you are also not seeing any googlable errors and/or warnings in browser's JavaScript console (press F12 in Chrome/Firefox23+/IE9+ to open the web developer toolset and then open the Console tab), then work through below list of possible causes.

Possible causes

  1. UICommand and UIInput components must be placed inside an UIForm component, e.g. <h:form> (and thus not plain HTML <form>), otherwise nothing can be sent to the server. UICommand components must also not have type="button" attribute, otherwise it will be a dead button which is only useful for JavaScript onclick. See also How to send form input values and invoke a method in JSF bean and <h:commandButton> does not initiate a postback.

  2. You cannot nest multiple UIForm components in each other. This is illegal in HTML. The browser behavior is unspecified. Watch out with include files! You can use UIForm components in parallel, but they won't process each other during submit. You should also watch out with "God Form" antipattern; make sure that you don't unintentionally process/validate all other (invisible) inputs in the very same form (e.g. having a hidden dialog with required inputs in the very same form). See also How to use <h:form> in JSF page? Single form? Multiple forms? Nested forms?.

  3. No UIInput value validation/conversion error should have occurred. You can use <h:messages> to show any messages which are not shown by any input-specific <h:message> components. Don't forget to include the id of <h:messages> in the <f:ajax render>, if any, so that it will be updated as well on ajax requests. See also h:messages does not display messages when p:commandButton is pressed.

  4. If UICommand or UIInput components are placed inside an iterating component like <h:dataTable>, <ui:repeat>, etc, then you need to ensure that exactly the same value of the iterating component is been preserved during the apply request values phase of the form submit request. JSF will reiterate over it to find the clicked link/button and submitted input values. Putting the bean in the view scope and/or making sure that you load the data model in @PostConstruct of the bean (and thus not in a getter method!) should fix it. See also How and when should I load the model from database for h:dataTable.

  5. If UICommand or UIInput components are included by a dynamic source such as <ui:include src="#{bean.include}">, then you need to ensure that exactly the same #{bean.include} value is preserved during the view build time of the form submit request. JSF will reexecute it during building the component tree. Putting the bean in the view scope and/or making sure that you load the data model in @PostConstruct of the bean (and thus not in a getter method!) should fix it. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).

  6. The rendered attribute of the component and all of its parents and the test attribute of any parent <c:if>/<c:when> should not evaluate to false during the apply request values phase of the form submit request. JSF will recheck it as part of safeguard against tampered/hacked requests. Storing the variables responsible for the condition in a @ViewScoped bean or making sure that you're properly preinitializing the condition in @PostConstruct of a @RequestScoped bean should fix it. The same applies to the disabled and readonly attributes of the component, which should not evaluate to true during apply request values phase. See also JSF CommandButton action not invoked, Form submit in conditionally rendered component is not processed, h:commandButton is not working once I wrap it in a <h:panelGroup rendered> and Force JSF to process, validate and update readonly/disabled input components anyway

  7. The onclick attribute of the UICommand component and the onsubmit attribute of the UIForm component should not return false or cause a JavaScript error. There should in case of <h:commandLink> or <f:ajax> also be no JS errors visible in the browser's JS console. Usually googling the exact error message will already give you the answer. See also Manually adding / loading jQuery with PrimeFaces results in Uncaught TypeErrors.

  8. If you're using Ajax via JSF 2.x <f:ajax> or e.g. PrimeFaces <p:commandXxx>, make sure that you have a <h:head> in the master template instead of the <head>. Otherwise JSF won't be able to auto-include the necessary JavaScript files which contains the Ajax functions. This would result in a JavaScript error like "mojarra is not defined" or "PrimeFaces is not defined" in browser's JS console. See also h:commandLink actionlistener is not invoked when used with f:ajax and ui:repeat.

  9. If you're using Ajax, and the submitted values end up being null, then make sure that the UIInput and UICommand components of interest are covered by the <f:ajax execute> or e.g. <p:commandXxx process>, otherwise they won't be executed/processed. See also Submitted form values not updated in model when adding <f:ajax> to <h:commandButton> and Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes.

  10. If the submitted values still end up being null, and you're using CDI to manage beans, then make sure that you import the scope annotation from the correct package, else CDI will default to @Dependent which effectively recreates the bean on every single evaluation of the EL expression. See also @SessionScoped bean looses scope and gets recreated all the time, fields become null and What is the default Managed Bean Scope in a JSF 2 application?

  11. If a parent of the <h:form> with the UICommand button is beforehand been rendered/updated by an ajax request coming from another form in the same page, then the first action will always fail in JSF 2.2 or older. The second and subsequent actions will work. This is caused by a bug in view state handling which is reported as JSF spec issue 790 and currently fixed in JSF 2.3. For older JSF versions, you need to explicitly specify the ID of the <h:form> in the render of the <f:ajax>. See also h:commandButton/h:commandLink does not work on first click, works only on second click.

  12. If the <h:form> has enctype="multipart/form-data" set in order to support file uploading, then you need to make sure that you're using at least JSF 2.2, or that the servlet filter who is responsible for parsing multipart/form-data requests is properly configured, otherwise the FacesServlet will end up getting no request parameters at all and thus not be able to apply the request values. How to configure such a filter depends on the file upload component being used. For Tomahawk <t:inputFileUpload>, check this answer and for PrimeFaces <p:fileUpload>, check this answer. Or, if you're actually not uploading a file at all, then remove the attribute altogether.

  13. Make sure that the ActionEvent argument of actionListener is an javax.faces.event.ActionEvent and thus not java.awt.event.ActionEvent, which is what most IDEs suggest as 1st autocomplete option. Having no argument is wrong as well if you use actionListener="#{bean.method}". If you don't want an argument in your method, use actionListener="#{bean.method()}". Or perhaps you actually want to use action instead of actionListener. See also Differences between action and actionListener.

  14. Make sure that no PhaseListener or any EventListener in the request-response chain has changed the JSF lifecycle to skip the invoke action phase by for example calling FacesContext#renderResponse() or FacesContext#responseComplete().

  15. Make sure that no Filter or Servlet in the same request-response chain has blocked the request fo the FacesServlet somehow. For example, login/security filters such as Spring Security. Particularly in ajax requests that would by default end up with no UI feedback at all. See also Spring Security 4 and PrimeFaces 5 AJAX request handling.

  16. If you are using a PrimeFaces <p:dialog> or a <p:overlayPanel>, then make sure that they have their own <h:form>. Because, these components are by default by JavaScript relocated to end of HTML <body>. So, if they were originally sitting inside a <form>, then they would now not anymore sit in a <form>. See also p:commandbutton action doesn't work inside p:dialog

  17. Bug in the framework. For example, RichFaces has a "conversion error" when using a rich:calendar UI element with a defaultLabel attribute (or, in some cases, a rich:placeholder sub-element). This bug prevents the bean method from being invoked when no value is set for the calendar date. Tracing framework bugs can be accomplished by starting with a simple working example and building the page back up until the bug is discovered.

Debugging hints

In case you still stucks, it's time to debug. In the client side, press F12 in webbrowser to open the web developer toolset. Click the Console tab so see the JavaScript conosle. It should be free of any JavaScript errors. Below screenshot is an example from Chrome which demonstrates the case of submitting an <f:ajax> enabled button while not having <h:head> declared (as described in point 7 above).

js console

Click the Network tab to see the HTTP traffic monitor. Submit the form and investigate if the request headers and form data and the response body are as per expectations. Below screenshot is an example from Chrome which demonstrates a successful ajax submit of a simple form with a single <h:inputText> and a single <h:commandButton> with <f:ajax execute="@form" render="@form">.

network monitor

(warning: when you post screenshots from HTTP request headers like above from a production environment, then make sure you scramble/obfuscate any session cookies in the screenshot to avoid session hijacking attacks!)

In the server side, make sure that server is started in debug mode. Put a debug breakpoint in a method of the JSF component of interest which you expect to be called during processing the form submit. E.g. in case of UICommand component, that would be UICommand#queueEvent() and in case of UIInput component, that would be UIInput#validate(). Just step through the code execution and inspect if the flow and variables are as per expectations. Below screenshot is an example from Eclipse's debugger.

debug server

Postgresql -bash: psql: command not found

It can be due to psql not being in PATH

$ locate psql
/usr/lib/postgresql/9.6/bin/psql

Then create a link in /usr/bin

ln -s /usr/lib/postgresql/9.6/bin/psql /usr/bin/psql

Then try to execute psql it should work.

How to remove non-alphanumeric characters?

Sounds like you almost knew what you wanted to do already, you basically defined it as a regex.

preg_replace("/[^A-Za-z0-9 ]/", '', $string);

How to get ERD diagram for an existing database?

  1. Open MySQL Workbench. In the home screen click 'Create EER Model From Existing Database'. We are doing this for the case that we have already made the data base and now we want to make an ER diagram of that database.

  2. Then you will see the 'Reverse Engineer Database' dialouge. Here if you are asked for the password, provided the admin password. Do not get confused here with the windows password. Here you need to provide the MySQL admin password. Then click on Next.

  3. In the next dialouge box, you'll see that the connection to DBMS is started and schema is revrieved from Database. Go next.

  4. Now Select the Schema you created earlier. It is the table you want to create the ER diagram of.

  5. Click Next and go to Select Objects menu. Here you can click on 'Show Filter' to use the selected Table Objects in the diagram. You can both add and remove tables here.Then click on Execute.

6.When you go Next and Finish, the required ER diagram is on the screen.

Can I get all methods of a class?

public static Method[] getAccessibleMethods(Class clazz) {
    List<Method> result = new ArrayList<Method>();
    while (clazz != null) {
        for (Method method : clazz.getDeclaredMethods()) {
            int modifiers = method.getModifiers();
            if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
                result.add(method);
            }
        }
        clazz = clazz.getSuperclass();
    }
    return result.toArray(new Method[result.size()]);
}

Error: Selection does not contain a main type

I ran into the same issue and found that there was an extra pair of braces (curly brackets) enclosing public static void main(String args) { ... }. This method should really be at the top scope in the class and should not be enclosed around braces. It seems that it is possible to end up with braces around this method when working in Eclipse. This could be just one way you can see this issue when working with Eclipse. Happy coding!

how to get all markers on google-maps-v3

If you are using JQuery Google map plug-in then below code will work for you -

var markers = $('#map_canvas').gmap('get','markers');

HowTo Generate List of SQL Server Jobs and their owners

A colleague told me about this stored procedure...

USE msdb

EXEC dbo.sp_help_job

How do I get Month and Date of JavaScript in 2 digit format?

Tip from MDN :

function date_locale(thisDate, locale) {
  if (locale == undefined)
    locale = 'fr-FR';
  // set your default country above (yes, I'm french !)
  // then the default format is "dd/mm/YYY"

  if (thisDate == undefined) {
    var d = new Date();
  } else {
    var d = new Date(thisDate);
  }
  return d.toLocaleDateString(locale);
}

var thisDate = date_locale();
var dayN = thisDate.slice(0, 2);
var monthN = thisDate.slice(3, 5);
console.log(dayN);
console.log(monthN);

http://jsfiddle.net/v4qcf5x6/

change type of input field with jQuery

I've created a jQuery extension to toggle between text and password. Works in IE8 (probably 6&7 as well, but not tested) and won't lose your value or attributes:

$.fn.togglePassword = function (showPass) {
    return this.each(function () {
        var $this = $(this);
        if ($this.attr('type') == 'text' || $this.attr('type') == 'password') {
            var clone = null;
            if((showPass == null && ($this.attr('type') == 'text')) || (showPass != null && !showPass)) {
                clone = $('<input type="password" />');
            }else if((showPass == null && ($this.attr('type') == 'password')) || (showPass != null && showPass)){
                clone = $('<input type="text" />');
            }
            $.each($this.prop("attributes"), function() {
                if(this.name != 'type') {
                    clone.attr(this.name, this.value);
                }
            });
            clone.val($this.val());
            $this.replaceWith(clone);
        }
    });
};

Works like a charm. You can simply call $('#element').togglePassword(); to switch between the two or give an option to 'force' the action based on something else (like a checkbox): $('#element').togglePassword($checkbox.prop('checked'));

Different names of JSON property during serialization and deserialization

I would bind two different getters/setters pair to one variable:

class Coordinates{
    int red;

    @JsonProperty("red")
    public byte getRed() {
      return red;
    }

    public void setRed(byte red) {
      this.red = red;
    }

    @JsonProperty("r")
    public byte getR() {
      return red;
    }

    public void setR(byte red) {
      this.red = red;
    }
}

The endpoint reference (EPR) for the Operation not found is

It happens because the source WSDL in each operation has not defined the SOAPAction value.

e.g.

<soap12:operation soapAction="" style="document"/>  

His is important for axis server.

If you have created the service on netbeans or another, don't forget to set the value action on the tag @WebMethod

e.g. @WebMethod(action = "hello", operationName = "hello")

This will create the SOAPAction value by itself.

Match the path of a URL, minus the filename extension

Like this:

if (preg_match('/(?<=net).*(?=\.php)/', $subject, $regs)) {
    $result = $regs[0];
}

Explanation:

"
(?<=      # Assert that the regex below can be matched, with the match ending at this position (positive lookbehind)
   net       # Match the characters “net” literally
)
.         # Match any single character that is not a line break character
   *         # Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
(?=       # Assert that the regex below can be matched, starting at this position (positive lookahead)
   \.        # Match the character “.” literally
   php       # Match the characters “php” literally
)
"

How to see local history changes in Visual Studio Code?

I built an extension called Checkpoints, an alternative to Local History. Checkpoints has support for viewing history for all files (that has checkpoints) in the tree view, not just the currently active file. There are some other minor differences aswell, but overall they are pretty similar.

How to add an Android Studio project to GitHub

  1. Sign up and create a GitHub account in www.github.com.
  2. Download git from https://git-scm.com/downloads and install it in your system.
  3. Open the project in android studio and go to File -> Settings -> Version Control -> Git.
  4. Click on test button to test "path to Git executables". If successful message is shown everything is ok, else navigate to git.exe from where you installed git and test again.
  5. Go to File -> Settings -> Version Control -> GitHub. Enter your email and password used to create GitHub account and click on OK button.
  6. Then go to VCS -> Import into Version Control -> Share Project on GitHub. Enter Repository name, Description and click Share button.
  7. In the next window check all files inorder to add files for initial commit and click OK.
  8. Now the project will be uploaded to the GitHub repository and when uploading is finished we will get a message in android studio showing "Successfully shared project on GitHub". Click on the link provided in that message to go to GitHub repository.

Unable to capture screenshot. Prevented by security policy. Galaxy S6. Android 6.0

You must have either disabled, froze or uninstalled FaceProvider in settings>applications>all
This will only happen if it's frozen, either uninstall it, or enable it.

Redis: How to access Redis log file

Found it with:

sudo tail /var/log/redis/redis-server.log -n 100

So if the setup was more standard that should be:

sudo tail /var/log/redis_6379.log -n 100

This outputs the last 100 lines of the file.

Where your log file is located is in your configs that you can access with:

redis-cli CONFIG GET *

The log file may not always be shown using the above. In that case use

tail -f `less  /etc/redis/redis.conf | grep logfile|cut -d\  -f2`

Can't change z-index with JQuery

zIndex is part of javaScript notation.(camelCase)
but jQuery.css uses same as CSS syntax.
so it is z-index.

you forgot .css("attr","value"). use ' or " in both, attr and val. so, .css("z-index","3000");

Adding Google Translate to a web site

Use:

c._ctkk=eval('((function(){var a\x3d2143197373;var b\x3d-58933561;return 408631+\x27.\x27+(a+b)})())');
<script type="text/javascript"> 
    (function(){
        var d="text/javascript",e="text/css",f="stylesheet",g="script",h="link",k="head",l="complete",m="UTF-8",n=".";
        function p(b){
            var a=document.getElementsByTagName(k)[0];
            a||(a=document.body.parentNode.appendChild(document.createElement(k)));
            a.appendChild(b)}
        function _loadJs(b){
            var a=document.createElement(g);
            a.type=d;
            a.charset=m;
            a.src=b;
            p(a)}
        function _loadCss(b){
            var a=document.createElement(h);
            a.type=e;
            a.rel=f;
            a.charset=m;
            a.href=b;
            p(a)}
        function _isNS(b){
            b=b.split(n);
            for(var a=window,c=0;c<b.length;++c)
                if(!(a=a[b[c]])) return ! 1;
            return ! 0}
        function _setupNS(b){
            b=b.split(n);
            for(var a=window,c=0;c<b.length;++c)
                a.hasOwnProperty?a.hasOwnProperty(b[c])?a=a[b[c]]:a=a[b[c]]={}:a=a[b[c]]||(a[b[c]]={});
            return a}
        window.addEventListener&&"undefined"==typeof document.readyState&&window.addEventListener("DOMContentLoaded",function(){document.readyState=l},!1);
    if (_isNS('google.translate.Element')){return}
    (function(){
        var c=_setupNS('google.translate._const');
        c._cl='en';
        c._cuc='googleTranslateElementInit1';
        c._cac='';
        c._cam='';
        c._ctkk=eval('((function(){var a\x3d2143197373;var b\x3d-58933561;return 408631+\x27.\x27+(a+b)})())');
        var h='translate.googleapis.com';
        var s=(true?'https':window.location.protocol=='https:'?'https':'http')+'://';
        var b=s+h;
        c._pah=h;
        c._pas=s;
        c._pbi=b+'/translate_static/img/te_bk.gif';
        c._pci=b+'/translate_static/img/te_ctrl3.gif';
        c._pli=b+'/translate_static/img/loading.gif';
        c._plla=h+'/translate_a/l';
        c._pmi=b+'/translate_static/img/mini_google.png';
        c._ps=b+'/translate_static/css/translateelement.css';
        c._puh='translate.google.com';
        _loadCss(c._ps);
        _loadJs(b+'/translate_static/js/element/main.js');
    })();
    })();
</script> 

How to output git log with the first line only?

If you don't want hashes and just the first lines (subject lines):

git log --pretty=format:%s

How to use the addr2line command in Linux?

You can also use gdb instead of addr2line to examine memory address. Load executable file in gdb and print the name of a symbol which is stored at the address. 16 Examining the Symbol Table.

(gdb) info symbol 0x4005BDC 

RGB to hex and hex to RGB

Here is the Javascript code to change HEX Color value to the Red, Green, Blue individually.

R = hexToR("#FFFFFF");
G = hexToG("#FFFFFF");
B = hexToB("#FFFFFF");

function hexToR(h) {return parseInt((cutHex(h)).substring(0,2),16)}
function hexToG(h) {return parseInt((cutHex(h)).substring(2,4),16)}
function hexToB(h) {return parseInt((cutHex(h)).substring(4,6),16)}
function cutHex(h) {return (h.charAt(0)=="#") ? h.substring(1,7):h}

How to increase request timeout in IIS?

In IIS Manager, right click on the site and go to Manage Web Site -> Advanced Settings. Under Connection Limits option, you should see Connection Time-out.

In Rails, how do you render JSON using a view?

Just add show.json.erb file with the contents

<%= @user.to_json %>

Sometimes it is useful when you need some extra helper methods that are not available in controller, i.e. image_path(@user.avatar) or something to generate additional properties in JSON:

<%= @user.attributes.merge(:avatar => image_path(@user.avatar)).to_json %>

How do I get a background location update every n minutes in my iOS application?

It seems that stopUpdatingLocation is what triggers the background watchdog timer, so I replaced it in didUpdateLocation with:

     [self.locationManager setDesiredAccuracy:kCLLocationAccuracyThreeKilometers];
     [self.locationManager setDistanceFilter:99999];

which appears to effectively power down the GPS. The selector for the background NSTimer then becomes:

- (void) changeAccuracy {
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
[self.locationManager setDistanceFilter:kCLDistanceFilterNone];
}

All I'm doing is periodically toggling the accuracy to get a high-accuracy coordinate every few minutes and because the locationManager hasn't been stopped, backgroundTimeRemaining stays at its maximum value. This reduced battery consumption from ~10% per hour (with constant kCLLocationAccuracyBest in the background) to ~2% per hour on my device

How to convert column with string type to int form in pyspark data frame?

Another way to do it is using the StructField if you have multiple fields that needs to be modified.

Ex:

from pyspark.sql.types import StructField,IntegerType, StructType,StringType
newDF=[StructField('CLICK_FLG',IntegerType(),True),
       StructField('OPEN_FLG',IntegerType(),True),
       StructField('I1_GNDR_CODE',StringType(),True),
       StructField('TRW_INCOME_CD_V4',StringType(),True),
       StructField('ASIAN_CD',IntegerType(),True),
       StructField('I1_INDIV_HHLD_STATUS_CODE',IntegerType(),True)
       ]
finalStruct=StructType(fields=newDF)
df=spark.read.csv('ctor.csv',schema=finalStruct)

Output:

Before

root
 |-- CLICK_FLG: string (nullable = true)
 |-- OPEN_FLG: string (nullable = true)
 |-- I1_GNDR_CODE: string (nullable = true)
 |-- TRW_INCOME_CD_V4: string (nullable = true)
 |-- ASIAN_CD: integer (nullable = true)
 |-- I1_INDIV_HHLD_STATUS_CODE: string (nullable = true)

After:

root
 |-- CLICK_FLG: integer (nullable = true)
 |-- OPEN_FLG: integer (nullable = true)
 |-- I1_GNDR_CODE: string (nullable = true)
 |-- TRW_INCOME_CD_V4: string (nullable = true)
 |-- ASIAN_CD: integer (nullable = true)
 |-- I1_INDIV_HHLD_STATUS_CODE: integer (nullable = true)

This is slightly a long procedure to cast , but the advantage is that all the required fields can be done.

It is to be noted that if only the required fields are assigned the data type, then the resultant dataframe will contain only those fields which are changed.

How can I upload fresh code at github?

In Linux use below command to upload code in git
1 ) git clone repository
ask for user name and password.
2) got to respositiory directory.
3) git add project name.
4) git commit -m ' messgage '.
5) git push origin master.
- user name ,password

Update new Change code into Github

->Goto Directory That your github up code
->git commit ProjectName -m 'Message'
->git push origin master.

SQL Developer is returning only the date, not the time. How do I fix this?

Well I found this way :

Oracle SQL Developer (Left top icon) > Preferences > Database > NLS and set the Date Format as MM/DD/YYYY HH24:MI:SS

enter image description here

PHP: How to remove all non printable characters in a string?

"cedivad" solved the issue for me with persistent result of Swedish chars ÅÄÖ.

$text = preg_replace( '/[^\p{L}\s]/u', '', $text );

Thanks!

What is the meaning of "int(a[::-1])" in Python?

The notation that is used in

a[::-1]

means that for a given string/list/tuple, you can slice the said object using the format

<object_name>[<start_index>, <stop_index>, <step>]

This means that the object is going to slice every "step" index from the given start index, till the stop index (excluding the stop index) and return it to you.

In case the start index or stop index is missing, it takes up the default value as the start index and stop index of the given string/list/tuple. If the step is left blank, then it takes the default value of 1 i.e it goes through each index.

So,

a = '1234'
print a[::2]

would print

13

Now the indexing here and also the step count, support negative numbers. So, if you give a -1 index, it translates to len(a)-1 index. And if you give -x as the step count, then it would step every x'th value from the start index, till the stop index in the reverse direction. For example

a = '1234'
print a[3:0:-1]

This would return

432

Note, that it doesn't return 4321 because, the stop index is not included.

Now in your case,

str(int(a[::-1]))

would just reverse a given integer, that is stored in a string, and then convert it back to a string

i.e "1234" -> "4321" -> 4321 -> "4321"

If what you are trying to do is just reverse the given string, then simply a[::-1] would work .

Find the directory part (minus the filename) of a full path in access 97

That's about it. There is no magic built-in function...

ViewPager PagerAdapter not updating the View

Always returning POSITION_NONE is simple but a little inefficient way because that evoke instantiation of all page that have already instantiated.

I've created a library ArrayPagerAdapter to change items in PagerAdapters dynamically.

Internally, this library's adapters return POSITION_NONE on getItemPosiition() only when necessary.

You can change items dynamically like following by using this library.

@Override
protected void onCreate(Bundle savedInstanceState) {
        /** ... **/
    adapter = new MyStatePagerAdapter(getSupportFragmentManager()
                            , new String[]{"1", "2", "3"});
    ((ViewPager)findViewById(R.id.view_pager)).setAdapter(adapter);
     adapter.add("4");
     adapter.remove(0);
}

class MyPagerAdapter extends ArrayViewPagerAdapter<String> {

    public MyPagerAdapter(String[] data) {
        super(data);
    }

    @Override
    public View getView(LayoutInflater inflater, ViewGroup container, String item, int position) {
        View v = inflater.inflate(R.layout.item_page, container, false);
        ((TextView) v.findViewById(R.id.item_txt)).setText(item);
        return v;
    }
}

Thils library also support pages created by Fragments.

HTML5 form validation pattern alphanumeric with spaces?

Use this code to ensure the user doesn't just enter spaces but a valid name:

pattern="[a-zA-Z][a-zA-Z0-9\s]*"

How to create jar file with package structure?

Your specified folderName must be on C:\Program Files\Java\jdk1.7.0_02\bin path Foldername having class files.

C:\Program Files\Java\jdk1.7.0_02\bin>jar cvf program1.jar Foldername

Now program1.jar will create in C:\Program Files\Java\jdk1.7.0_02\bin path

C# - Insert a variable number of spaces into a string? (Formatting an output file)

For this you probably want myString.PadRight(totalLength, charToInsert).

See String.PadRight Method (Int32) for more info.

Classpath resource not found when running as jar

Regarding to the originally error message

cannot be resolved to absolute file path because it does not reside in the file system

The following code could be helpful, to find the solution for the path problem:

Paths.get("message.txt").toAbsolutePath().toString();

With this you can determine, where the application expects the missing file. You can execute this in the main method of your application.

How do I create an .exe for a Java program?

The Java Service Wrapper might help you, depending on your requirements.

How to convert Blob to File in JavaScript

I have used FileSaver.js to save the blob as file.

This is the repo : https://github.com/eligrey/FileSaver.js/

Usage:

import { saveAs } from 'file-saver';

var blob = new Blob(["Hello, world!"], {type: "text/plain;charset=utf-8"});
saveAs(blob, "hello world.txt");

saveAs("https://httpbin.org/image", "image.jpg");

.keyCode vs. .which

jQuery normalises event.which depending on whether event.which, event.keyCode or event.charCode is supported by the browser:

// Add which for key events
if ( event.which == null && (event.charCode != null || event.keyCode != null) ) {
   event.which = event.charCode != null ? event.charCode : event.keyCode;
}

An added benefit of .which is that jQuery does it for mouse clicks too:

// Add which for click: 1 === left; 2 === middle; 3 === right
// Note: button is not normalized, so don't use it
if ( !event.which && event.button !== undefined ) {
    event.which = (event.button & 1 ? 1 : ( event.button & 2 ? 3 : ( event.button & 4 ? 2 : 0 ) ));
}

add to array if it isn't there already

Try adding as key instead of value:

Adding an entry

function addEntry($entry) {
    $this->entries[$entry] = true;
}

Getting all entries

function getEntries() {
    return array_keys($this->enties);
}

How can I set Image source with base64

Try using setAttribute instead:

document.getElementById('img')
    .setAttribute(
        'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
    );

Real answer: (And make sure you remove the line-breaks in the base64.)

Highcharts - redraw() vs. new Highcharts.chart

var newData = [1,2,3,4,5,6,7];
var chart = $('#chartjs').highcharts();
chart.series[0].setData(newData, true);

Explanation:
Variable newData contains value that want to update in chart. Variable chart is an object of a chart. setData is a method provided by highchart to update data.

Method setData contains two parameters, in first parameter we need to pass new value as array and second param is Boolean value. If true then chart updates itself and if false then we have to use redraw() method to update chart (i.e chart.redraw();)

http://jsfiddle.net/NxEnH/8/

What are the file limits in Git (number and size)?

I think that it's good to try to avoid large file commits as being part of the repository (e.g. a database dump might be better off elsewhere), but if one considers the size of the kernel in its repository, you can probably expect to work comfortably with anything smaller in size and less complex than that.

How to create a numpy array of arbitrary length strings?

You could use the object data type:

>>> import numpy
>>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
>>> s[0] += 'bcdef'
>>> s
array([abcdef, b, dude], dtype=object)

How to use nan and inf in C?

<inf.h>

/* IEEE positive infinity.  */

#if __GNUC_PREREQ(3,3)
# define INFINITY   (__builtin_inff())
#else
# define INFINITY   HUGE_VALF
#endif

and

<bits/nan.h>
#ifndef _MATH_H
# error "Never use <bits/nan.h> directly; include <math.h> instead."
#endif


/* IEEE Not A Number.  */

#if __GNUC_PREREQ(3,3)

# define NAN    (__builtin_nanf (""))

#elif defined __GNUC__

# define NAN \
  (__extension__                                  \
   ((union { unsigned __l __attribute__ ((__mode__ (__SI__))); float __d; })  \
    { __l: 0x7fc00000UL }).__d)

#else

# include <endian.h>

# if __BYTE_ORDER == __BIG_ENDIAN
#  define __nan_bytes       { 0x7f, 0xc0, 0, 0 }
# endif
# if __BYTE_ORDER == __LITTLE_ENDIAN
#  define __nan_bytes       { 0, 0, 0xc0, 0x7f }
# endif

static union { unsigned char __c[4]; float __d; } __nan_union
    __attribute_used__ = { __nan_bytes };
# define NAN    (__nan_union.__d)

#endif  /* GCC.  */

Using CookieContainer with WebClient class

Yes. IMHO, overriding GetWebRequest() is the best solution to WebClient's limited functionalty. Before I knew about this option, I wrote lots of really painful code at the HttpWebRequest layer because WebClient almost, but not quite, did what I needed. Derivation is much easier.

Another option is to use the regular WebClient class, but manually populate the Cookie header before making the request and then pull out the Set-Cookies header on the response. There are helper methods on the CookieContainer class which make creating and parsing these headers easier: CookieContainer.SetCookies() and CookieContainer.GetCookieHeader(), respectively.

I prefer the former approach since it's easier for the caller and requires less repetitive code than the second option. Also, the derivation approach works the same way for multiple extensibility scenarios (e.g. cookies, proxies, etc.).

SQL permissions for roles

USE DataBaseName; GO --------- CREATE ROLE --------- CREATE ROLE Doctors ; GO  ---- Assign Role To users -------  CREATE USER [Username] FOR LOGIN [Domain\Username] EXEC sp_addrolemember N'Doctors', N'Username'  ----- GRANT Permission to Users Assinged with this Role----- GRANT ALL ON Table1, Table2, Table3 TO Doctors; GO 

SQL Server Linked Server Example Query

select name from drsql01.test.dbo.employee
  • drslq01 is servernmae --linked serer
  • test is database name
  • dbo is schema -default schema
  • employee is table name

I hope it helps to understand, how to execute query for linked server

How can I select all children of an element except the last child?

.nav-menu li:not(:last-child){
    // write some style here
}

this code should apply the style to all

  • except the last child

  • HTTP headers in Websockets client API

    Sending Authorization header is not possible.

    Attaching a token query parameter is an option. However, in some circumstances, it may be undesirable to send your main login token in plain text as a query parameter because it is more opaque than using a header and will end up being logged whoknowswhere. If this raises security concerns for you, an alternative is to use a secondary JWT token just for the web socket stuff.

    Create a REST endpoint for generating this JWT, which can of course only be accessed by users authenticated with your primary login token (transmitted via header). The web socket JWT can be configured differently than your login token, e.g. with a shorter timeout, so it's safer to send around as query param of your upgrade request.

    Create a separate JwtAuthHandler for the same route you register the SockJS eventbusHandler on. Make sure your auth handler is registered first, so you can check the web socket token against your database (the JWT should be somehow linked to your user in the backend).

    Calculate row means on subset of columns

    (Another solution using pivot_longer & pivot_wider from latest Tidyr update)

    You should try using pivot_longer to get your data from wide to long form Read latest tidyR update on pivot_longer & pivot_wider (https://tidyr.tidyverse.org/articles/pivot.html)

    library(tidyverse)
    C1<-c(3,2,4,4,5)
    C2<-c(3,7,3,4,5)
    C3<-c(5,4,3,6,3)
    DF<-data.frame(ID=c("A","B","C","D","E"),C1=C1,C2=C2,C3=C3)
    

    Output here

      ID     mean
      <fct> <dbl>
    1 A      3.67
    2 B      4.33
    3 C      3.33
    4 D      4.67
    5 E      4.33
    

    Where is SQL Profiler in my SQL Server 2008?

    Also ensure that "client tools" are selected in the install options. However if SQL Managment Studio 2008 exists then it is likely that you installed the express edition.

    How to Specify Eclipse Proxy Authentication Credentials?

    This sometime works, sometime no.

    I have installed 1 Eclipse - works.

    Installed second - doesn't work.

    And I cann't figure why!

    After some time may be found a solution.

    Need delete all setting for proxy (included credentials). And re-insert for new.

    After this for me getting work.

    How can I create basic timestamps or dates? (Python 3.4)

    >>> import time
    >>> print(time.strftime('%a %H:%M:%S'))
    Mon 06:23:14
    

    Count number of rows within each group

    An alternative to the aggregate() function in this case would be table() with as.data.frame(), which would also indicate which combinations of Year and Month are associated with zero occurrences

    df<-data.frame(x=rep(1:6,rep(c(1,2,3),2)),year=1993:2004,month=c(1,1:11))
    
    myAns<-as.data.frame(table(df[,c("year","month")]))
    

    And without the zero-occurring combinations

    myAns[which(myAns$Freq>0),]
    

    Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

    As mentioned in other posts, simply catch the exception in DbEntityValidationException class. Which will give you watever you required during error cases.

     try
     {
      ....
     }
     catch(DbEntityValidationException ex)
     {
      ....
     }
    

    why I can't get value of label with jquery and javascript?

    Label's aren't form elements. They don't have a value. They have innerHTML and textContent.

    Thus,

    $('#telefon').html() 
    // or
    $('#telefon').text()
    

    or

    var telefon = document.getElementById('telefon');
    telefon.innerHTML;
    

    If you are starting with your form element, check out the labels list of it. That is,

    var el = $('#myformelement');
    var label = $( el.prop('labels') );
    // label.html();
    // el.val();
    // blah blah blah you get the idea
    

    SQL SERVER, SELECT statement with auto generate row id

    Select (Select count(y.au_lname) from dbo.authors y
    where y.au_lname + y.au_fname <= x.au_lname + y.au_fname) as Counterid,
    x.au_lname,x.au_fname from authors x group by au_lname,au_fname
    order by Counterid --Alternatively that can be done which is equivalent as above..
    

    Dynamic function name in javascript?

    For setting the name of an existing anonymous function:
    (Based on @Marcosc's answer)

    var anonymous = function() { return true; }
    
    var name = 'someName';
    var strFn = anonymous.toString().replace('function ', 'return function ' + name);
    var fn = new Function(strFn)();
    
    console.log(fn()); // —> true
    

    Demo.

    Note: Don't do it ;/

    storing user input in array

    You have at least these 3 issues:

    1. you are not getting the element's value properly
    2. The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
    3. Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.

    You can save all three values at once by doing:

    var title=new Array();
    var names=new Array();//renamed to names -added an S- 
                          //to avoid conflicts with the input named "name"
    var tickets=new Array();
    
    function insert(){
        var titleValue = document.getElementById('title').value;
        var actorValue = document.getElementById('name').value;
        var ticketsValue = document.getElementById('tickets').value;
        title[title.length]=titleValue;
        names[names.length]=actorValue;
        tickets[tickets.length]=ticketsValue;
      }
    

    And then change the show function to:

    function show() {
      var content="<b>All Elements of the Arrays :</b><br>";
      for(var i = 0; i < title.length; i++) {
         content +=title[i]+"<br>";
      }
      for(var i = 0; i < names.length; i++) {
         content +=names[i]+"<br>";
      }
      for(var i = 0; i < tickets.length; i++) {
         content +=tickets[i]+"<br>";
      }
      document.getElementById('display').innerHTML = content; //note that I changed 
                                                        //to 'display' because that's
                                                  //what you have in your markup
    }
    

    Here's a jsfiddle for you to play around.

    How do I find files that do not contain a given string pattern?

    You will actually need:

    find .  -not  -ipath '.*svn*' -exec  grep  -H -E -o -c  "foo"  {} \; | grep :0\$
    

    Common CSS Media Queries Break Points

    I've been using:

    @media only screen and (min-width: 768px) {
        /* tablets and desktop */
    }
    
    @media only screen and (max-width: 767px) {
        /* phones */
    }
    
    @media only screen and (max-width: 767px) and (orientation: portrait) {
        /* portrait phones */
    }
    

    It keeps things relatively simple and allows you to do something a bit different for phones in portrait mode (a lot of the time I find myself having to change various elements for them).

    jQuery onclick event for <li> tags

    this is a HTML element.
    $(this) is a jQuery object that encapsulates the HTML element.

    Use $(this).text() to retrieve the element's inner text.

    I suggest you refer to the jQuery API documentation for further information.

    Full examples of using pySerial package

    http://web.archive.org/web/20131107050923/http://www.roman10.net/serial-port-communication-in-python/comment-page-1/

    #!/usr/bin/python
    
    import serial, time
    #initialization and open the port
    
    #possible timeout values:
    #    1. None: wait forever, block call
    #    2. 0: non-blocking mode, return immediately
    #    3. x, x is bigger than 0, float allowed, timeout block call
    
    ser = serial.Serial()
    #ser.port = "/dev/ttyUSB0"
    ser.port = "/dev/ttyUSB7"
    #ser.port = "/dev/ttyS2"
    ser.baudrate = 9600
    ser.bytesize = serial.EIGHTBITS #number of bits per bytes
    ser.parity = serial.PARITY_NONE #set parity check: no parity
    ser.stopbits = serial.STOPBITS_ONE #number of stop bits
    #ser.timeout = None          #block read
    ser.timeout = 1            #non-block read
    #ser.timeout = 2              #timeout block read
    ser.xonxoff = False     #disable software flow control
    ser.rtscts = False     #disable hardware (RTS/CTS) flow control
    ser.dsrdtr = False       #disable hardware (DSR/DTR) flow control
    ser.writeTimeout = 2     #timeout for write
    
    try: 
        ser.open()
    except Exception, e:
        print "error open serial port: " + str(e)
        exit()
    
    if ser.isOpen():
    
        try:
            ser.flushInput() #flush input buffer, discarding all its contents
            ser.flushOutput()#flush output buffer, aborting current output 
                     #and discard all that is in buffer
    
            #write data
            ser.write("AT+CSQ")
            print("write data: AT+CSQ")
    
           time.sleep(0.5)  #give the serial port sometime to receive the data
    
           numOfLines = 0
    
           while True:
              response = ser.readline()
              print("read data: " + response)
    
            numOfLines = numOfLines + 1
    
            if (numOfLines >= 5):
                break
    
            ser.close()
        except Exception, e1:
            print "error communicating...: " + str(e1)
    
    else:
        print "cannot open serial port "
    

    How to determine the first and last iteration in a foreach loop?

    You could use a counter:

    $i = 0;
    $len = count($array);
    foreach ($array as $item) {
        if ($i == 0) {
            // first
        } else if ($i == $len - 1) {
            // last
        }
        // …
        $i++;
    }
    

    Ruby class instance variable vs. class variable

    While it may immediately seem useful to utilize class instance variables, since class instance variable are shared among subclasses and they can be referred to within both singleton and instance methods, there is a singificant drawback. They are shared and so subclasses can change the value of the class instance variable, and the base class will also be affected by the change, which is usually undesirable behavior:

    class C
      @@c = 'c'
      def self.c_val
        @@c
      end
    end
    
    C.c_val
     => "c" 
    
    class D < C
    end
    
    D.instance_eval do 
      def change_c_val
        @@c = 'd'
      end
    end
     => :change_c_val 
    
    D.change_c_val
    (irb):12: warning: class variable access from toplevel
     => "d" 
    
    C.c_val
     => "d" 
    

    Rails introduces a handy method called class_attribute. As the name implies, it declares a class-level attribute whose value is inheritable by subclasses. The class_attribute value can be accessed in both singleton and instance methods, as is the case with the class instance variable. However, the huge benefit with class_attribute in Rails is subclasses can change their own value and it will not impact parent class.

    class C
      class_attribute :c
      self.c = 'c'
    end
    
     C.c
     => "c" 
    
    class D < C
    end
    
    D.c = 'd'
     => "d" 
    
     C.c
     => "c" 
    

    What is the difference between function and procedure in PL/SQL?

    In the few words - function returns something. You can use function in SQL query. Procedure is part of code to do something with data but you can not invoke procedure from query, you have to run it in PL/SQL block.

    How to get all options of a select using jQuery?

    For multiselect option:

    $('#test').val() returns list of selected values. $('#test option').length returns total number of options (both selected and not selected)

    How to convert color code into media.brush?

    For simplicity you could create an extension:-

        public static SolidColorBrush ToSolidColorBrush(this string hex_code)
        {
            return (SolidColorBrush)new BrushConverter().ConvertFromString(hex_code);
        }
    

    And then to use:-

     SolidColorBrush accentBlue = "#3CACDC".ToSolidColorBrush();
    

    Retrieve CPU usage and memory usage of a single process on Linux?

    To get the memory usage of just your application (as opposed to the shared libraries it uses, you need to use the Linux smaps interface). This answer explains it well.

    CSS: image link, change on hover

    It can be better if you set the a element in this way

    display:block;
    

    and then by css sprites set your over background

    Edit: check this example out http://jsfiddle.net/steweb/dTwtk/

    Elegant way to read file into byte[] array in Java

    A long time ago:

    Call any of these

    byte[] org.apache.commons.io.FileUtils.readFileToByteArray(File file)
    byte[] org.apache.commons.io.IOUtils.toByteArray(InputStream input) 
    

    From

    http://commons.apache.org/io/

    If the library footprint is too big for your Android app, you can just use relevant classes from the commons-io library

    Today (Java 7+ or Android API Level 26+)

    Luckily, we now have a couple of convenience methods in the nio packages. For instance:

    byte[] java.nio.file.Files.readAllBytes(Path path)
    

    Javadoc here

    Eclipse Build Path Nesting Errors

    Here is a simple solution:

    1. Right click the project >> properties >> build path;
    2. In Source tab, Select all the source folders;
    3. Remove them;
    4. Right click on project, Maven >> Update the project.

    Remove all classes that begin with a certain string

    http://www.mail-archive.com/[email protected]/msg03998.html says:

    ...and .removeClass() would remove all classes...

    It works for me ;)

    cheers

    Memcache Vs. Memcached

    (PartlyStolen from ServerFault)

    I think that both are functionally the same, but they simply have different authors, and the one is simply named more appropriately than the other.


    Here is a quick backgrounder in naming conventions (for those unfamiliar), which explains the frustration by the question asker: For many *nix applications, the piece that does the backend work is called a "daemon" (think "service" in Windows-land), while the interface or client application is what you use to control or access the daemon. The daemon is most often named the same as the client, with the letter "d" appended to it. For example "imap" would be a client that connects to the "imapd" daemon.

    This naming convention is clearly being adhered to by memcache when you read the introduction to the memcache module (notice the distinction between memcache and memcached in this excerpt):

    Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.

    The Memcache module also provides a session handler (memcache).

    More information about memcached can be found at » http://www.danga.com/memcached/.

    The frustration here is caused by the author of the PHP extension which was badly named memcached, since it shares the same name as the actual daemon called memcached. Notice also that in the introduction to memcached (the php module), it makes mention of libmemcached, which is the shared library (or API) that is used by the module to access the memcached daemon:

    memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.

    This extension uses libmemcached library to provide API for communicating with memcached servers. It also provides a session handler (memcached).

    Information about libmemcached can be found at » http://tangent.org/552/libmemcached.html.

    Detect backspace and del on "input" event?

    on android devices using chrome we can't detect a backspace. You can use workaround for it:

    var oldInput = '',
        newInput = '';
    
     $("#ID").keyup(function () {
      newInput = $('#ID').val();
       if(newInput.length < oldInput.length){
          //backspace pressed
       }
       oldInput = newInput;
     })
    

    Is there a free GUI management tool for Oracle Database Express?

    Yes, there is Oracle SQL Developer, which is maintained by Oracle.

    Oracle SQL Developer is a free graphical tool for database development. With SQL Developer, you can browse database objects, run SQL statements and SQL scripts, and edit and debug PL/SQL statements. You can also run any number of provided reports, as well as create and save your own. SQL Developer enhances productivity and simplifies your database development tasks.

    SQL Developer can connect to any Oracle Database version 10g and later and runs on Windows, Linux and Mac OSX.

    JUnit test for System.out.println()

    @dfa answer is great, so I took it a step farther to make it possible to test blocks of ouput.

    First I created TestHelper with a method captureOutput that accepts the annoymous class CaptureTest. The captureOutput method does the work of setting and tearing down the output streams. When the implementation of CaptureOutput's test method is called, it has access to the output generate for the test block.

    Source for TestHelper:

    public class TestHelper {
    
        public static void captureOutput( CaptureTest test ) throws Exception {
            ByteArrayOutputStream outContent = new ByteArrayOutputStream();
            ByteArrayOutputStream errContent = new ByteArrayOutputStream();
    
            System.setOut(new PrintStream(outContent));
            System.setErr(new PrintStream(errContent));
    
            test.test( outContent, errContent );
    
            System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
            System.setErr(new PrintStream(new FileOutputStream(FileDescriptor.out)));
    
        }
    }
    
    abstract class CaptureTest {
        public abstract void test( ByteArrayOutputStream outContent, ByteArrayOutputStream errContent ) throws Exception;
    }
    

    Note that TestHelper and CaptureTest are defined in the same file.

    Then in your test, you can import the static captureOutput. Here is an example using JUnit:

    // imports for junit
    import static package.to.TestHelper.*;
    
    public class SimpleTest {
    
        @Test
        public void testOutput() throws Exception {
    
            captureOutput( new CaptureTest() {
                @Override
                public void test(ByteArrayOutputStream outContent, ByteArrayOutputStream errContent) throws Exception {
    
                    // code that writes to System.out
    
                    assertEquals( "the expected output\n", outContent.toString() );
                }
            });
    }
    

    How to convert date in to yyyy-MM-dd Format?

    UPDATE My Answer here is now outdated. The Joda-Time project is now in maintenance mode, advising migration to the java.time classes. See the modern solution in the Answer by Ole V.V..

    Joda-Time

    The accepted answer by NidhishKrishnan is correct.

    For fun, here is the same kind of code in Joda-Time 2.3.

    // © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
    // import org.joda.time.*;
    // import org.joda.time.format.*;
    
    java.util.Date date = new Date(); // A Date object coming from other code.
    
    // Pass the java.util.Date object to constructor of Joda-Time DateTime object.
    DateTimeZone kolkataTimeZone = DateTimeZone.forID( "Asia/Kolkata" );
    DateTime dateTimeInKolkata = new DateTime( date, kolkataTimeZone );
    
    DateTimeFormatter formatter = DateTimeFormat.forPattern( "yyyy-MM-dd");
    System.out.println( "dateTimeInKolkata formatted for date: " + formatter.print( dateTimeInKolkata ) );
    System.out.println( "dateTimeInKolkata formatted for ISO 8601: " + dateTimeInKolkata );
    

    When run…

    dateTimeInKolkata formatted for date: 2013-12-17
    dateTimeInKolkata formatted for ISO 8601: 2013-12-17T14:56:46.658+05:30
    

    'negative' pattern matching in python

    If the OK line is the first line and the last line is the dot you could consider slice them off like this:

    TestString = '''OK SYS 10 LEN 20 12 43
    1233a.fdads.txt,23 /data/a11134/a.txt
    3232b.ddsss.txt,32 /data/d13f11/b.txt
    3452d.dsasa.txt,1234 /data/c13af4/f.txt
    .
    '''
    print('\n'.join(TestString.split()[1:-1]))
    

    However if this is a very large string you may run into memory problems.

    The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

    try giving AppPool ID or Network Services whichever applicable access HKLM\SYSTEM\CurrentControlSet\services\eventlog\security also. I was getting the same error .. this worked for me. See the error is also saying that the inaccessible logs are Security Logs.

    I also gave permission in eventlog\application .

    I gave full access everywhere.

    How do I change the IntelliJ IDEA default JDK?

    One other place worth checking: Look in the pom.xml for your project, if you are using Maven compiler plugin, at the source/target config and make sure it is the desired version of Java. I found that I had 1.7 in the following; I changed it to 1.8 and then everything compiled correctly in IntelliJ.

    <build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
    </plugins>
    </build>
    

    jQuery javascript regex Replace <br> with \n

    Not really anything to do with jQuery, but if you want to trim a pattern from a string, then use a regular expression:

    <textarea id="ta0"></textarea>
    <button onclick="
      var ta = document.getElementById('ta0');
      var text = 'some<br>text<br />to<br/>replace';
      var re = /<br *\/?>/gi;
      ta.value = text.replace(re, '\n');
    ">Add stuff to text area</button>
    

    How to convert float to varchar in SQL Server

    Try using the STR() function.

    SELECT STR(float_field, 25, 5)
    

    STR() Function


    Another note: this pads on the left with spaces. If this is a problem combine with LTRIM:

    SELECT LTRIM(STR(float_field, 25, 5))
    

    onclick open window and specific size

    Using function in typescript

    openWindow(){
        //you may choose to deduct some value from current screen size
        let height = window.screen.availHeight-100;
        let width = window.screen.availWidth-150;
        window.open("http://your_url",`width=${width},height=${height}`);
    }
    

    How to persist data in a dockerized postgres database using volumes

    I think you just need to create your volume outside docker first with a docker create -v /location --name and then reuse it.

    And by the time I used to use docker a lot, it wasn't possible to use a static docker volume with dockerfile definition so my suggestion is to try the command line (eventually with a script ) .

    MySQL WHERE: how to write "!=" or "not equals"?

    The != operator most certainly does exist! It is an alias for the standard <> operator.

    Perhaps your fields are not actually empty strings, but instead NULL?

    To compare to NULL you can use IS NULL or IS NOT NULL or the null safe equals operator <=>.

    -didSelectRowAtIndexPath: not being called

    Another possibility is that a UITapGestureRecognizer could be eating the events, as was the case here: https://stackoverflow.com/a/9248827/214070

    I didn't suspect this cause, because the table cells would still highlight blue as if the taps were getting through.

    How to make a new List in Java

    Sometimes - but only very rarely - instead of a new ArrayList, you may want a new LinkedList. Start out with ArrayList and if you have performance problems and evidence that the list is the problem, and a lot of adding and deleting to that list - then - not before - switch to a LinkedList and see if things improve. But in the main, stick with ArrayList and all will be fine.

    Why am I getting error for apple-touch-icon-precomposed.png

    I guess apple devices make those requests if the device owner adds the site to it. This is the equivalent of the favicon. To resolve, add 2 100×100 png files, save it as apple-touch-icon-precomposed.png and apple-touch-icon.png and upload it to the root directory of the server. After that, the error should be gone.

    I noticed lots of requests for apple-touch-icon-precomposed.png and apple-touch-icon.png in the logs that tried to load the images from the root directory of the site. I first thought it was a misconfiguration of the mobile theme and plugin, but found out later that Apple devices make those requests if the device owner adds the site to it.

    Source: Why Webmasters Should Analyze Their 404 Error Log (Mar 2012; by Martin Brinkmann)

    "You tried to execute a query that does not include the specified aggregate function"

    The error is because fName is included in the SELECT list, but is not included in a GROUP BY clause and is not part of an aggregate function (Count(), Min(), Max(), Sum(), etc.)

    You can fix that problem by including fName in a GROUP BY. But then you will face the same issue with surname. So put both in the GROUP BY:

    SELECT
        fName,
        surname,
        Count(*) AS num_rows
    FROM
        author
        INNER JOIN book
        ON author.aID = book.authorID;
    GROUP BY
        fName,
        surname
    

    Note I used Count(*) where you wanted SUM(orders.quantity). However, orders isn't included in the FROM section of your query, so you must include it before you can Sum() one of its fields.

    If you have Access available, build the query in the query designer. It can help you understand what features are possible and apply the correct Access SQL syntax.

    How do I restrict a float value to only two places after the decimal point in C?

    You can still use:

    float ceilf(float x); // don't forget #include <math.h> and link with -lm.
    

    example:

    float valueToRound = 37.777779;
    float roundedValue = ceilf(valueToRound * 100) / 100;
    

    Perl: function to trim string leading and trailing whitespace

    Here's one approach using a regular expression:

    $string =~ s/^\s+|\s+$//g ;     # remove both leading and trailing whitespace
    

    Perl 6 will include a trim function:

    $string .= trim;
    

    Source: Wikipedia

    How to get current screen width in CSS?

    Based on your requirement i think you are wanted to put dynamic fields in CSS file, however that is not possible as CSS is a static language. However you can simulate the behaviour by using Angular.

    Please refer to the below example. I'm here showing only one component.

    login.component.html

    import { Component, OnInit } from '@angular/core';
    import { DomSanitizer } from '@angular/platform-browser';
    
        @Component({
          selector: 'app-login',
          templateUrl: './login.component.html',
          styleUrls: ['./login.component.css']
        })
        export class LoginComponent implements OnInit {
    
          cssProperty:any;
          constructor(private sanitizer: DomSanitizer) { 
            console.log(window.innerWidth);
            console.log(window.innerHeight);
            this.cssProperty = 'position:fixed;top:' + Math.floor(window.innerHeight/3.5) + 'px;left:' + Math.floor(window.innerWidth/3) + 'px;';
            this.cssProperty = this.sanitizer.bypassSecurityTrustStyle(this.cssProperty);
          }
    
        ngOnInit() {
    
          }
    
        }
    

    login.component.ts

    <div class="home">
        <div class="container" [style]="cssProperty">
            <div class="card">
                <div class="card-header">Login</div>
                <div class="card-body">Please login</div>
                <div class="card-footer">Login</div>
            </div>
        </div>
    </div>
    

    login.component.css

    .card {
        max-width: 400px;
    }
    .card .card-body {
        min-height: 150px;
    }
    .home {
        background-color: rgba(171, 172, 173, 0.575);
    }
    

    React prevent event bubbling in nested components on click

    I had the same issue. I found stopPropagation did work. I would split the list item into a separate component, as so:

    class List extends React.Component {
      handleClick = e => {
        // do something
      }
    
      render() {
        return (
          <ul onClick={this.handleClick}>
            <ListItem onClick={this.handleClick}>Item</ListItem> 
          </ul>
        )
      }
    }
    
    class ListItem extends React.Component {
      handleClick = e => {
        e.stopPropagation();  //  <------ Here is the magic
        this.props.onClick();
      }
    
      render() {
        return (
          <li onClick={this.handleClick}>
            {this.props.children}
          </li>       
        )
      }
    }
    

    Android ADB commands to get the device properties

    From Linux Terminal:

    adb shell getprop | grep "model\|version.sdk\|manufacturer\|hardware\|platform\|revision\|serialno\|product.name\|brand"
    

    From Windows PowerShell:

    adb shell 
    getprop | grep -e 'model' -e 'version.sdk' -e 'manufacturer' -e 'hardware' -e 'platform' -e 'revision' -e 'serialno' -e 'product.name' -e 'brand'
    

    Sample output for Samsung:

    [gsm.version.baseband]: [G900VVRU2BOE1]
    [gsm.version.ril-impl]: [Samsung RIL v3.0]
    [net.knoxscep.version]: [2.0.1]
    [net.knoxsso.version]: [2.1.1]
    [net.knoxvpn.version]: [2.2.0]
    [persist.service.bdroid.version]: [4.1]
    [ro.board.platform]: [msm8974]
    [ro.boot.hardware]: [qcom]
    [ro.boot.serialno]: [xxxxxx]
    [ro.build.version.all_codenames]: [REL]
    [ro.build.version.codename]: [REL]
    [ro.build.version.incremental]: [G900VVRU2BOE1]
    [ro.build.version.release]: [5.0]
    [ro.build.version.sdk]: [21]
    [ro.build.version.sdl]: [2101]
    [ro.com.google.gmsversion]: [5.0_r2]
    [ro.config.timaversion]: [3.0]
    [ro.hardware]: [qcom]
    [ro.opengles.version]: [196108]
    [ro.product.brand]: [Verizon]
    [ro.product.manufacturer]: [samsung]
    [ro.product.model]: [SM-G900V]
    [ro.product.name]: [kltevzw]
    [ro.revision]: [14]
    [ro.serialno]: [e5ce97c7]
    

    How do you put an image file in a json object?

    To upload files directly to Mongo DB you can make use of Grid FS. Although I will suggest you to upload the file anywhere in file system and put the image's url in the JSON object for every entry and then when you call the data for specific object you can call for the image using URL.

    Tell me which backend technology are you using? I can give more suggestions based on that.

    What is the largest Safe UDP Packet Size on the Internet

    The maximum safe UDP payload is 508 bytes. This is a packet size of 576 (the "minimum maximum reassembly buffer size"), minus the maximum 60-byte IP header and the 8-byte UDP header.

    Any UDP payload this size or smaller is guaranteed to be deliverable over IP (though not guaranteed to be delivered). Anything larger is allowed to be outright dropped by any router for any reason. Except on an IPv6-only route, where the maximum payload is 1,212 bytes. As others have mentioned, additional protocol headers could be added in some circumstances. A more conservative value of around 300-400 bytes may be preferred instead.

    The maximum possible UDP payload is 67 KB, split into 45 IP packets, adding an additional 900 bytes of overhead (IPv4, MTU 1500, minimal 20-byte IP headers).

    Any UDP packet may be fragmented. But this isn't too important, because losing a fragment has the same effect as losing an unfragmented packet: the entire packet is dropped. With UDP, this is going to happen either way.

    IP packets include a fragment offset field, which indicates the byte offset of the UDP fragment in relation to its UDP packet. This field is 13-bit, allowing 8,192 values, which are in 8-byte units. So the range of such offsets an IP packet can refer to is 0...65,528 bytes. Being an offset, we add 1,480 for the last UDP fragment to get 67,008. Minus the UDP header in the first fragment gives us a nice, round 67 KB.

    Sources: RFC 791, RFC 1122, RFC 2460

    How to align the checkbox and label in same line in html?

    Just place a div around the input and label...

        <li>
          <div>
            <input id="checkid"  type="checkbox" value="test" />
          </div>
          <div>
            <label  style="word-wrap:break-word">testdata</label>
          </div>
        </li>
    

    Best way to pass parameters to jQuery's .load()

    In the first case, the data are passed to the script via GET, in the second via POST.

    http://docs.jquery.com/Ajax/load#urldatacallback

    I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.

    Adding integers to an int array

    To add an element to an array you need to use the format:

    array[index] = element;
    

    Where array is the array you declared, index is the position where the element will be stored, and element is the item you want to store in the array.

    In your code, you'd want to do something like this:

    int[] num = new int[args.length];
    for (int i = 0; i < args.length; i++) {
        int neki = Integer.parseInt(args[i]);
        num[i] = neki;
    }
    

    The add() method is available for Collections like List and Set. You could use it if you were using an ArrayList (see the documentation), for example:

    List<Integer> num = new ArrayList<>();
    for (String s : args) {
        int neki = Integer.parseInt(s);
        num.add(neki);
    }
    

    Windows.history.back() + location.reload() jquery

    It will have already gone back before it executes the reload.

    You would be better off to replace:

    window.history.back();
    location.reload(); 
    

    with:

    window.location.replace("pagehere.html");
    

    How to return a custom object from a Spring Data JPA GROUP BY query

    I do not like java type names in query strings and handle it with a specific constructor. Spring JPA implicitly calls constructor with query result in HashMap parameter:

    @Getter
    public class SurveyAnswerStatistics {
      public static final String PROP_ANSWER = "answer";
      public static final String PROP_CNT = "cnt";
    
      private String answer;
      private Long   cnt;
    
      public SurveyAnswerStatistics(HashMap<String, Object> values) {
        this.answer = (String) values.get(PROP_ANSWER);
        this.count  = (Long) values.get(PROP_CNT);
      }
    }
    
    @Query("SELECT v.answer as "+PROP_ANSWER+", count(v) as "+PROP_CNT+" FROM  Survey v GROUP BY v.answer")
    List<SurveyAnswerStatistics> findSurveyCount();
    

    Code needs Lombok for resolving @Getter

    How do I tell a Python script to use a particular version

    put at the start of my programs its use full for work with python

    import sys
    
    if sys.version_info[0] < 3:
        raise Exception("Python 3 or a more recent version is required.")
    

    This code will help full for the progress

    DTO and DAO concepts and MVC

    DTO is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.

    • DTO should only contain private fields for your data, getters, setters, and constructors.
    • DTO is not recommended to add business logic methods to such classes, but it is OK to add some util methods.

    DAO is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).

    Here is an example of how the DAO and DTO interfaces would look like:

    interface PersonDTO {
        String getName();
        void setName(String name);
        //.....
    }
    
    interface PersonDAO {
        PersonDTO findById(long id);
        void save(PersonDTO person);
        //.....
    }
    

    The MVC is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
    It tells you how to organize the whole application, not just the part responsible for data retrieval.

    As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
    This would separate your business logic from the view.

    How to get response using cURL in PHP

    am using this simple one

    ´´´´ class Connect {

    public $url;
    public $path;
    public $username;
    public $password;
    
        $ch = curl_init();
    
        curl_setopt($ch, CURLOPT_URL, $this->url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    
        curl_setopt($ch, CURLOPT_USERPWD, "$this->username:$this->password");
    
        //PROPFIND request that lists all requested properties.
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PROPFIND");
        $response = curl_exec($ch);
    
        curl_close($ch);
    

    Export pictures from excel file into jpg using VBA

    New versions of excel have made old answers obsolete. It took a long time to make this, but it does a pretty good job. Note that the maximum image size is limited and the aspect ratio is ever so slightly off, as I was not able to perfectly optimize the reshaping math. Note that I've named one of my worksheets wsTMP, you can replace it with Sheet1 or the like. Takes about 1 second to print the screenshot to target path.

    Option Explicit
    
    Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
    
    Sub weGucciFam()
    
    Dim tmp As Variant, str As String, h As Double, w As Double
    
    Application.PrintCommunication = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual
    Application.ScreenUpdating = False
    If Application.StatusBar = False Then Application.StatusBar = "EVENTS DISABLED"
    
    keybd_event vbKeyMenu, 0, 0, 0 'these do just active window
    keybd_event vbKeySnapshot, 0, 0, 0
    keybd_event vbKeySnapshot, 0, 2, 0
    keybd_event vbKeyMenu, 0, 2, 0 'sendkeys alt+printscreen doesn't work
    wsTMP.Paste
    DoEvents
    Const dw As Double = 1186.56
    Const dh As Double = 755.28
    
    str = "C:\Users\YOURUSERNAMEHERE\Desktop\Screenshot.jpeg"
    w = wsTMP.Shapes(1).Width
    h = wsTMP.Shapes(1).Height
    
    Application.DisplayAlerts = False
    Set tmp = Charts.Add
    On Error Resume Next
    With tmp
        .PageSetup.PaperSize = xlPaper11x17
        .PageSetup.TopMargin = IIf(w > dw, dh - dw * h / w, dh - h) + 28
        .PageSetup.BottomMargin = 0
        .PageSetup.RightMargin = IIf(h > dh, dw - dh * w / h, dw - w) + 36
        .PageSetup.LeftMargin = 0
        .PageSetup.HeaderMargin = 0
        .PageSetup.FooterMargin = 0
        .SeriesCollection(1).Delete
        DoEvents
        .Paste
        DoEvents
        .Export Filename:=str, Filtername:="jpeg"
        .Delete
    End With
    On Error GoTo 0
    Do Until wsTMP.Shapes.Count < 1
        wsTMP.Shapes(1).Delete
    Loop
    
    Application.PrintCommunication = True
    Application.EnableEvents = True
    Application.Calculation = xlCalculationAutomatic
    Application.ScreenUpdating = True
    Application.StatusBar = False
    
    End Sub
    

    MD5 hashing in Android

    The androidsnippets.com code does not work reliably because 0's seem to be cut out of the resulting hash.

    A better implementation is here.

    public static String MD5_Hash(String s) {
        MessageDigest m = null;
    
        try {
                m = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
        }
    
        m.update(s.getBytes(),0,s.length());
        String hash = new BigInteger(1, m.digest()).toString(16);
        return hash;
    }
    

    How to change the output color of echo in Linux

    We can use 24 Bits RGB true colors for both text and background!

     ESC[38;2;?r?;?g?;?b?m  /*Foreground color*/
     ESC[48;2;?r?;?g?;?b?m  /*Background color*/
    

    Example red text and closing tag:

     echo -e "\e[38;2;255;0;0mHello world\e[0m"
    

    Generator:

    _x000D_
    _x000D_
    text.addEventListener("input",update)_x000D_
    back.addEventListener("input",update)_x000D_
    _x000D_
    function update(){_x000D_
      let a = text.value.substr(1).match(/.{1,2}/g)_x000D_
      let b = back.value.substr(1).match(/.{1,2}/g)_x000D_
      out1.textContent = "echo -e \"\\" + `033[38;2;${parseInt(a[0],16)};${parseInt(a[1],16)};${parseInt(a[2],16)}mHello\"`_x000D_
      out2.textContent = "echo -e \"\\" + `033[48;2;${parseInt(b[0],16)};${parseInt(b[1],16)};${parseInt(b[2],16)}mWorld!\"`_x000D_
    }
    _x000D_
    div {padding:1rem;font-size:larger}
    _x000D_
    TEXT COLOR: <input type="color" id="text" value="#23233">_x000D_
    <br><div id="out1"></div>_x000D_
    BACK COLOR: <input type="color" id="back" value="#FFFF00">_x000D_
    <br><div id="out2">
    _x000D_
    _x000D_
    _x000D_

    24-bit: As "true color" graphic cards with 16 to 24 bits of color became common, Xterm,KDE's Konsole, as well as all libvte based terminals (including GNOME Terminal) support 24-bit foreground and background color setting https://en.wikipedia.org/wiki/ANSI_escape_code#24-bit

    Is it safe to use in my scripts?

    Yes! 8 and 16 bits terminals will just display as fallback a color on the range of the available palette, keeping the best contrast, no breakages!


    Also, nobody noticed the usefulness of the ANSI code 7 reversed video.

    It stay readable on any terminal schemes colors, black or white backgrounds, or other fancies palettes, by swapping foreground and background colors.

    Example, for a red background that works everywhere:

    echo -e "\033[31;7mHello world\e[0m";
    

    This is how it looks when changing the terminal built-in schemes:

    enter image description here

    This is the loop script used for the gif.

    for i in {30..49};do echo -e "\033[$i;7mReversed color code $i\e[0m Hello world!";done
    

    See https://en.wikipedia.org/wiki/ANSI_escape_code#SGR_(Select_Graphic_Rendition)_parameters

    What is the difference between char * const and const char *?

    // Some more complex constant variable/pointer declaration.
    // Observing cases when we get error and warning would help
    // understanding it better.
    
    int main(void)
    {
      char ca1[10]= "aaaa"; // char array 1
      char ca2[10]= "bbbb"; // char array 2
    
      char *pca1= ca1;
      char *pca2= ca2;
    
      char const *ccs= pca1;
      char * const csc= pca2;
      ccs[1]='m';  // Bad - error: assignment of read-only location ‘*(ccs + 1u)’
      ccs= csc;    // Good
    
      csc[1]='n';  // Good
      csc= ccs;    // Bad - error: assignment of read-only variable ‘csc’
    
      char const **ccss= &ccs;     // Good
      char const **ccss1= &csc;    // Bad - warning: initialization from incompatible pointer type
    
      char * const *cscs= &csc;    // Good
      char * const *cscs1= &ccs;   // Bad - warning: initialization from incompatible pointer type
    
      char ** const cssc=   &pca1; // Good
      char ** const cssc1=  &ccs;  // Bad - warning: initialization from incompatible pointer type
      char ** const cssc2=  &csc;  // Bad - warning: initialization discards ‘const’
                                   //                qualifier from pointer target type
    
      *ccss[1]= 'x'; // Bad - error: assignment of read-only location ‘**(ccss + 8u)’
      *ccss= ccs;    // Good
      *ccss= csc;    // Good
      ccss= ccss1;   // Good
      ccss= cscs;    // Bad - warning: assignment from incompatible pointer type
    
      *cscs[1]= 'y'; // Good
      *cscs= ccs;    // Bad - error: assignment of read-only location ‘*cscs’
      *cscs= csc;    // Bad - error: assignment of read-only location ‘*cscs’
      cscs= cscs1;   // Good
      cscs= cssc;    // Good
    
      *cssc[1]= 'z'; // Good
      *cssc= ccs;    // Bad - warning: assignment discards ‘const’
                     //                qualifier from pointer target type
      *cssc= csc;    // Good
      *cssc= pca2;   // Good
      cssc= ccss;    // Bad - error: assignment of read-only variable ‘cssc’
      cssc= cscs;    // Bad - error: assignment of read-only variable ‘cssc’
      cssc= cssc1;   // Bad - error: assignment of read-only variable ‘cssc’
    }
    

    Break out of a While...Wend loop

    Another option would be to set a flag variable as a Boolean and then change that value based on your criteria.

    Dim count as Integer 
    Dim flag as Boolean
    
    flag = True
    
    While flag
        count = count + 1 
    
        If count = 10 Then
            'Set the flag to false         '
            flag = false
        End If 
    Wend
    

    Creating a textarea with auto-resize

    For those who want the textarea to be auto resized on both width and height:

    HTML:

    <textarea class='textbox'></textarea>
    <div>
      <span class='tmp_textbox'></span>
    </div>
    

    CSS:

    .textbox,
    .tmp_textbox {
      font-family: 'Arial';
      font-size: 12px;
      resize: none;
      overflow:hidden;
    }
    
    .tmp_textbox {
      display: none;
    }
    

    jQuery:

    $(function(){
      //alert($('.textbox').css('padding'))
      $('.textbox').on('keyup change', checkSize)
      $('.textbox').trigger('keyup')
    
      function checkSize(){
        var str = $(this).val().replace(/\r?\n/g, '<br/>');
        $('.tmp_textbox').html( str )
        console.log($(this).val())
    
        var strArr = str.split('<br/>')
        var row = strArr.length
        $('.textbox').attr('rows', row)
        $('.textbox').width( $('.tmp_textbox').width() + parseInt($('.textbox').css('padding')) * 2 + 10 )
      }
    })
    

    Codepen:

    http://codepen.io/anon/pen/yNpvJJ

    Cheers,

    How to hide element label by element id in CSS?

    If you don't care about IE6 users, use the equality attribute selector.

    label[for="foo"] { display:none; }
    

    Converting of Uri to String

    Uri to String

    Uri uri;
    String stringUri;
    stringUri = uri.toString();
    

    String to Uri

    Uri uri;
    String stringUri;
    uri = Uri.parse(stringUri);
    

    How to remove an element from a list by index

    You can use either del or pop to remove element from list based on index. Pop will print member it is removing from list, while list delete that member without printing it.

    >>> a=[1,2,3,4,5]
    >>> del a[1]
    >>> a
    [1, 3, 4, 5]
    >>> a.pop(1)
     3
    >>> a
    [1, 4, 5]
    >>> 
    

    How to make a JTable non-editable

    You can use a TableModel.

    Define a class like this:

    public class MyModel extends AbstractTableModel{
        //not necessary
    }
    

    actually isCellEditable() is false by default so you may omit it. (see: http://docs.oracle.com/javase/6/docs/api/javax/swing/table/AbstractTableModel.html)

    Then use the setModel() method of your JTable.

    JTable myTable = new JTable();
    myTable.setModel(new MyModel());
    

    Code coverage for Jest built on top of Jasmine

    1. Check the latest Jest (v 0.22): https://github.com/facebook/jest

    2. The Facebook team adds the Istanbul code coverage output as part of the coverage report and you can use it directly.

    3. After executing Jest, you can get a coverage report in the console and under the root folder set by Jest, you will find the coverage report in JSON and HTML format.

    4. FYI, if you install from npm, you might not get the latest version; so try the GitHub first and make sure the coverage is what you need.

    Output in a table format in Java's System.out

    I may be very late for the Answer but here a simple and generic solution

    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.UUID;
    
    public class TableGenerator {
    
        private int PADDING_SIZE = 2;
        private String NEW_LINE = "\n";
        private String TABLE_JOINT_SYMBOL = "+";
        private String TABLE_V_SPLIT_SYMBOL = "|";
        private String TABLE_H_SPLIT_SYMBOL = "-";
    
        public String generateTable(List<String> headersList, List<List<String>> rowsList,int... overRiddenHeaderHeight)
        {
            StringBuilder stringBuilder = new StringBuilder();
    
            int rowHeight = overRiddenHeaderHeight.length > 0 ? overRiddenHeaderHeight[0] : 1; 
    
            Map<Integer,Integer> columnMaxWidthMapping = getMaximumWidhtofTable(headersList, rowsList);
    
            stringBuilder.append(NEW_LINE);
            stringBuilder.append(NEW_LINE);
            createRowLine(stringBuilder, headersList.size(), columnMaxWidthMapping);
            stringBuilder.append(NEW_LINE);
    
    
            for (int headerIndex = 0; headerIndex < headersList.size(); headerIndex++) {
                fillCell(stringBuilder, headersList.get(headerIndex), headerIndex, columnMaxWidthMapping);
            }
    
            stringBuilder.append(NEW_LINE);
    
            createRowLine(stringBuilder, headersList.size(), columnMaxWidthMapping);
    
    
            for (List<String> row : rowsList) {
    
                for (int i = 0; i < rowHeight; i++) {
                    stringBuilder.append(NEW_LINE);
                }
    
                for (int cellIndex = 0; cellIndex < row.size(); cellIndex++) {
                    fillCell(stringBuilder, row.get(cellIndex), cellIndex, columnMaxWidthMapping);
                }
    
            }
    
            stringBuilder.append(NEW_LINE);
            createRowLine(stringBuilder, headersList.size(), columnMaxWidthMapping);
            stringBuilder.append(NEW_LINE);
            stringBuilder.append(NEW_LINE);
    
            return stringBuilder.toString();
        }
    
        private void fillSpace(StringBuilder stringBuilder, int length)
        {
            for (int i = 0; i < length; i++) {
                stringBuilder.append(" ");
            }
        }
    
        private void createRowLine(StringBuilder stringBuilder,int headersListSize, Map<Integer,Integer> columnMaxWidthMapping)
        {
            for (int i = 0; i < headersListSize; i++) {
                if(i == 0)
                {
                    stringBuilder.append(TABLE_JOINT_SYMBOL);   
                }
    
                for (int j = 0; j < columnMaxWidthMapping.get(i) + PADDING_SIZE * 2 ; j++) {
                    stringBuilder.append(TABLE_H_SPLIT_SYMBOL);
                }
                stringBuilder.append(TABLE_JOINT_SYMBOL);
            }
        }
    
    
        private Map<Integer,Integer> getMaximumWidhtofTable(List<String> headersList, List<List<String>> rowsList)
        {
            Map<Integer,Integer> columnMaxWidthMapping = new HashMap<>();
    
            for (int columnIndex = 0; columnIndex < headersList.size(); columnIndex++) {
                columnMaxWidthMapping.put(columnIndex, 0);
            }
    
            for (int columnIndex = 0; columnIndex < headersList.size(); columnIndex++) {
    
                if(headersList.get(columnIndex).length() > columnMaxWidthMapping.get(columnIndex))
                {
                    columnMaxWidthMapping.put(columnIndex, headersList.get(columnIndex).length());
                }
            }
    
    
            for (List<String> row : rowsList) {
    
                for (int columnIndex = 0; columnIndex < row.size(); columnIndex++) {
    
                    if(row.get(columnIndex).length() > columnMaxWidthMapping.get(columnIndex))
                    {
                        columnMaxWidthMapping.put(columnIndex, row.get(columnIndex).length());
                    }
                }
            }
    
            for (int columnIndex = 0; columnIndex < headersList.size(); columnIndex++) {
    
                if(columnMaxWidthMapping.get(columnIndex) % 2 != 0)
                {
                    columnMaxWidthMapping.put(columnIndex, columnMaxWidthMapping.get(columnIndex) + 1);
                }
            }
    
    
            return columnMaxWidthMapping;
        }
    
        private int getOptimumCellPadding(int cellIndex,int datalength,Map<Integer,Integer> columnMaxWidthMapping,int cellPaddingSize)
        {
            if(datalength % 2 != 0)
            {
                datalength++;
            }
    
            if(datalength < columnMaxWidthMapping.get(cellIndex))
            {
                cellPaddingSize = cellPaddingSize + (columnMaxWidthMapping.get(cellIndex) - datalength) / 2;
            }
    
            return cellPaddingSize;
        }
    
        private void fillCell(StringBuilder stringBuilder,String cell,int cellIndex,Map<Integer,Integer> columnMaxWidthMapping)
        {
    
            int cellPaddingSize = getOptimumCellPadding(cellIndex, cell.length(), columnMaxWidthMapping, PADDING_SIZE);
    
            if(cellIndex == 0)
            {
                stringBuilder.append(TABLE_V_SPLIT_SYMBOL); 
            }
    
            fillSpace(stringBuilder, cellPaddingSize);
            stringBuilder.append(cell);
            if(cell.length() % 2 != 0)
            {
                stringBuilder.append(" ");
            }
    
            fillSpace(stringBuilder, cellPaddingSize);
    
            stringBuilder.append(TABLE_V_SPLIT_SYMBOL); 
    
        }
    
        public static void main(String[] args) {
            TableGenerator tableGenerator = new TableGenerator();
    
            List<String> headersList = new ArrayList<>(); 
            headersList.add("Id");
            headersList.add("F-Name");
            headersList.add("L-Name");
            headersList.add("Email");
    
            List<List<String>> rowsList = new ArrayList<>();
    
            for (int i = 0; i < 5; i++) {
                List<String> row = new ArrayList<>(); 
                row.add(UUID.randomUUID().toString());
                row.add(UUID.randomUUID().toString());
                row.add(UUID.randomUUID().toString());
                row.add(UUID.randomUUID().toString());
    
                rowsList.add(row);
            }
    
            System.out.println(tableGenerator.generateTable(headersList, rowsList));
        }
    }
    

    With this kind of Output

    +----------------------------------------+----------------------------------------+----------------------------------------+----------------------------------------+
    |                   Id                   |                F-Name                  |                 L-Name                 |                  Email                 |
    +----------------------------------------+----------------------------------------+----------------------------------------+----------------------------------------+
    |  70a56f25-d42a-499c-83ac-50188c45a0ac  |  aa04285e-c135-46e2-9f90-988bf7796cd0  |  ac495ba7-d3c7-463c-8c24-9ffde67324bc  |  f6b5851b-41e0-4a4e-a237-74f8e0bff9ab  |
    |  6de181ca-919a-4425-a753-78d2de1038ef  |  c4ba5771-ccee-416e-aebd-ef94b07f4fa2  |  365980cb-e23a-4513-a895-77658f130135  |  69e01da1-078e-4934-afb0-5afd6ee166ac  |
    |  f3285f33-5083-4881-a8b4-c8ae10372a6c  |  46df25ed-fa0f-42a4-9181-a0528bc593f6  |  d24016bf-a03f-424d-9a8f-9a7b7388fd85  |  4b976794-aac1-441e-8bd2-78f5ccbbd653  |
    |  ab799acb-a582-45e7-ba2f-806948967e6c  |  d019438d-0a75-48bc-977b-9560de4e033e  |  8cb2ad11-978b-4a67-a87e-439d0a21ef99  |  2f2d9a39-9d95-4a5a-993f-ceedd5ff9953  |
    |  78a68c0a-a824-42e8-b8a8-3bdd8a89e773  |  0f030c1b-2069-4c1a-bf7d-f23d1e291d2a  |  7f647cb4-a22e-46d2-8c96-0c09981773b1  |  0bc944ef-c1a7-4dd1-9eef-915712035a74  |
    +----------------------------------------+----------------------------------------+----------------------------------------+----------------------------------------+
    

    MVC pattern on Android

    According to the explanation that the Xamarin team explained (on the iOS MVC "I know it seems weird, but wait a second"):

    • The model (data or application logic),
    • The view (user interface), and
    • The controller (code behind).

    I can say this:

    The model on Android is simply the parcelable object. The view is the XML layout, and the controller is the (activity + its fragment).

    *This is just my opinion, not from any resource or a book.

    creating charts with angularjs

    To collect more useful resources here:

    As mentioned before D3.js is definitely the best visualization library for charts. To use it in AngularJS I developed angular-chart. It is an easy to use directive which connects D3.js with the AngularJS 2-Way-DataBinding. This way the chart gets automatically updated whenever you change the configuration options and at the same time the charts saves its state (zoom level, ...) to make it available in the AngularJS world.

    Check out the examples to get convinced.

    Determining complexity for recursive functions (Big O notation)

    We can prove it mathematically which is something I was missing in the above answers.

    It can dramatically help you understand how to calculate any method. I recommend reading it from top to bottom to fully understand how to do it:

    1. T(n) = T(n-1) + 1 It means that the time it takes for the method to finish is equal to the same method but with n-1 which is T(n-1) and we now add + 1 because it's the time it takes for the general operations to be completed (except T(n-1)). Now, we are going to find T(n-1) as follow: T(n-1) = T(n-1-1) + 1. It looks like we can now form a function that can give us some sort of repetition so we can fully understand. We will place the right side of T(n-1) = ... instead of T(n-1) inside the method T(n) = ... which will give us: T(n) = T(n-1-1) + 1 + 1 which is T(n) = T(n-2) + 2 or in other words we need to find our missing k: T(n) = T(n-k) + k. The next step is to take n-k and claim that n-k = 1 because at the end of the recursion it will take exactly O(1) when n<=0. From this simple equation we now know that k = n - 1. Let's place k in our final method: T(n) = T(n-k) + k which will give us: T(n) = 1 + n - 1 which is exactly n or O(n).
    2. Is the same as 1. You can test it your self and see that you get O(n).
    3. T(n) = T(n/5) + 1 as before, the time for this method to finish equals to the time the same method but with n/5 which is why it is bounded to T(n/5). Let's find T(n/5) like in 1: T(n/5) = T(n/5/5) + 1 which is T(n/5) = T(n/5^2) + 1. Let's place T(n/5) inside T(n) for the final calculation: T(n) = T(n/5^k) + k. Again as before, n/5^k = 1 which is n = 5^k which is exactly as asking what in power of 5, will give us n, the answer is log5n = k (log of base 5). Let's place our findings in T(n) = T(n/5^k) + k as follow: T(n) = 1 + logn which is O(logn)
    4. T(n) = 2T(n-1) + 1 what we have here is basically the same as before but this time we are invoking the method recursively 2 times thus we multiple it by 2. Let's find T(n-1) = 2T(n-1-1) + 1 which is T(n-1) = 2T(n-2) + 1. Our next place as before, let's place our finding: T(n) = 2(2T(n-2)) + 1 + 1 which is T(n) = 2^2T(n-2) + 2 that gives us T(n) = 2^kT(n-k) + k. Let's find k by claiming that n-k = 1 which is k = n - 1. Let's place k as follow: T(n) = 2^(n-1) + n - 1 which is roughly O(2^n)
    5. T(n) = T(n-5) + n + 1 It's almost the same as 4 but now we add n because we have one for loop. Let's find T(n-5) = T(n-5-5) + n + 1 which is T(n-5) = T(n - 2*5) + n + 1. Let's place it: T(n) = T(n-2*5) + n + n + 1 + 1) which is T(n) = T(n-2*5) + 2n + 2) and for the k: T(n) = T(n-k*5) + kn + k) again: n-5k = 1 which is n = 5k + 1 that is roughly n = k. This will give us: T(n) = T(0) + n^2 + n which is roughly O(n^2).

    I now recommend reading the rest of the answers which now, will give you a better perspective. Good luck winning those big O's :)

    Serialize form data to JSON

    Using Underscore.js:

    function serializeForm($form){
        return _.object(_.map($form.serializeArray(), function(item){return [item.name, item.value]; }));
    }
    

    MySQL - SELECT all columns WHERE one column is DISTINCT

    I had a similar problem, maybe that help someone, for example - table with 3 columns

    SELECT * FROM DataTable WHERE Data_text = 'test' GROUP BY Data_Name ORDER BY Data_Name ASC
    

    or

    SELECT Data_Id, Data_Text, Data_Name FROM DataTable WHERE Data_text = 'test' GROUP BY Data_Name ORDER BY Data_Name ASC
    

    Two ways work for me.

    CodeIgniter - Correct way to link to another page in a view

    <a href="<?php echo site_url('controller/function'); ?>Compose</a>
    
    <a href="<?php echo site_url('controller/function'); ?>Inbox</a>
    
    <a href="<?php echo site_url('controller/function'); ?>Outbox</a>
    
    <a href="<?php echo site_url('controller/function'); ?>logout</a>
    
    <a href="<?php echo site_url('controller/function'); ?>logout</a>
    

    SQL Server - Case Statement

    The query can be written slightly simpler, like this:

    DECLARE @T INT = 2 
    
    SELECT CASE 
             WHEN @T < 1 THEN 'less than one' 
             WHEN @T = 1 THEN 'one' 
             ELSE 'greater than one' 
           END T
    

    Incrementing in C++ - When to use x++ or ++x?

    Scott Meyers tells you to prefer prefix except on those occasions where logic would dictate that postfix is appropriate.

    "More Effective C++" item #6 - that's sufficient authority for me.

    For those who don't own the book, here are the pertinent quotes. From page 32:

    From your days as a C programmer, you may recall that the prefix form of the increment operator is sometimes called "increment and fetch", while the postfix form is often known as "fetch and increment." The two phrases are important to remember, because they all but act as formal specifications...

    And on page 34:

    If you're the kind who worries about efficiency, you probably broke into a sweat when you first saw the postfix increment function. That function has to create a temporary object for its return value and the implementation above also creates an explicit temporary object that has to be constructed and destructed. The prefix increment function has no such temporaries...

    What does collation mean?

    Besides the "accented letters are sorted differently than unaccented ones" in some Western European languages, you must take into account the groups of letters, which sometimes are sorted differently, also.

    Traditionally, in Spanish, "ch" was considered a letter in its own right, same with "ll" (both of which represent a single phoneme), so a list would get sorted like this:

    • caballo
    • cinco
    • coche
    • charco
    • chocolate
    • chueco
    • dado
    • (...)
    • lámpara
    • luego
    • llanta
    • lluvia
    • madera

    Notice all the words starting with single c go together, except words starting with ch which go after them, same with ll-starting words which go after all the words starting with a single l. This is the ordering you'll see in old dictionaries and encyclopedias, sometimes even today by very conservative organizations.

    The Royal Academy of the Language changed this to make it easier for Spanish to be accomodated in the computing world. Nevertheless, ñ is still considered a different letter than n and goes after it, and before o. So this is a correctly ordered list:

    • Namibia
    • número
    • ñandú
    • ñú
    • obra
    • ojo

    By selecting the correct collation, you get all this done for you, automatically :-)

    Set folder browser dialog start location

    In my case, it was an accidental double escaping.

    this works:

    SelectedPath = @"C:\Program Files\My Company\My product";
    

    this doesn't:

    SelectedPath = @"C:\\Program Files\\My Company\\My product";
    

    How to change the author and committer name and e-mail of multiple commits in Git?

    For those under windows, you could also use the git-rocket-filter tool.

    From the documentation:

    Change commit author name and email:

    git-rocket-filter --branch TestBranch --commit-filter '
        if (commit.AuthorName.Contains("Jim")) {   
            commit.AuthorName = "Paul"; 
            commit.AuthorEmail = "[email protected]"; 
        }
    

    Changing factor levels with dplyr mutate

    With the forcats package from the tidyverse this is easy, too.

    mutate(dat, x = fct_recode(x, "B" = "A"))
    

    Text that shows an underline on hover

    <span class="txt">Some Text</span>
    
    .txt:hover {
        text-decoration: underline;
    }
    

    Can't create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog

    I had a similar issue but from reading this question I figured I could run on UI thread:

    YourActivity.this.runOnUiThread(new Runnable() {
        public void run() {
            alertDialog.show();
        }
    });
    

    Seems to do the trick for me.

    UPDATE with CASE and IN - Oracle

    Got a solution that runs. Don't know if it is optimal though. What I do is to split the string according to http://blogs.oracle.com/aramamoo/2010/05/how_to_split_comma_separated_string_and_pass_to_in_clause_of_select_statement.html

    Using:
    select regexp_substr(' 1, 2 , 3 ','[^,]+', 1, level) from dual
    connect by regexp_substr('1 , 2 , 3 ', '[^,]+', 1, level) is not null;

    So my final code looks like this ($bp_gr1' are strings like 1,2,3):

    UPDATE TAB1
    SET    BUDGPOST_GR1 =
              CASE
                 WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( '$BP_GR1',
                                                                '[^,]+',
                                                                1,
                                                                LEVEL )
                                     FROM       DUAL
                                     CONNECT BY REGEXP_SUBSTR ( '$BP_GR1',
                                                                '[^,]+',
                                                                1,
                                                                LEVEL )
                                                   IS NOT NULL) )
                 THEN
                    'BP_GR1'
                 WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( ' $BP_GR2',
                                                                '[^,]+',
                                                                1,
                                                                LEVEL )
                                     FROM       DUAL
                                     CONNECT BY REGEXP_SUBSTR ( '$BP_GR2',
                                                                '[^,]+',
                                                                1,
                                                                LEVEL )
                                                   IS NOT NULL) )
                 THEN
                    'BP_GR2'
                 WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( ' $BP_GR3',
                                                                '[^,]+',
                                                                1,
                                                                LEVEL )
                                     FROM       DUAL
                                     CONNECT BY REGEXP_SUBSTR ( '$BP_GR3',
                                                                '[^,]+',
                                                                1,
                                                                LEVEL )
                                                   IS NOT NULL) )
                 THEN
                    'BP_GR3'
                 WHEN ( BUDGPOST IN (SELECT     REGEXP_SUBSTR ( '$BP_GR4',
                                                                '[^,]+',
                                                                1,
                                                                LEVEL )
                                     FROM       DUAL
                                     CONNECT BY REGEXP_SUBSTR ( '$BP_GR4',
                                                                '[^,]+',
                                                                1,
                                                                LEVEL )
                                                   IS NOT NULL) )
                 THEN
                    'BP_GR4'
                 ELSE
                    'SAKNAR BUDGETGRUPP'
              END;
    

    Is there a way to make it run faster?

    How to convert float number to Binary?

    void transfer(double x) {
    unsigned long long* p = (unsigned long long*)&x;
    for (int i = sizeof(unsigned long long) * 8 - 1; i >= 0; i--) {cout<< ((*p) >>i & 1);}}
    

    How to get current route in Symfony 2?

    To get the current route based on the URL (more reliable in case of forwards):

    public function getCurrentRoute(Request $request)
    {
        $pathInfo    = $request->getPathInfo();
        $routeParams = $this->router->match($pathInfo);
        $routeName   = $routeParams['_route'];
        if (substr($routeName, 0, 1) === '_') {
            return;
        }
        unset($routeParams['_route']);
    
        $data = [
            'name'   => $routeName,
            'params' => $routeParams,
        ];
    
        return $data;
    }
    

    Does JSON syntax allow duplicate keys in an object?

    According to RFC-7159, the current standard for JSON published by the Internet Engineering Task Force (IETF), states "The names within an object SHOULD be unique". However, according to RFC-2119 which defines the terminology used in IETF documents, the word "should" in fact means "... there may exist valid reasons in particular circumstances to ignore a particular item, but the full implications must be understood and carefully weighed before choosing a different course." What this essentially means is that while having unique keys is recommended, it is not a must. We can have duplicate keys in a JSON object, and it would still be valid.

    From practical application, I have seen the value from the last key is considered when duplicate keys are found in a JSON.

    How to identify which columns are not "NA" per row in a matrix?

    Try:

    which( !is.na(p), arr.ind=TRUE)
    

    Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

    > apply(p, 1, function(x) which(!is.na(x)) )
    [[1]]
    [1] 2 3
    
    [[2]]
    [1] 4 7
    
    [[3]]
    integer(0)
    
    [[4]]
    [1] 5
    
    [[5]]
    integer(0)
    

    Or even with smushing together with paste:

    lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
    

    The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

    > which( !is.na(p), arr.ind=TRUE)
         row col
    [1,]   1   2
    [2,]   1   3
    [3,]   2   4
    [4,]   4   5
    [5,]   2   7
    

    Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

    > which( !is.na(p) )
    [1]  6 11 17 24 32
    

    How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

    Below is an action method that returns a json string (cameCase) by serializing an array of objects.

    public string GetSerializedCourseVms()
        {
            var courses = new[]
            {
                new CourseVm{Number = "CREA101", Name = "Care of Magical Creatures", Instructor ="Rubeus Hagrid"},
                new CourseVm{Number = "DARK502", Name = "Defence against dark arts", Instructor ="Severus Snape"},
                new CourseVm{Number = "TRAN201", Name = "Transfiguration", Instructor ="Minerva McGonal"}
            };
            var camelCaseFormatter = new JsonSerializerSettings();
            camelCaseFormatter.ContractResolver = new CamelCasePropertyNamesContractResolver();
            return JsonConvert.SerializeObject(courses, camelCaseFormatter);
        }
    

    Note the JsonSerializerSettings instance passed as the second parameter. That's what makes the camelCase happen.

    Fastest way to duplicate an array in JavaScript - slice vs. 'for' loop

    ECMAScript 2015 way with the Spread operator:

    Basic examples:

    var copyOfOldArray = [...oldArray]
    var twoArraysBecomeOne = [...firstArray, ..seccondArray]
    

    Try in the browser console:

    var oldArray = [1, 2, 3]
    var copyOfOldArray = [...oldArray]
    console.log(oldArray)
    console.log(copyOfOldArray)
    
    var firstArray = [5, 6, 7]
    var seccondArray = ["a", "b", "c"]
    var twoArraysBecomOne = [...firstArray, ...seccondArray]
    console.log(twoArraysBecomOne);
    

    References

    Biggest advantage to using ASP.Net MVC vs web forms

    You don't feel bad about using 'non post-back controls' anymore - and figuring how to smush them into a traditional asp.net environment.

    This means that modern (free to use) javascript controls such this or this or this can all be used without that trying to fit a round peg in a square hole feel.

    Matrix multiplication using arrays

    static int b[][]={{21,21},{22,22}};
    
    static int a[][] ={{1,1},{2,2}};
    
    public static void mul(){
        int c[][] = new int[2][2];
    
        for(int i=0;i<b.length;i++){
            for(int j=0;j<b.length;j++){
                c[i][j] =0;
            }   
        }
    
        for(int i=0;i<a.length;i++){
            for(int j=0;j<b.length;j++){
                for(int k=0;k<b.length;k++){
                c[i][j]= c[i][j] +(a[i][k] * b[k][j]);
                }
            }
        }
    
        for(int i=0;i<c.length;i++){
            for(int j=0;j<c.length;j++){
                System.out.print(c[i][j]);
            }   
            System.out.println("\n");
        }
    }
    

    How to import an excel file in to a MySQL database

    1. Export it into some text format. The easiest will probably be a tab-delimited version, but CSV can work as well.

    2. Use the load data capability. See http://dev.mysql.com/doc/refman/5.1/en/load-data.html

    3. Look half way down the page, as it will gives a good example for tab separated data:

      FIELDS TERMINATED BY '\t' ENCLOSED BY '' ESCAPED BY '\'

    4. Check your data. Sometimes quoting or escaping has problems, and you need to adjust your source, import command-- or it may just be easier to post-process via SQL.

    Batch file for PuTTY/PSFTP file transfer automation

    You need to store the psftp script (lines from open to bye) into a separate file and pass that to psftp using -b switch:

    cd "C:\Program Files (x86)\PuTTY"
    psftp -b "C:\path\to\script\script.txt"
    

    Reference:
    https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-option-b


    EDIT: For username+password: As you cannot use psftp commands in a batch file, for the same reason, you cannot specify the username and the password as psftp commands. These are inputs to the open command. While you can specify the username with the open command (open <user>@<IP>), you cannot specify the password this way. This can be done on a psftp command line only. Then it's probably cleaner to do all on the command-line:

    cd "C:\Program Files (x86)\PuTTY"
    psftp -b script.txt <user>@<IP> -pw <PW>
    

    And remove the open, <user> and <PW> lines from your script.txt.

    Reference:
    https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-starting
    https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-pw


    What you are doing atm is that you run psftp without any parameter or commands. Once you exit it (like by typing bye), your batch file continues trying to run open command (and others), what Windows shell obviously does not understand.


    If you really want to keep everything in one file (the batch file), you can write commands to psftp standard input, like:

    (
        echo cd ...
        echo lcd ...
        echo put log.sh
    ) | psftp -b script.txt <user>@<IP> -pw <PW>
    

    How to skip over an element in .map()?

    if it null or undefined in one line ES5/ES6

    //will return array of src 
    images.filter(p=>!p.src).map(p=>p.src);//p = property
    
    
    //in your condition
    images.filter(p=>p.src.split('.').pop() !== "json").map(p=>p.src);
    

    Use '=' or LIKE to compare strings in SQL?

    To see the performance difference, try this:

    SELECT count(*)
    FROM master..sysobjects as A
    JOIN tempdb..sysobjects as B
    on A.name = B.name
    
    SELECT count(*)
    FROM master..sysobjects as A
    JOIN tempdb..sysobjects as B
    on A.name LIKE B.name
    

    Comparing strings with '=' is much faster.

    Error: No module named psycopg2.extensions

    In python 3.4, while in a virtual environment, make sure you have the build dependencies first:

    sudo apt-get build-dep python3-psycopg2
    

    Then install it:

    pip install psycopg2 
    

    Is there a css cross-browser value for "width: -moz-fit-content;"?

    Is there a single declaration that fixes this for Webkit, Gecko, and Blink? No. However, there is a cross-browser solution by specifying multiple width property values that correspond to each layout engine's convention.

    .mydiv {  
      ...
      width: intrinsic;           /* Safari/WebKit uses a non-standard name */
      width: -moz-max-content;    /* Firefox/Gecko */
      width: -webkit-max-content; /* Chrome */
      ...
    }
    

    Adapted from: MDN

    How to programmatically connect a client to a WCF service?

    You'll have to use the ChannelFactory class.

    Here's an example:

    var myBinding = new BasicHttpBinding();
    var myEndpoint = new EndpointAddress("http://localhost/myservice");
    using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
    {
        IMyService client = null;
    
        try
        {
            client = myChannelFactory.CreateChannel();
            client.MyServiceOperation();
            ((ICommunicationObject)client).Close();
            myChannelFactory.Close();
        }
        catch
        {
            (client as ICommunicationObject)?.Abort();
        }
    }
    

    Related resources:

    How to make an element width: 100% minus padding?

    For me, using margin:15px;padding:10px 0 15px 23px;width:100%, the result was this:

    enter image description here

    The solution for me was to use width:auto instead of width:100%. My new code was:

    margin:15px;padding:10px 0 15px 23px;width:auto. Then the element aligned properly:

    enter image description here