Programs & Examples On #Objdump

objdump is a program for displaying various information about object files. For instance, it can be used as a disassembler to view executable in assembly form. It is part of the GNU Binutils for fine-grained control over executable and other binary data.

Switching between GCC and Clang/LLVM using CMake

CMake honors the environment variables CC and CXX upon detecting the C and C++ compiler to use:

$ export CC=/usr/bin/clang
$ export CXX=/usr/bin/clang++
$ cmake ..
-- The C compiler identification is Clang
-- The CXX compiler identification is Clang

The compiler specific flags can be overridden by putting them into a make override file and pointing the CMAKE_USER_MAKE_RULES_OVERRIDE variable to it. Create a file ~/ClangOverrides.txt with the following contents:

SET (CMAKE_C_FLAGS_INIT                "-Wall -std=c99")
SET (CMAKE_C_FLAGS_DEBUG_INIT          "-g")
SET (CMAKE_C_FLAGS_MINSIZEREL_INIT     "-Os -DNDEBUG")
SET (CMAKE_C_FLAGS_RELEASE_INIT        "-O3 -DNDEBUG")
SET (CMAKE_C_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")

SET (CMAKE_CXX_FLAGS_INIT                "-Wall")
SET (CMAKE_CXX_FLAGS_DEBUG_INIT          "-g")
SET (CMAKE_CXX_FLAGS_MINSIZEREL_INIT     "-Os -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELEASE_INIT        "-O3 -DNDEBUG")
SET (CMAKE_CXX_FLAGS_RELWITHDEBINFO_INIT "-O2 -g")

The suffix _INIT will make CMake initialize the corresponding *_FLAGS variable with the given value. Then invoke cmake in the following way:

$ cmake -DCMAKE_USER_MAKE_RULES_OVERRIDE=~/ClangOverrides.txt ..

Finally to force the use of the LLVM binutils, set the internal variable _CMAKE_TOOLCHAIN_PREFIX. This variable is honored by the CMakeFindBinUtils module:

$ cmake -D_CMAKE_TOOLCHAIN_PREFIX=llvm- ..

Putting this all together you can write a shell wrapper which sets up the environment variables CC and CXX and then invokes cmake with the mentioned variable overrides.

Also see this CMake FAQ on make override files.

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

Instead of gdb, run gdbtui. Or run gdb with the -tui switch. Or press C-x C-a after entering gdb. Now you're in GDB's TUI mode.

Enter layout asm to make the upper window display assembly -- this will automatically follow your instruction pointer, although you can also change frames or scroll around while debugging. Press C-x s to enter SingleKey mode, where run continue up down finish etc. are abbreviated to a single key, allowing you to walk through your program very quickly.

   +---------------------------------------------------------------------------+
B+>|0x402670 <main>         push   %r15                                        |
   |0x402672 <main+2>       mov    %edi,%r15d                                  |
   |0x402675 <main+5>       push   %r14                                        |
   |0x402677 <main+7>       push   %r13                                        |
   |0x402679 <main+9>       mov    %rsi,%r13                                   |
   |0x40267c <main+12>      push   %r12                                        |
   |0x40267e <main+14>      push   %rbp                                        |
   |0x40267f <main+15>      push   %rbx                                        |
   |0x402680 <main+16>      sub    $0x438,%rsp                                 |
   |0x402687 <main+23>      mov    (%rsi),%rdi                                 |
   |0x40268a <main+26>      movq   $0x402a10,0x400(%rsp)                       |
   |0x402696 <main+38>      movq   $0x0,0x408(%rsp)                            |
   |0x4026a2 <main+50>      movq   $0x402510,0x410(%rsp)                       |
   +---------------------------------------------------------------------------+
child process 21518 In: main                            Line: ??   PC: 0x402670
(gdb) file /opt/j64-602/bin/jconsole
Reading symbols from /opt/j64-602/bin/jconsole...done.
(no debugging symbols found)...done.
(gdb) layout asm
(gdb) start
(gdb)

Command line tool to dump Windows DLL version?

For some DLLs I found version info manually with objdump in .rsrc. With objdump -s -j .rsrc zlib1.dll:

zlib1.dll:     file format pei-x86-64

Contents of section .rsrc:
 62e9e000 00000000 00000000 00000000 00000100  ................
 62e9e010 10000000 18000080 00000000 00000000  ................
 62e9e020 00000000 00000100 01000000 30000080  ............0...
 62e9e030 00000000 00000000 00000000 00000100  ................
 62e9e040 09040000 48000000 58e00100 34030000  ....H...X...4...
 62e9e050 00000000 00000000 34033400 00005600  ........4.4...V.
 62e9e060 53005f00 56004500 52005300 49004f00  S._.V.E.R.S.I.O.
 62e9e070 4e005f00 49004e00 46004f00 00000000  N._.I.N.F.O.....
 62e9e080 bd04effe 00000100 02000100 00000b00  ................
 62e9e090 02000100 00000b00 3f000000 00000000  ........?.......
 62e9e0a0 04000000 02000000 00000000 00000000  ................
 62e9e0b0 00000000 94020000 01005300 74007200  ..........S.t.r.
 62e9e0c0 69006e00 67004600 69006c00 65004900  i.n.g.F.i.l.e.I.
 62e9e0d0 6e006600 6f000000 70020000 01003000  n.f.o...p.....0.
 62e9e0e0 34003000 39003000 34004500 34000000  4.0.9.0.4.E.4...
 62e9e0f0 64001e00 01004600 69006c00 65004400  d.....F.i.l.e.D.
 62e9e100 65007300 63007200 69007000 74006900  e.s.c.r.i.p.t.i.
 62e9e110 6f006e00 00000000 7a006c00 69006200  o.n.....z.l.i.b.
 62e9e120 20006400 61007400 61002000 63006f00   .d.a.t.a. .c.o.
 62e9e130 6d007000 72006500 73007300 69006f00  m.p.r.e.s.s.i.o.
 62e9e140 6e002000 6c006900 62007200 61007200  n. .l.i.b.r.a.r.
 62e9e150 79000000 2e000700 01004600 69006c00  y.........F.i.l.
 62e9e160 65005600 65007200 73006900 6f006e00  e.V.e.r.s.i.o.n.
 62e9e170 00000000 31002e00 32002e00 31003100  ....1...2...1.1.
 62e9e180 00000000 34000a00 01004900 6e007400  ....4.....I.n.t.
 62e9e190 65007200 6e006100 6c004e00 61006d00  e.r.n.a.l.N.a.m.
 62e9e1a0 65000000 7a006c00 69006200 31002e00  e...z.l.i.b.1...
 62e9e1b0 64006c00 6c000000 7c002c00 01004c00  d.l.l...|.,...L.
 62e9e1c0 65006700 61006c00 43006f00 70007900  e.g.a.l.C.o.p.y.
 62e9e1d0 72006900 67006800 74000000 28004300  r.i.g.h.t...(.C.
 62e9e1e0 29002000 31003900 39003500 2d003200  ). .1.9.9.5.-.2.
 62e9e1f0 30003100 37002000 4a006500 61006e00  0.1.7. .J.e.a.n.
 62e9e200 2d006c00 6f007500 70002000 47006100  -.l.o.u.p. .G.a.
 62e9e210 69006c00 6c007900 20002600 20004d00  i.l.l.y. .&. .M.
 62e9e220 61007200 6b002000 41006400 6c006500  a.r.k. .A.d.l.e.
 62e9e230 72000000 3c000a00 01004f00 72006900  r...<.....O.r.i.
 62e9e240 67006900 6e006100 6c004600 69006c00  g.i.n.a.l.F.i.l.
 62e9e250 65006e00 61006d00 65000000 7a006c00  e.n.a.m.e...z.l.
 62e9e260 69006200 31002e00 64006c00 6c000000  i.b.1...d.l.l...
 62e9e270 2a000500 01005000 72006f00 64007500  *.....P.r.o.d.u.
 62e9e280 63007400 4e006100 6d006500 00000000  c.t.N.a.m.e.....
 62e9e290 7a006c00 69006200 00000000 32000700  z.l.i.b.....2...
 62e9e2a0 01005000 72006f00 64007500 63007400  ..P.r.o.d.u.c.t.
 62e9e2b0 56006500 72007300 69006f00 6e000000  V.e.r.s.i.o.n...
 62e9e2c0 31002e00 32002e00 31003100 00000000  1...2...1.1.....
 62e9e2d0 78003000 01004300 6f006d00 6d006500  x.0...C.o.m.m.e.
 62e9e2e0 6e007400 73000000 46006f00 72002000  n.t.s...F.o.r. .
 62e9e2f0 6d006f00 72006500 20006900 6e006600  m.o.r.e. .i.n.f.
 62e9e300 6f007200 6d006100 74006900 6f006e00  o.r.m.a.t.i.o.n.
 62e9e310 20007600 69007300 69007400 20006800   .v.i.s.i.t. .h.
 62e9e320 74007400 70003a00 2f002f00 77007700  t.t.p.:././.w.w.
 62e9e330 77002e00 7a006c00 69006200 2e006e00  w...z.l.i.b...n.
 62e9e340 65007400 2f000000 44000000 01005600  e.t./...D.....V.
 62e9e350 61007200 46006900 6c006500 49006e00  a.r.F.i.l.e.I.n.
 62e9e360 66006f00 00000000 24000400 00005400  f.o.....$.....T.
 62e9e370 72006100 6e007300 6c006100 74006900  r.a.n.s.l.a.t.i.
 62e9e380 6f006e00 00000000 0904e404 00000000  o.n.............

How to set a bitmap from resource

If the resource is showing and is a view, you can also capture it. Like a screenshot:

View rootView = ((View) findViewById(R.id.yourView)).getRootView();
rootView.setDrawingCacheEnabled(true);
rootView.layout(0, 0, rootView.getWidth(), rootView.getHeight());
rootView.buildDrawingCache();

Bitmap bm = Bitmap.createBitmap(rootView.getDrawingCache());

rootView.setDrawingCacheEnabled(false);

This actually grabs the whole layout but you can alter as you wish.

How do I code my submit button go to an email address

There are several ways to do an email from HTML. Typically you see people doing a mailto like so:

<a href="mailto:[email protected]">Click to email</a>

But if you are doing it from a button you may want to look into a javascript solution.

Object spread vs. Object.assign

Other answers are old, could not get a good answer.
Below example is for object literals, helps how both can complement each other, and how it cannot complement each other (therefore difference):

var obj1 = { a: 1,  b: { b1: 1, b2: 'b2value', b3: 'b3value' } };

// overwrite parts of b key
var obj2 = {
      b: {
        ...obj1.b,
        b1: 2
      }
};
var res2 = Object.assign({}, obj1, obj2); // b2,b3 keys still exist
document.write('res2: ', JSON.stringify (res2), '<br>');
// Output:
// res2: {"a":1,"b":{"b1":2,"b2":"b2value","b3":"b3value"}}  // NOTE: b2,b3 still exists

// overwrite whole of b key
var obj3 = {
      b: {
        b1: 2
      }
};
var res3 = Object.assign({}, obj1, obj3); // b2,b3 keys are lost
document.write('res3: ', JSON.stringify (res3), '<br>');
// Output:
  // res3: {"a":1,"b":{"b1":2}}  // NOTE: b2,b3 values are lost

Several more small examples here, also for array & object:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

How can I open a .db file generated by eclipse(android) form DDMS-->File explorer-->data--->data-->packagename-->database?

Download this Sqlite manager its the easiest one to use Sqlite manager

and drag and drop your fetched file on its running instance

only drawback of this Sqlite Manager it stop responding if you run some SQL statement that has Syntax Error in it.

So i Use Firefox Plugin Side by side also which you can find at FireFox addons

how to use html2canvas and jspdf to export to pdf in a proper and simple way

Changing this line:

var doc = new jsPDF('L', 'px', [w, h]);
var doc = new jsPDF('L', 'pt', [w, h]);

To fix the dimensions.

"Register" an .exe so you can run it from any command line in Windows

You need to make sure that the exe is in a folder that's on the PATH environment variable.

You can do this by either installing it into a folder that's already on the PATH or by adding your folder to the PATH.

You can have your installer do this - but you will need to restart the machine to make sure it gets picked up.

Check if all elements in a list are identical

Doubt this is the "most Pythonic", but something like:

>>> falseList = [1,2,3,4]
>>> trueList = [1, 1, 1]
>>> 
>>> def testList(list):
...   for item in list[1:]:
...     if item != list[0]:
...       return False
...   return True
... 
>>> testList(falseList)
False
>>> testList(trueList)
True

would do the trick.

Is there a way to represent a directory tree in a Github README.md?

The best way to do this is to surround your tree in the triple backticks to denote a code block. For more info, see the markdown docs: http://daringfireball.net/projects/markdown/syntax#code

What does 'git remote add upstream' help achieve?

The wiki is talking from a forked repo point of view. You have access to pull and push from origin, which will be your fork of the main diaspora repo. To pull in changes from this main repo, you add a remote, "upstream" in your local repo, pointing to this original and pull from it.

So "origin" is a clone of your fork repo, from which you push and pull. "Upstream" is a name for the main repo, from where you pull and keep a clone of your fork updated, but you don't have push access to it.

The import android.support cannot be resolved

I followed the instructions above by Gene in Android Studio 1.5.1 but it added this to my build.gradle file:

compile 'platforms:android:android-support-v4:23.1.1'

so I changed it to:

compile 'com.android.support:support-v4:23.1.1'

And it started working.

The localhost page isn’t working localhost is currently unable to handle this request. HTTP ERROR 500

If you are using the codeigniter framework and are testing the project on a localhost, open the main Index.php file of your project folder and find this code:

define('ENVIRONMENT', 'production');

Change it to

define ('ENVIRONMENT', 'development');

Because same this ENVIRONMENT is in your database.php file under config folder. like this:

 'db_debug' => (ENVIRONMENT! == 'development')

So the environment should be the same in both places and problem will be solved.

make div's height expand with its content

Try this: overflow: auto;

It worked for my problem..

spring data jpa @query and pageable

Please reference :Spring Data JPA @Query, if you are using Spring Data JPA version 2.0.4 and later. Sample like below:

@Query(value = "SELECT u FROM User u ORDER BY id")
Page<User> findAllUsersWithPagination(Pageable pageable);

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

The return value def __unicode __ should be similar to the return value of the related models (tables) for correct viewing of "some_field" in django admin panel. You can also use:

def __str__(self):
    return self.some_field

How do I turn off Oracle password expiration?

As the other answers state, changing the user's profile (e.g. the 'DEFAULT' profile) appropriately will lead to passwords, that once set, will never expire.

However, as one commenter points out, passwords set under the profile's old values may already be expired, and (if after the profile's specified grace period) the account locked.

The solution for expired passwords with locked accounts (as provided in an answering comment) is to use one version of the ALTER USER command:

ALTER USER xyz_user ACCOUNT UNLOCK;

However the unlock command only works for accounts where the account is actually locked, but not for those accounts that are in the grace period, i.e. where the password is expired but the account is not yet locked. For these accounts the password must be reset with another version of the ALTER USER command:

ALTER USER xyz_user IDENTIFIED BY new_password;

Below is a little SQL*Plus script that a privileged user (e.g. user 'SYS') can use to reset a user's password to the current existing hashed value stored in the database.

EDIT: Older versions of Oracle store the password or password-hash in the pword column, newer versions of Oracle store the password-hash in the spare4 column. Script below changed to collect the pword and spare4 columns, but to use the spare4 column to reset the user's account; modify as needed.

REM Tell SQL*Plus to show before and after versions of variable substitutions.
SET VERIFY ON
SHOW VERIFY

REM Tell SQL*Plus to use the ampersand '&' to indicate variables in substitution/expansion.
SET DEFINE '&'
SHOW DEFINE

REM Specify in a SQL*Plus variable the account to 'reset'.
REM Note that user names are case sensitive in recent versions of Oracle.
REM DEFINE USER_NAME = 'xyz_user'

REM Show the status of the account before reset.
SELECT
  ACCOUNT_STATUS,
  TO_CHAR(LOCK_DATE, 'YYYY-MM-DD HH24:MI:SS') AS LOCK_DATE,
  TO_CHAR(EXPIRY_DATE, 'YYYY-MM-DD HH24:MI:SS') AS EXPIRY_DATE
FROM
  DBA_USERS
WHERE
  USERNAME = '&USER_NAME';

REM Create SQL*Plus variable to hold the existing values of the password and spare4 columns.
DEFINE OLD_SPARE4 = ""
DEFINE OLD_PASSWORD = ""

REM Tell SQL*Plus where to store the values to be selected with SQL.
REM Note that the password hash value is stored in spare4 column in recent versions of Oracle,
REM   and in the password column in older versions of Oracle.
COLUMN SPARE4HASH NEW_VALUE OLD_SPARE4
COLUMN PWORDHASH NEW_VALUE OLD_PASSWORD

REM Select the old spare4 and password columns as delimited strings 
SELECT 
  '''' || SPARE4 || '''' AS SPARE4HASH,
  '''' || PASSWORD || '''' AS PWORDHASH
FROM 
  SYS.USER$ 
WHERE 
  NAME = '&USER_NAME';

REM Show the contents of the SQL*Plus variables
DEFINE OLD_SPARE4
DEFINE OLD_PASSWORD

REM Reset the password - Older versions of Oracle (e.g. Oracle 10g and older) 
REM ALTER USER &USER_NAME IDENTIFIED BY VALUES &OLD_PASSWORD;

REM Reset the password - Newer versions of Oracle (e.g. Oracle 11g and newer) 
ALTER USER &USER_NAME IDENTIFIED BY VALUES &OLD_SPARE4;

REM Show the status of the account after reset
SELECT
  ACCOUNT_STATUS,
  TO_CHAR(LOCK_DATE, 'YYYY-MM-DD HH24:MI:SS') AS LOCK_DATE,
  TO_CHAR(EXPIRY_DATE, 'YYYY-MM-DD HH24:MI:SS') AS EXPIRY_DATE
FROM
  DBA_USERS
WHERE
  USERNAME = '&USER_NAME';

Perl regular expression (using a variable as a search string with Perl operator characters included)

Use the quotemeta function:

$text_to_search = "example text with [foo] and more";
$search_string = quotemeta "[foo]";

print "wee" if ($text_to_search =~ /$search_string/);

Insert/Update/Delete with function in SQL Server

Functions are not meant to be used that way, if you wish to perform data change you can just create a Stored Proc for that.

How can I strip all punctuation from a string in JavaScript using regex?

If you want to remove specific punctuation from a string, it will probably be best to explicitly remove exactly what you want like

replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"")

Doing the above still doesn't return the string as you have specified it. If you want to remove any extra spaces that were left over from removing crazy punctuation, then you are going to want to do something like

replace(/\s{2,}/g," ");

My full example:

var s = "This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation";
var punctuationless = s.replace(/[.,\/#!$%\^&\*;:{}=\-_`~()]/g,"");
var finalString = punctuationless.replace(/\s{2,}/g," ");

Results of running code in firebug console:

alt text

How to convert xml into array in php?

$array = json_decode(json_encode((array)simplexml_load_string($xml)),true);

How to set fake GPS location on IOS real device

Of course ios7 prohibits creating fake locations on real device.
For testing purpose there are two approches:
1) while device is connected to xcode, use the simulator and let it play a gpx track.

2) for real world testing, not connected to simu, one possibility is that your app, has a special modus built in, where you set it to "playback" mode. In that mode the app has to create the locations itself, using a timer of 1s, and creating a new CLLocation object.

3) A third possibility is described here: https://blackpixel.com/writing/2013/05/simulating-locations-with-xcode.html

How to get a list of properties with a given attribute?

The solution I end up using most is based off of Tomas Petricek's answer. I usually want to do something with both the attribute and property.

var props = from p in this.GetType().GetProperties()
            let attr = p.GetCustomAttributes(typeof(MyAttribute), true)
            where attr.Length == 1
            select new { Property = p, Attribute = attr.First() as MyAttribute};

When and where to use GetType() or typeof()?

typeof is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType is called on an object at runtime. In both cases the result is an object of the type System.Type containing meta-information on a type.

Example where compile-time and run-time types are equal

string s = "hello";

Type t1 = typeof(string);
Type t2 = s.GetType();

t1 == t2 ==> true

Example where compile-time and run-time types are different

object obj = "hello";

Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType();  // ==> string!

t1 == t2 ==> false

i.e., the compile time type (static type) of the variable obj is not the same as the runtime type of the object referenced by obj.


Testing types

If, however, you only want to know whether mycontrol is a TextBox then you can simply test

if (mycontrol is TextBox)

Note that this is not completely equivalent to

if (mycontrol.GetType() == typeof(TextBox))    

because mycontrol could have a type that is derived from TextBox. In that case the first comparison yields true and the second false! The first and easier variant is OK in most cases, since a control derived from TextBox inherits everything that TextBox has, probably adds more to it and is therefore assignment compatible to TextBox.

public class MySpecializedTextBox : TextBox
{
}

MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox)       ==> true

if (specialized.GetType() == typeof(TextBox))        ==> false

Casting

If you have the following test followed by a cast and T is nullable ...

if (obj is T) {
    T x = (T)obj; // The casting tests, whether obj is T again!
    ...
}

... you can change it to ...

T x = obj as T;
if (x != null) {
    ...
}

Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as operator followed by a test for null is more performing.

Starting with C# 7.0 you can simplify the code by using pattern matching:

if (obj is T t) {
    // t is a variable of type T having a non-null value.
    ...
}

Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:

if (o is int? ni) ===> does NOT compile!

This is because either the value is null or it is an int. This works for int? o as well as for object o = new Nullable<int>(x);:

if (o is int i) ===> OK!

I like it, because it eliminates the need to access the Nullable<T>.Value property.

How to allow remote access to my WAMP server for Mobile(Android)

I assume you are using windows. Open the command prompt and type ipconfig and find out your local address (on your pc) it should look something like 192.168.1.13 or 192.168.0.5 where the end digit is the one that changes. It should be next to IPv4 Address.

If your WAMP does not use virtual hosts the next step is to enter that IP address on your phones browser ie http://192.168.1.13 If you have a virtual host then you will need root to edit the hosts file.

If you want to test the responsiveness / mobile design of your website you can change your user agent in chrome or other browsers to mimic a mobile.

See http://googlesystem.blogspot.co.uk/2011/12/changing-user-agent-new-google-chrome.html.

Edit: Chrome dev tools now has a mobile debug tool where you can change the size of the viewport, spoof user agents, connections (4G, 3G etc).

If you get forbidden access then see this question WAMP error: Forbidden You don't have permission to access /phpmyadmin/ on this server. Basically, change the occurrances of deny,allow to allow,deny in the httpd.conf file. You can access this by the WAMP menu.

To eliminate possible causes of the issue for now set your config file to

<Directory />
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    <RequireAll>
        Require all granted
    </RequireAll>
</Directory>

As thatis working for my windows PC, if you have the directory config block as well change that also to allow all.

Config file that fixed the problem:

https://gist.github.com/samvaughton/6790739

Problem was that the /www apache directory config block still had deny set as default and only allowed from localhost.

Show a PDF files in users browser via PHP/Perl

You could modify a PDF renderer such as xpdf or evince to render into a graphics image on your server, and then deliver the image to the user. This is how Google's quick view of PDF files works, they render it locally, then deliver images to the user. No downloaded PDF file, and the source is pretty well obscured. :)

Find and Replace Inside a Text File from a Bash Command

Be careful if you replace URLs with "/" character.

An example of how to do it:

sed -i "s%http://domain.com%http://www.domain.com/folder/%g" "test.txt"

Extracted from: http://www.sysadmit.com/2015/07/linux-reemplazar-texto-en-archivos-con-sed.html

Table Naming Dilemma: Singular vs. Plural Names

While looking for good naming covention, the following confusion arises as should i name :

1) acc. to what the table holds eg: A table of users. Its always going to be plural. So, Users

2) acc. to what a record holds eg: A record in users tables will a single user. SO, User.

Now, the problem for users_roles majorly. case 1: acc. to first naming convention, users_roles What this name suggest, users and their roles.

case 2: acc. to second naming convention, user_role What this name suggest, user and his roles.

Good naming convention is to give a additional idea of Entity relationships, especially when many to many relationships are stored.

Here, as per the scenario, we should identify as sets of information.

In users table, all sets formed are unique user. In Roles table, all sets formed are unique roles. In user and roles relationship table, sets of users can be formed with different roles which gives an idea of 1-many relationships stored.

I would prefer,
Users table => user
Roles table => role
users role relationship table => user_roles

What is the difference between 'java', 'javaw', and 'javaws'?

See Java tools documentation for:

  1. The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.
  2. The javaw command is identical to java, except that with javaw there is no associated console window. Use javaw when you don't want a command prompt window to appear.

The javaws command launches Java Web Start, which is the reference implementation of the Java Network Launching Protocol (JNLP). Java Web Start launches Java applications/applets hosted on a network.

If a JNLP file is specified, javaws will launch the Java application/applet specified in the JNLP file.

The javaws launcher has a set of options that are supported in the current release. However, the options may be removed in a future release.

See also JDK 9 Release Notes Deprecated APIs, Features, and Options:

Java Deployment Technologies are deprecated and will be removed in a future release
Java Applet and WebStart functionality, including the Applet API, the Java plug-in, the Java Applet Viewer, JNLP and Java Web Start, including the javaws tool, are all deprecated in JDK 9 and will be removed in a future release.

How do I delete a local repository in git?

Delete the .git directory in the root-directory of your repository if you only want to delete the git-related information (branches, versions).

If you want to delete everything (git-data, code, etc), just delete the whole directory.

.git directories are hidden by default, so you'll need to be able to view hidden files to delete it.

Installing TensorFlow on Windows (Python 3.6.x)

Tensorflow is not compatible with python3.7 and spyder3.3.1

To work with stable tensorflow version

follow the procedure

windows-->search-->Anaconda prompt-->right click -->click Run as adminstrator

Below command create the virtual environment which does not disturb existing projects

conda create -n projectname 

Below command activates your virtual environment within this directory installed package will not disturb your existing project.

activate projectname

Below command installs python 3.6.7 and spyder 3.2.3 as well

conda install spyder=3.2.3

Below mentioned tensorflow version works without any error. As per your need, you can install tensorflow version specifically.

pip install tensorflow==1.3.0

To open spyder

spyder

To exit form Virtual environment

deactivate

Using DISTINCT along with GROUP BY in SQL Server

Use DISTINCT to remove duplicate GROUPING SETS from the GROUP BY clause

In a completely silly example using GROUPING SETS() in general (or the special grouping sets ROLLUP() or CUBE() in particular), you could use DISTINCT in order to remove the duplicate values produced by the grouping sets again:

SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)

With DISTINCT:

actors
------
NULL
a
b

Without DISTINCT:

actors
------
a
b
NULL
a
b
a
b

But why, apart from making an academic point, would you do that?

Use DISTINCT to find unique aggregate function values

In a less far-fetched example, you might be interested in the DISTINCT aggregated values, such as, how many different duplicate numbers of actors are there?

SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors

Answer:

count
-----
2

Use DISTINCT to remove duplicates with more than one GROUP BY column

Another case, of course, is this one:

SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id

With DISTINCT:

actors  count
-------------
a       2
b       1

Without DISTINCT:

actors  count
-------------
a       2
b       1
b       1

For more details, I've written some blog posts, e.g. about GROUPING SETS and how they influence the GROUP BY operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).

extract date only from given timestamp in oracle sql

In Oracle 11g, To get the complete date from the Timestamp, use this-

Select TRUNC(timestamp) FROM TABLE_NAME;

To get the Year from the Timestamp, use this-

Select EXTRACT(YEAR FROM TRUNC(timestamp)) from TABLE_NAME;

To get the Month from the Timestamp, use this-

Select EXTRACT(MONTH FROM TRUNC(timestamp)) from TABLE_NAME;

To get the Day from the Timestamp, use this-

Select EXTRACT(DAY FROM TRUNC(timestamp)) from TABLE_NAME;

How to Calculate Execution Time of a Code Snippet in C++

#include <boost/progress.hpp>

using namespace boost;

int main (int argc, const char * argv[])
{
  progress_timer timer;

  // do stuff, preferably in a 100x loop to make it take longer.

  return 0;
}

When progress_timer goes out of scope it will print out the time elapsed since its creation.

UPDATE: Here's a version that works without Boost (tested on macOS/iOS):

#include <chrono>
#include <string>
#include <iostream>
#include <math.h>
#include <unistd.h>

class NLTimerScoped {
private:
    const std::chrono::steady_clock::time_point start;
    const std::string name;

public:
    NLTimerScoped( const std::string & name ) : name( name ), start( std::chrono::steady_clock::now() ) {
    }


    ~NLTimerScoped() {
        const auto end(std::chrono::steady_clock::now());
        const auto duration_ms = std::chrono::duration_cast<std::chrono::milliseconds>( end - start ).count();

        std::cout << name << " duration: " << duration_ms << "ms" << std::endl;
    }

};

int main(int argc, const char * argv[]) {

    {
        NLTimerScoped timer( "sin sum" );

        float a = 0.0f;

        for ( int i=0; i < 1000000; i++ ) {
            a += sin( (float) i / 100 );
        }

        std::cout << "sin sum = " << a << std::endl;
    }



    {
        NLTimerScoped timer( "sleep( 4 )" );

        sleep( 4 );
    }



    return 0;
}

fitting data with numpy

Unfortunately, np.polynomial.polynomial.polyfit returns the coefficients in the opposite order of that for np.polyfit and np.polyval (or, as you used np.poly1d). To illustrate:

In [40]: np.polynomial.polynomial.polyfit(x, y, 4)
Out[40]: 
array([  84.29340848, -100.53595376,   44.83281408,   -8.85931101,
          0.65459882])

In [41]: np.polyfit(x, y, 4)
Out[41]: 
array([   0.65459882,   -8.859311  ,   44.83281407, -100.53595375,
         84.29340846])

In general: np.polynomial.polynomial.polyfit returns coefficients [A, B, C] to A + Bx + Cx^2 + ..., while np.polyfit returns: ... + Ax^2 + Bx + C.

So if you want to use this combination of functions, you must reverse the order of coefficients, as in:

ffit = np.polyval(coefs[::-1], x_new)

However, the documentation states clearly to avoid np.polyfit, np.polyval, and np.poly1d, and instead to use only the new(er) package.

You're safest to use only the polynomial package:

import numpy.polynomial.polynomial as poly

coefs = poly.polyfit(x, y, 4)
ffit = poly.polyval(x_new, coefs)
plt.plot(x_new, ffit)

Or, to create the polynomial function:

ffit = poly.Polynomial(coefs)    # instead of np.poly1d
plt.plot(x_new, ffit(x_new))

fit and data plot

PHP sessions default timeout

Yes, that's usually happens after 1440s (24 minutes)

How do I open a URL from C++?

I was having the exact same problem in Windows.

I noticed that in OP's gist, he uses string("open ") in line 21, however, by using it one comes across this error:

'open' is not recognized as an internal or external command

After researching, I have found that open is MacOS the default command to open things. It is different on Windows or Linux.

Linux: xdg-open <URL>

Windows: start <URL>


For those of you that are using Windows, as I am, you can use the following:

std::string op = std::string("start ").append(url);
system(op.c_str());

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

What about wrapping it in a container. Container shoud have style like:

{
    width:100%;
    border: 10px solid transparent;
}

How to pass multiple checkboxes using jQuery ajax post

Could use the following and then explode the post result explode(",", $_POST['data']); to give an array of results.

var data = new Array();
$("input[name='checkBoxesName']:checked").each(function(i) {
    data.push($(this).val());
});

How to change the spinner background in Android?

enter image description here

Spinner code

<Spinner
    android:id="@+id/spinner"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/text.white"
    android:paddingBottom="13dp"
    android:background="@drawable/bg_spinner"/>

bg_spinner.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/colorPrimaryDark"/>
            <corners android:radius="10dp" />
        </shape>
    </item>
    <item android:gravity="center_vertical|right" android:right="8dp">
        <layer-list>
            <item android:width="12dp" android:height="12dp"  android:gravity="center" android:bottom="10dp">
                <rotate
                    android:fromDegrees="45"
                    android:toDegrees="45">
                    <shape android:shape="rectangle">
                        <solid android:color="#ffffff" />
                        <stroke android:color="#ffffff" android:width="1dp"/>
                    </shape>
                </rotate>
            </item>
            <item android:width="20dp" android:height="10dp" android:bottom="21dp" android:gravity="center">
                <shape android:shape="rectangle">
                    <solid android:color="@color/colorPrimaryDark"/>
                </shape>
            </item>
        </layer-list>
    </item>
</layer-list>

How to install package from github repo in Yarn

This is described here: https://yarnpkg.com/en/docs/cli/add#toc-adding-dependencies

For example:

yarn add https://github.com/novnc/noVNC.git#0613d18

Overloading and overriding

in C# there is no Java like hidden override, without keyword override on overriding method! see these C# implementations:

variant 1 without override: result is 200

    class Car {
        public int topSpeed() {
            return 200;
        }
    }

    class Ferrari : Car {
        public int topSpeed(){
                return 400;
        }
    }

    static void Main(string[] args){
        Car car = new Ferrari();
        int num= car.topSpeed();
        Console.WriteLine("Top speed for this car is: "+num);
        Console.ReadLine();
    }

variant 2 with override keyword: result is 400

    class Car {
        public virtual int topSpeed() {
            return 200;
        }
    }

    class Ferrari : Car {
        public override int topSpeed(){
                return 400;
        }
    }

    static void Main(string[] args){
        Car car = new Ferrari();
        int num= car.topSpeed();
        Console.WriteLine("Top speed for this car is: "+num);
        Console.ReadLine();
    }

keyword virtual on Car class is opposite for final on Java, means not final, you can override, or implement if Car was abstract

Moq, SetupGet, Mocking a property

ColumnNames is a property of type List<String> so when you are setting up you need to pass a List<String> in the Returns call as an argument (or a func which return a List<String>)

But with this line you are trying to return just a string

input.SetupGet(x => x.ColumnNames).Returns(temp[0]);

which is causing the exception.

Change it to return whole list:

input.SetupGet(x => x.ColumnNames).Returns(temp);

How to accept Date params in a GET request to Spring MVC Controller?

Below solution perfectly works for spring boot application.

Controller:

@GetMapping("user/getAllInactiveUsers")
List<User> getAllInactiveUsers(@RequestParam("date") @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss") Date dateTime) {
    return userRepository.getAllInactiveUsers(dateTime);
}

So in the caller (in my case its a web flux), we need to pass date time in this("yyyy-MM-dd HH:mm:ss") format.

Caller Side:

public Flux<UserDto> getAllInactiveUsers(String dateTime) {
    Flux<UserDto> userDto = RegistryDBService.getDbWebClient(dbServiceUrl).get()
            .uri("/user/getAllInactiveUsers?date={dateTime}", dateTime).retrieve()
            .bodyToFlux(User.class).map(UserDto::of);
    return userDto;
}

Repository:

@Query("SELECT u from User u  where u.validLoginDate < ?1 AND u.invalidLoginDate < ?1 and u.status!='LOCKED'")
List<User> getAllInactiveUsers(Date dateTime);

Cheers!!

Cannot implicitly convert type from Task<>

Depending on what you're trying to do, you can either block with GetIdList().Result ( generally a bad idea, but it's hard to tell the context) or use a test framework that supports async test methods and have the test method do var results = await GetIdList();

SQL- Ignore case while searching for a string

Like this.

SELECT DISTINCT COL_NAME FROM myTable WHERE COL_NAME iLIKE '%Priceorder%'

In postgresql.

.gitignore all the .DS_Store files in every folder and subfolder

You can also add the --cached flag to auco's answer to maintain local .DS_store files, as Edward Newell mentioned in his original answer. The modified command looks like this: find . -name .DS_Store -print0 | xargs -0 git rm --cached --ignore-unmatch ..cheers and thanks!

Spring Boot - Handle to Hibernate SessionFactory

Great work Andreas. I created a bean version so the SessionFactory could be autowired.

import javax.persistence.EntityManagerFactory;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;

....

@Autowired
private EntityManagerFactory entityManagerFactory;

@Bean
public SessionFactory getSessionFactory() {
    if (entityManagerFactory.unwrap(SessionFactory.class) == null) {
        throw new NullPointerException("factory is not a hibernate factory");
    }
    return entityManagerFactory.unwrap(SessionFactory.class);
}

Javascript replace with reference to matched group?

"hello _there_".replace(/_(.*?)_/, function(a, b){
    return '<div>' + b + '</div>';
})

Oh, or you could also:

"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")

EDIT by Liran H: For six other people including myself, $1 did not work, whereas \1 did.

Merging dataframes on index with pandas

You should be able to use join, which joins on the index as default. Given your desired result, you must use outer as the join type.

>>> df1.join(df2, how='outer')
            V1  V2
A 1/1/2012  12  15
  2/1/2012  14 NaN
  3/1/2012 NaN  21
B 1/1/2012  15  24
  2/1/2012   8   9
C 1/1/2012  17 NaN
  2/1/2012   9 NaN
D 1/1/2012 NaN   7
  2/1/2012 NaN  16

Signature: _.join(other, on=None, how='left', lsuffix='', rsuffix='', sort=False) Docstring: Join columns with other DataFrame either on index or on a key column. Efficiently Join multiple DataFrame objects by index at once by passing a list.

Iterating through populated rows

It looks like you just hard-coded the row and column; otherwise, a couple of small tweaks, and I think you're there:

Dim sh As Worksheet
Dim rw As Range
Dim RowCount As Integer

RowCount = 0

Set sh = ActiveSheet
For Each rw In sh.Rows

  If sh.Cells(rw.Row, 1).Value = "" Then
    Exit For
  End If

  RowCount = RowCount + 1

Next rw

MsgBox (RowCount)

How can I get a list of Git branches, ordered by most recent commit?

I know there are a lot of answers already, but here are my two cents for a simple alias (I like to have my most recent branch at the bottom):

[alias]
        br = !git branch --sort=committerdate --color=always | tail -n15
[color "branch"]
        current = yellow
        local = cyan
        remote = red

This will give you a nice overview of your latest 15 branches, in color, with your current branch highlighted (and it has an asterisk).

How to check a string for a special character?

You can use string.punctuation and any function like this

import string
invalidChars = set(string.punctuation.replace("_", ""))
if any(char in invalidChars for char in word):
    print "Invalid"
else:
    print "Valid"

With this line

invalidChars = set(string.punctuation.replace("_", ""))

we are preparing a list of punctuation characters which are not allowed. As you want _ to be allowed, we are removing _ from the list and preparing new set as invalidChars. Because lookups are faster in sets.

any function will return True if atleast one of the characters is in invalidChars.

Edit: As asked in the comments, this is the regular expression solution. Regular expression taken from https://stackoverflow.com/a/336220/1903116

word = "Welcome"
import re
print "Valid" if re.match("^[a-zA-Z0-9_]*$", word) else "Invalid"

Why does javascript replace only first instance when using replace?

You can use:

String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
    return this.toString();
}
return this.split(search).join(replace);
}

Encode html entities in javascript

Here is how I implemented the encoding. I took inspiration from the answers given above.

_x000D_
_x000D_
function encodeHTML(str) {
  const code = {
      ' ' : '&nbsp;',
      '¢' : '&cent;',
      '£' : '&pound;',
      '¥' : '&yen;',
      '€' : '&euro;', 
      '©' : '&copy;',
      '®' : '&reg;',
      '<' : '&lt;', 
      '>' : '&gt;',  
      '"' : '&quot;', 
      '&' : '&amp;',
      '\'' : '&apos;'
  };
  return str.replace(/[\u00A0-\u9999<>\&''""]/gm, (i)=>code[i]);
}

// TEST
console.log(encodeHTML("Dolce & Gabbana"));
console.log(encodeHTML("Hamburgers < Pizza < Tacos"));
console.log(encodeHTML("Sixty > twelve"));
console.log(encodeHTML('Stuff in "quotation marks"'));
console.log(encodeHTML("Schindler's List"));
console.log(encodeHTML("<>"));
_x000D_
_x000D_
_x000D_

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

I came from Google and I just wanted to add the solution that worked for me. My problem was I was trying to delete records of a huge table that had a lot of FK in cascade so I got the same error as the OP.

I disabled the autocommit and then it worked just adding COMMIT at the end of the SQL sentence. As far as I understood this releases the buffer bit by bit instead of waiting at the end of the command.

To keep with the example of the OP, this should have worked:

mysql> set autocommit=0;

mysql> update customer set account_import_id = 1; commit;

Do not forget to reactivate the autocommit again if you want to leave the MySQL config as before.

mysql> set autocommit=1;

MySQL INSERT INTO ... VALUES and SELECT

 
INSERT INTO table_name1
            (id,
             name,
             address,
             contact_number) 
SELECT id, name, address, contact_number FROM table_name2;   

How to embed images in html email

Here is a way to get a string variable without having to worry about the coding.

If you have Mozilla Thunderbird, you can use it to fetch the html image code for you.

I wrote a little tutorial here, complete with a screenshot (it's for powershell, but that doesn't matter for this):

powershell email with html picture showing red x

And again:

How to embed images in email

How do I set the proxy to be used by the JVM

As is pointed out in other answers, if you need to use Authenticated proxies, there's no reliable way to do this purely using command-line variables - which is annoying if you're using someone else's application and don't want to mess with the source code.

Will Iverson makes the helpful suggestion over at Using HttpProxy to connect to a host with preemtive authentication to use a Proxy-management tool such as Proxifier ( http://www.proxifier.com/ for Mac OS X and Windows) to handle this.

For example with Proxifier you can set it up to only intercept java commands to be managed and redirected through its (authenticated) proxy. You're going to want to set the proxyHost and proxyPort values to blank in this case though, e.g. pass in -Dhttp.proxyHost= -Dhttp.proxyPort= to your java commands.

Angular 2 optional route parameter

I can't comment, but in reference to: Angular 2 optional route parameter

an update for Angular 6:

import {map} from "rxjs/operators"

constructor(route: ActivatedRoute) {
  let paramId = route.params.pipe(map(p => p.id));

  if (paramId) {
    ...
  }
}

See https://angular.io/api/router/ActivatedRoute for additional information on Angular6 routing.

MongoDB: How to query for records where field is null or not set?

If you want to ONLY count the documents with sent_at defined with a value of null (don't count the documents with sent_at not set):

db.emails.count({sent_at: { $type: 10 }})

How to install gem from GitHub source?

Try the specific_install gem it allows you you to install a gem from its github repository (like 'edge'), or from an arbitrary URL. Very usefull for forking gems and hacking on them on multiple machines and such.

gem install specific_install
gem specific_install -l <url to a github gem>

e.g.

gem specific_install https://github.com/githubsvnclone/rdoc.git 

Managing jQuery plugin dependency in webpack

For global access to jquery then several options exist. In my most recent webpack project, I wanted global access to jquery so I added the following to my plugins declarations:

 plugins: [
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    })
  ]

This then means that jquery is accessible from within the JavaScript source code via global references $ and jQuery.

Of course, you need to have also installed jquery via npm:

$ npm i jquery --save

For a working example of this approach please feel free to fork my app on github

Flatten list of lists

I would use itertools.chain - this will also cater for > 1 element in each sublist:

from itertools import chain
list(chain.from_iterable([[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]))

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

<script type="text/javascript">
    function lnkLogout_Confirm()
    {
        var bResponse = confirm('Are you sure you want to exit?');

        if (bResponse === true) {
            ////console.log("lnkLogout_Confirm clciked.");
            var url = '@Url.Action("Login", "Login")';
            window.location.href = url;
        }
        return bResponse;
    }

</script>

trigger click event from angularjs directive

This is how I was able to trigger a button click when the page loads.

<li ng-repeat="a in array">
  <a class="button" id="btn" ng-click="function(a)" index="$index" on-load-clicker>
    {{a.name}}
  </a>
</li>

A simple directive that takes the index from the ng-repeat and uses a condition to call the first button in the index and click it when the page loads.

angular
    .module("myApp")
        .directive('onLoadClicker', function ($timeout) {
            return {
                restrict: 'A',
                scope: {
                    index: '=index'
                },
                link: function($scope, iElm) {
                    if ($scope.index == 0) {
                        $timeout(function() {

                            iElm.triggerHandler('click');

                        }, 0);
                    }
                }
            };
        });

This was the only way I was able to even trigger an auto click programmatically in the first place. angular.element(document.querySelector('#btn')).click(); Did not work from the controller so making this simple directive seems most effective if you are trying to run a click on page load and you can specify which button to click by passing in the index. I got help through this stack-overflow answer from another post reference: https://stackoverflow.com/a/26495541/4684183 onLoadClicker Directive.

How to get the last value of an ArrayList

All you need to do is use size() to get the last value of the Arraylist. For ex. if you ArrayList of integers, then to get last value you will have to

int lastValue = arrList.get(arrList.size()-1);

Remember, elements in an Arraylist can be accessed using index values. Therefore, ArrayLists are generally used to search items.

Getting scroll bar width using JavaScript

Here's an easy way using jQuery.

var scrollbarWidth = jQuery('div.withScrollBar').get(0).scrollWidth - jQuery('div.withScrollBar').width();

Basically we subtract the scrollable width from the overall width and that should provide the scrollbar's width. Of course, you'd want to cache the jQuery('div.withScrollBar') selection so you're not doing that part twice.

Show/Hide Multiple Divs with Jquery

Check This Example

Html:

<div class="buttons">
<a class="button" id="showall">All</a>
<a class="button" id="showdiv1">Div 1</a>
<a class="button" id="showdiv2">Div 2</a>
<a class="button" id="showdiv3">Div 3</a>
<a class="button" id="showdiv4">Div 4</a>
</div>

<div id="div1">1</div>
<div id="div2">2</div>
<div id="div3">3</div>
<div id="div4">4</div>

Javascript:

$('#showall').click(function(){
    $('div').show();
});

$('#showdiv1').click(function(){
    $('div[id^=div]').hide();
    $('#div1').show();
});
$('#showdiv2').click(function(){
    $('div[id^=div]').hide();
    $('#div2').show();
});

$('#showdiv3').click(function(){
    $('div[id^=div]').hide();
    $('#div3').show();
});

$('#showdiv4').click(function(){
    $('div[id^=div]').hide();
    $('#div4').show();

});

This version of the application is not configured for billing through Google Play

If you're here from 2018, you need to download the APK directly from Play Store and install the "derived" APK. Maybe it is because of Google's Play Store has a feature "App Signing by Google Play".

How to set response header in JAX-RS so that user sees download popup for Excel?

I figured to set HTTP response header and stream to display download-popup in browser via standard servlet. note: I'm using Excella, excel output API.

package local.test.servlet;

import java.io.IOException;
import java.net.URL;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import local.test.jaxrs.ExcellaTestResource;
import org.apache.poi.ss.usermodel.Workbook;
import org.bbreak.excella.core.BookData;
import org.bbreak.excella.core.exception.ExportException;
import org.bbreak.excella.reports.exporter.ExcelExporter;
import org.bbreak.excella.reports.exporter.ReportBookExporter;
import org.bbreak.excella.reports.model.ConvertConfiguration;
import org.bbreak.excella.reports.model.ReportBook;
import org.bbreak.excella.reports.model.ReportSheet;
import org.bbreak.excella.reports.processor.ReportProcessor;

@WebServlet(name="ExcelServlet", urlPatterns={"/ExcelServlet"})
public class ExcelServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        try {

            URL templateFileUrl = ExcellaTestResource.class.getResource("myTemplate.xls");
            //   /C:/Users/m-hugohugo/Documents/NetBeansProjects/KogaAlpha/build/web/WEB-INF/classes/local/test/jaxrs/myTemplate.xls
            System.out.println(templateFileUrl.getPath());
            String templateFilePath = URLDecoder.decode(templateFileUrl.getPath(), "UTF-8");
            String outputFileDir = "MasatoExcelHorizontalOutput";

            ReportProcessor reportProcessor = new ReportProcessor();
            ReportBook outputBook = new ReportBook(templateFilePath, outputFileDir, ExcelExporter.FORMAT_TYPE);

            ReportSheet outputSheet = new ReportSheet("MySheet");
            outputBook.addReportSheet(outputSheet);

            reportProcessor.addReportBookExporter(new OutputStreamExporter(response));
            System.out.println("wtf???");
            reportProcessor.process(outputBook);


            System.out.println("done!!");
        }
        catch(Exception e) {
            System.out.println(e);
        }

    } //end doGet()

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

}//end class



class OutputStreamExporter extends ReportBookExporter {

    private HttpServletResponse response;

    public OutputStreamExporter(HttpServletResponse response) {
        this.response = response;
    }

    @Override
    public String getExtention() {
        return null;
    }

    @Override
    public String getFormatType() {
        return ExcelExporter.FORMAT_TYPE;
    }

    @Override
    public void output(Workbook book, BookData bookdata, ConvertConfiguration configuration) throws ExportException {

        System.out.println(book.getFirstVisibleTab());
        System.out.println(book.getSheetName(0));

        //TODO write to stream
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment; filename=masatoExample.xls");
            book.write(response.getOutputStream());
            response.getOutputStream().close();
            System.out.println("booya!!");
        }
        catch(Exception e) {
            System.out.println(e);
        }
    }
}//end class

importing jar libraries into android-studio

Android Studio 1.0 makes it easier to add a .jar file library to a project. Go to File>Project Structure and then Click on Dependencies. Over there you can add .jar files from your computer to the project. You can also search for libraries from maven.

Angular 2 router no base href set

Check your index.html. If you have accidentally removed the following part, include it and it will be fine

<base href="/">

<meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">

How to clear textarea on click?

The best solution what I know so far:

<textarea name="message" onblur="if (this.value == '') {this.value = 'text here';}"   onfocus="if (this.value == 'text here') {this.value = '';}">text here</textarea>

What is the meaning of "Failed building wheel for X" in pip install?

It might be helpful to address this question from a package deployment perspective.

There are many tutorials out there that explain how to publish a package to PyPi. Below are a couple I have used;

medium
real python

My experience is that most of these tutorials only have you use the .tar of the source, not a wheel. Thus, when installing packages created using these tutorials, I've received the "Failed to build wheel" error.

I later found the link on PyPi to the Python Software Foundation's docs PSF Docs. I discovered that their setup and build process is slightly different, and does indeed included building a wheel file.

After using the officially documented method, I no longer received the error when installing my packages.

So, the error might simply be a matter of how the developer packaged and deployed the project. None of us were born knowing how to use PyPi, and if they happened upon the wrong tutorial -- well, you can fill in the blanks.

I'm sure that is not the only reason for the error, but I'm willing to bet that is a major reason for it.

How can I see what I am about to push with git?

There is always dry-run:

git push --dry-run

It will do everything except for the actually sending of the data.

If you want a more graphical view you have a bunch of options.

Tig and the gitk script that come with git both display the current branch of your local copy and the branch of the remote or origin.

alt text

So any commits you make that are after the origin are the commits that will be pushed.

Open gitk from shell while in the branch you want to push by typing gitk&, then to see the difference between what is on the remote and what you are about to push to the remote, select your local unpushed commit and right-click on the remote and choose "Diff this -> selected": alt text

Are nested try/except blocks in Python a good programming practice?

I don't think it's a matter of being Pythonic or elegant. It's a matter of preventing exceptions as much as you can. Exceptions are meant to handle errors that might occur in code or events you have no control over.

In this case, you have full control when checking if an item is an attribute or in a dictionary, so avoid nested exceptions and stick with your second attempt.

How to Set user name and Password of phpmyadmin

You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.

How do I use WPF bindings with RelativeSource?

I just posted another solution for accessing the DataContext of a parent element in Silverlight that works for me. It uses Binding ElementName.

How to write trycatch in R

tryCatch has a slightly complex syntax structure. However, once we understand the 4 parts which constitute a complete tryCatch call as shown below, it becomes easy to remember:

expr: [Required] R code(s) to be evaluated

error : [Optional] What should run if an error occured while evaluating the codes in expr

warning : [Optional] What should run if a warning occured while evaluating the codes in expr

finally : [Optional] What should run just before quitting the tryCatch call, irrespective of if expr ran successfully, with an error, or with a warning

tryCatch(
    expr = {
        # Your code...
        # goes here...
        # ...
    },
    error = function(e){ 
        # (Optional)
        # Do this if an error is caught...
    },
    warning = function(w){
        # (Optional)
        # Do this if an warning is caught...
    },
    finally = {
        # (Optional)
        # Do this at the end before quitting the tryCatch structure...
    }
)

Thus, a toy example, to calculate the log of a value might look like:

log_calculator <- function(x){
    tryCatch(
        expr = {
            message(log(x))
            message("Successfully executed the log(x) call.")
        },
        error = function(e){
            message('Caught an error!')
            print(e)
        },
        warning = function(w){
            message('Caught an warning!')
            print(w)
        },
        finally = {
            message('All done, quitting.')
        }
    )    
}

Now, running three cases:

A valid case

log_calculator(10)
# 2.30258509299405
# Successfully executed the log(x) call.
# All done, quitting.

A "warning" case

log_calculator(-10)
# Caught an warning!
# <simpleWarning in log(x): NaNs produced>
# All done, quitting.

An "error" case

log_calculator("log_me")
# Caught an error!
# <simpleError in log(x): non-numeric argument to mathematical function>
# All done, quitting.

I've written about some useful use-cases which I use regularly. Find more details here: https://rsangole.netlify.com/post/try-catch/

Hope this is helpful.

React: why child component doesn't update when prop changes

Use the setState function. So you could do

       this.setState({this.state.foo.bar:123}) 

inside the handle event method.

Once, the state is updated, it will trigger changes, and re-render will take place.

How can I convert a dictionary into a list of tuples?

Create a list of namedtuples

It can often be very handy to use namedtuple. For example, you have a dictionary of 'name' as keys and 'score' as values like:

d = {'John':5, 'Alex':10, 'Richard': 7}

You can list the items as tuples, sorted if you like, and get the name and score of, let's say the player with the highest score (index=0) very Pythonically like this:

>>> player = best[0]

>>> player.name
        'Alex'
>>> player.score
         10

How to do this:

list in random order or keeping order of collections.OrderedDict:

import collections
Player = collections.namedtuple('Player', 'name score')
players = list(Player(*item) for item in d.items())

in order, sorted by value ('score'):

import collections
Player = collections.namedtuple('Player', 'score name')

sorted with lowest score first:

worst = sorted(Player(v,k) for (k,v) in d.items())

sorted with highest score first:

best = sorted([Player(v,k) for (k,v) in d.items()], reverse=True)

Getting Textarea Value with jQuery

It can be done at easily like as:

     <a id="send-thoughts" href="">Click</a>
     <textarea id="message"></textarea>

        $("a#send-thoughts").click(function() {
            var thought = $("#message").val();
            alert(thought);
        });

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

Single bash line:

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

Slight problem: duplicate filename.

How do I create a simple 'Hello World' module in Magento?

I was trying to make my module from magaplaza hello world tutorial, but something went wrong. I imported code of this module https://github.com/astorm/magento2-hello-world from github and it worked. from that module, i created it a categories subcategories ajax select drop downs Module. After installing it in aap/code directory of your magento2 installation follow this URL.. http://www.example.com/hello_mvvm/hello/world You can download its code from here https://github.com/sanaullahAhmad/Magento2_cat_subcat_ajax_select_dropdowns and place it in your aap/code folder. than run these commands...

php bin/magento setup:update
php bin/magento setup:static-content:deploy -f
php bin/magento c:c

Now you can check module functionality with following URL http://{{www.example.com}}/hello_mvvm/hello/world

Android: converting String to int

Change

try {
    myNum = Integer.parseInt(myString.getText().toString());
} catch(NumberFormatException nfe) {

to

try {
    myNum = Integer.parseInt(myString);
} catch(NumberFormatException nfe) {

Model backing a DB Context has changed; Consider Code First Migrations

Adding this as another possible solution, because this is what fixed it in our case;

Make sure if you have multiple projects that they are using the same Entity Framework Nuget package version!.

In our case we had one project ( call if project A ) holding the EF code first context with all entities. It was this project that we were using to add migrations & update the database. However a second project ( B ) was referencing project A to make use of the context. When running this project we got the same error;

The model backing the 'MyDbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

JavaScript: How to find out if the user browser is Chrome?

even shorter: var is_chrome = /chrome/i.test( navigator.userAgent );

Deep-Learning Nan loss reasons

I'd like to plug in some (shallow) reasons I have experienced as follows:

  1. we may have updated our dictionary(for NLP tasks) but the model and the prepared data used a different one.
  2. we may have reprocessed our data(binary tf_record) but we loaded the old model. The reprocessed data may conflict with the previous one.
  3. we may should train the model from scratch but we forgot to delete the checkpoints and the model loaded the latest parameters automatically.

Hope that helps.

.attr('checked','checked') does not work

$('.checkbox').prop('checked',true); 
$('.checkbox').prop('checked',false);

... works perfectly with jquery1.9.1

Benefits of inline functions in C++?

Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger.

Does it make a significant difference? Not noticeably enough on modern hardware for most. But it can make a difference, which is enough for some people.

Marking something inline does not give you a guarantee that it will be inline. It's just a suggestion to the compiler. Sometimes it's not possible such as when you have a virtual function, or when there is recursion involved. And sometimes the compiler just chooses not to use it.

I could see a situation like this making a detectable difference:

inline int aplusb_pow2(int a, int b) {
  return (a + b)*(a + b) ;
}

for(int a = 0; a < 900000; ++a)
    for(int b = 0; b < 900000; ++b)
        aplusb_pow2(a, b);

Oracle Convert Seconds to Hours:Minutes:Seconds

Try this one. Very simple and easy to use

select to_char(to_date(10000,'sssss'),'hh24:mi:ss') from dual;

JSON.parse unexpected character error

You're not parsing a string, you're parsing an already-parsed object :)

var obj1 = JSON.parse('{"creditBalance":0,...,"starStatus":false}');
//                    ^                                          ^
//                    if you want to parse, the input should be a string 

var obj2 = {"creditBalance":0,...,"starStatus":false};
// or just use it directly.

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

All values of column A that are not present in column B will have a red background. Hope that it helps as starting point.

Sub highlight_missings()
Dim i As Long, lastA As Long, lastB As Long
Dim compare As Variant
Range("A:A").ClearFormats
lastA = Range("A65536").End(xlUp).Row
lastB = Range("B65536").End(xlUp).Row

For i = 2 To lastA
    compare = Application.Match(Range("a" & i), Range("B2:B" & lastB), 0)
        If IsError(compare) Then
            Range("A" & i).Interior.ColorIndex = 3
        End If
Next i
End Sub

How to extract the substring between two markers?

Surprised that nobody has mentioned this which is my quick version for one-off scripts:

>>> x = 'gfgfdAAA1234ZZZuijjk'
>>> x.split('AAA')[1].split('ZZZ')[0]
'1234'

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

Quantile-Quantile Plot using SciPy

If you need to do a QQ plot of one sample vs. another, statsmodels includes qqplot_2samples(). Like Ricky Robinson in a comment above, this is what I think of as a QQ plot vs a probability plot which is a sample against a theoretical distribution.

http://statsmodels.sourceforge.net/devel/generated/statsmodels.graphics.gofplots.qqplot_2samples.html

Difference between "or" and || in Ruby?

The way I use these operators:

||, && are for boolean logic. or, and are for control flow. E.g.

do_smth if may_be || may_be -- we evaluate the condition here

do_smth or do_smth_else -- we define the workflow, which is equivalent to do_smth_else unless do_smth

to give a simple example:

> puts "a" && "b"
b

> puts 'a' and 'b'
a

A well-known idiom in Rails is render and return. It's a shortcut for saying return if render, while render && return won't work. See "Avoiding Double Render Errors" in the Rails documentation for more information.

How do I start PowerShell from Windows Explorer?

As an alternative to the answer above, which requires you to type the PowerShell command (powershell.exe) each time, you can create a context menu entry just like with the "Open command window here" context menu.

There are three registry keys where these commands go. Each key controls the context menu of a different Windows Explorer object. The first one is the one you asked about:

  • HKCR\Directory\Background\shell - This is the context menu for the Explorer window itself (that is, the context menu that is displayed when no item is selected, such as when right-clicking in an empty area of the window).
  • HKCR\Directory\shell - This is the context menu of the folders in Windows Explorer.
  • HKCR\Drive\shell - This is the context menu for the drive icons in the root of Windows Explorer.

For each of these registry keys, you can add a subkey that will add an "Open PowerShell window here" command to the context menu, just as you have an "Open command window here" context menu.

Here is a copy of my OpenPowerShellHere.reg file, which puts the command in the context menu of each of the Explorer objects, the window background, the folder, and the drive icon:

Windows Registry Editor Version 5.00

;
; Add context menu entry to Windows Explorer background
;
[HKEY_CLASSES_ROOT\Directory\Background\shell\powershell]
@="Open PowerShell window here"
"NoWorkingDirectory"=""

[HKEY_CLASSES_ROOT\Directory\Background\shell\powershell\command]
@="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -NoExit -Command Set-Location -LiteralPath '%V'"

;
; Add context menu entry to Windows Explorer folders
;
[HKEY_CLASSES_ROOT\Directory\shell\powershell]
@="Open PowerShell window here"
"NoWorkingDirectory"=""

[HKEY_CLASSES_ROOT\Directory\shell\powershell\command]
@="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -NoExit -Command Set-Location -LiteralPath '%V'"

;
; Add context menu entry to Windows Explorer drive icons
;
[HKEY_CLASSES_ROOT\Drive\shell\powershell]
@="Open PowerShell window here"
"NoWorkingDirectory"=""

[HKEY_CLASSES_ROOT\Drive\shell\powershell\command]
@="C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -NoExit -Command Set-Location -LiteralPath '%V'"

So, with your favorite text editor, open a new file named OpenPowerShellHere.reg. Copy the exact text of the code above, paste it into the new file, and save it. (I would have included a copy of the file, but I couldn't figure out if attachments were possible.) If you want to exclude the command from one of the entry, just comment out the appropriate section with semicolons. My comments show you each section.

After you save the file, run it by double-clicking on it. When it asks, tell it to proceed. As soon as you run it, the context menu entries will show up!

Here is my Explorer window context menu. I've highlighted the console and PowerShell commands. As you can see, you can also add a context menu entry to run an elevated command window, i.e., Run as Administrator.

PowerShell entry in Explorer context menu

Note: Context menu entries are displayed alphabetically, based on their Registry keys. The key name for the elevated command shell is "runas", which is why it comes after the PowerShell entry.

Note: If you have an explorer window open, you may need to close it and reopen it to get the changed to take effect.

Note: In Windows 7, the HKCR\Directory\Shell does not work if you use the toolkit on the side of the explorer

(ie. Clicking Documents under the Libraries header)

you must navigate using Computer -> C: -> to -> Some -> Target -> Directory

How to write a full path in a batch file having a folder name with space?

start "" AcroRd32.exe /A "page=207" "C:\Users\abc\Desktop\abc xyz def\abc def xyz 2015.pdf"

You may try this, I did it finally, it works!

Double % formatting question for printf in Java

Following is the list of conversion characters that you may use in the printf:

%d – for signed decimal integer

%f – for the floating point

%o – octal number

%c – for a character

%s – a string

%i – use for integer base 10

%u – for unsigned decimal number

%x – hexadecimal number

%% – for writing % (percentage)

%n – for new line = \n

if (boolean == false) vs. if (!boolean)

Mostly READABILITY. When reading others code, it is much more intuitive to read as NOT CONTAINS KEY !values.containsKey(NoteColumns.CREATED_DATE) instead of reading CONTAINS KEY IS FALSE (values.containsKey(NoteColumns.CREATED_DATE) == false).

Cookies vs. sessions

when you save the #ID as the cookie to recognize logged in users, you actually are showing data to users that is not related to them. In addition, if a third party tries to set random IDs as cookie data in their browser, they will be able to convince the server that they are a user while they actually are not. That's a lack of security.

You have used cookies, and as you said you have already completed most of the project. besides cookie has the privilege of remaining for a long time, while sessions end more quickly. So sessions are not suitable in this case. In reality many famous and popular websites and services use cookie and you can stay logged-in for a long time. But how can you use their method to create a safer log-in process?

here's the idea: you can help the way you use cookies: If you use random keys instead of IDs to recognize logged-in users, first, you don't leak your primary data to random users, and second, If you consider the Random key large enough, It will be harder for anyone to guess a key or create a random one. for example you can save a 40 length key like this in User's browser: "KUYTYRFU7987gJHFJ543JHBJHCF5645UYTUYJH54657jguthfn" and it will be less likely for anyone to create the exact key and pretend to be someone else.

CXF: No message body writer found for class - automatically mapping non-simple resources

Step 1: Add the bean class into the dataFormat list:

<dataFormats>
    <json id="jack" library="Jackson" prettyPrint="true"
          unmarshalTypeName="{ur bean class path}" /> 
</dataFormats>

Step 2: Marshal the bean prior to the client call:

<marchal id="marsh" ref="jack"/>

How to format an inline code in Confluence?

I found formatting with colors a bit trickier as Confluence (5.6.3) is very fussy about spaces around the {{monospace}} blocks.

Creating Colored Monospace with Wiki Markup

As rendered by Confluence

How can I check whether a numpy array is empty or not?

http://www.scipy.org/Tentative_NumPy_Tutorial#head-6a1bc005bd80e1b19f812e1e64e0d25d50f99fe2

NumPy's main object is the homogeneous multidimensional array. In Numpy dimensions are called axes. The number of axes is rank. Numpy's array class is called ndarray. It is also known by the alias array. The more important attributes of an ndarray object are:

ndarray.ndim
the number of axes (dimensions) of the array. In the Python world, the number of dimensions is referred to as rank.

ndarray.shape
the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the rank, or number of dimensions, ndim.

ndarray.size
the total number of elements of the array. This is equal to the product of the elements of shape.

How can I access an internal class from an external assembly?

I see only one case that you would allow exposure to your internal members to another assembly and that is for testing purposes.

Saying that there is a way to allow "Friend" assemblies access to internals:

In the AssemblyInfo.cs file of the project you add a line for each assembly.

[assembly: InternalsVisibleTo("name of assembly here")]

this info is available here.

Hope this helps.

Reading file line by line (with space) in Unix Shell scripting - Issue

You want to read raw lines to avoid problems with backslashes in the input (use -r):

while read -r line; do
   printf "<%s>\n" "$line"
done < file.txt

This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in

while IFS= read -r line; do
   printf "%s\n" "$line"
done < file.txt

This now is an equivalent of cat < file.txt as long as file.txt ends with a newline.

Note that you must double quote "$line" in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.

Convert string to boolean in C#

I know this is not an ideal question to answer but as the OP seems to be a beginner, I'd love to share some basic knowledge with him... Hope everybody understands

OP, you can convert a string to type Boolean by using any of the methods stated below:

 string sample = "True";
 bool myBool = bool.Parse(sample);

 ///or

 bool myBool = Convert.ToBoolean(sample);

bool.Parse expects one parameter which in this case is sample, .ToBoolean also expects one parameter.

You can use TryParse which is the same as Parse but it doesn't throw any exception :)

  string sample = "false";
  Boolean myBool;

  if (Boolean.TryParse(sample , out myBool))
  {
  }

Please note that you cannot convert any type of string to type Boolean because the value of a Boolean can only be True or False

Hope you understand :)

Do I need to close() both FileReader and BufferedReader?

You Only Need to close the bufferedReader i.e reader.close() and it will work fine .

How to read file from res/raw by name

You can read files in raw/res using getResources().openRawResource(R.raw.myfilename).

BUT there is an IDE limitation that the file name you use can only contain lower case alphanumeric characters and dot. So file names like XYZ.txt or my_data.bin will not be listed in R.

Printing the value of a variable in SQL Developer

1 ) Go to view menu.
2 ) Select the DBMS_OUTPUT menu item.
3 ) Press Ctrl + N and select connection editor.
4 ) Execute the SET SERVEROUTPUT ON Command.
5 ) Then execute your PL/SQL Script.

enter image description here enter image description here

Using Linq select list inside list

You have to use the SelectMany extension method or its equivalent syntax in pure LINQ.

(from model in list
 where model.application == "applicationname"
 from user in model.users
 where user.surname == "surname"
 select new { user, model }).ToList();

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

If you'd like to have your JAVA_HOME recognised by intellij, you can do one of these:

  • Start your intellij from terminal /Applications/IntelliJ IDEA 14.app/Contents/MacOS (this will pick your bash env variables)
  • Add login env variable by executing: launchctl setenv JAVA_HOME "/Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home"

As others have answered you can ignore JAVA_HOME by setting up SDK in project structure.

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

I have solved the issue by the following way.

1. Creating a class . The class has some empty implementations

class MyTrustManager implements X509TrustManager {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
    return null;
}

public void checkClientTrusted(X509Certificate[] certs, String authType) {
}

public void checkServerTrusted(X509Certificate[] certs, String authType) {
}

@Override
public void checkClientTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString)
        throws CertificateException {
    // TODO Auto-generated method stub

}

@Override
public void checkServerTrusted(java.security.cert.X509Certificate[] paramArrayOfX509Certificate, String paramString)
        throws CertificateException {
    // TODO Auto-generated method stub

}

2. Creating a method

private static void disableSSL() {
    try {
        TrustManager[] trustAllCerts = new TrustManager[] { new MyTrustManager() };

        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

  1. Call the disableSSL() method where the exception is thrown. It worked fine.

SQL recursive query on self referencing table (Oracle)

It's a little on the cumbersome side, but I believe this should work (without the extra join). This assumes that you can choose a character that will never appear in the field in question, to act as a separator.

You can do it without nesting the select, but I find this a little cleaner that having four references to SYS_CONNECT_BY_PATH.

select id, 
       parent_id, 
       case 
         when lvl <> 1 
         then substr(name_path,
                     instr(name_path,'|',1,lvl-1)+1,
                     instr(name_path,'|',1,lvl)
                      -instr(name_path,'|',1,lvl-1)-1) 
         end as name 
from (
  SELECT id, parent_id, sys_connect_by_path(name,'|') as name_path, level as lvl
  FROM tbl 
  START WITH id = 1 
  CONNECT BY PRIOR id = parent_id)

Ignore 'Security Warning' running script from command line

If you're running into this error from a downloaded powershell script, you can unblock the script this way:

  1. Right-click on the .ps1 file in question, and select Properties

  2. Click Unblock in the file properties

    enter image description here

  3. Click OK

Composer Warning: openssl extension is missing. How to enable in WAMP

For installing Composer below steps worked me:(WAMP version 2.4 x64bit)

edit ->
**C:\wamp\bin\php\php5.4.12\php.ini**
;;uncomment below line or remove the semicolons ';'
extension=php_openssl.dll

**C:\wamp\bin\apache\Apache2.4.4\bin\php.ini**

extension=php_openssl.dll

Order by multiple columns with Doctrine

You have to add the order direction right after the column name:

$qb->orderBy('column1 ASC, column2 DESC');

As you have noted, multiple calls to orderBy do not stack, but you can make multiple calls to addOrderBy:

$qb->addOrderBy('column1', 'ASC')
   ->addOrderBy('column2', 'DESC');

Copy mysql database from remote server to local computer

Please check this gist.

https://gist.github.com/ecdundar/789660d830d6d40b6c90

#!/bin/bash

# copymysql.sh

# GENERATED WITH USING ARTUR BODERA S SCRIPT
# Source script at: https://gist.github.com/2215200

MYSQLDUMP="/usr/bin/mysqldump"
MYSQL="/usr/bin/mysql"

REMOTESERVERIP=""
REMOTESERVERUSER=""
REMOTESERVERPASSWORD=""
REMOTECONNECTIONSTR="-h ${REMOTESERVERIP} -u ${REMOTESERVERUSER} --password=${REMOTESERVERPASSWORD} "

LOCALSERVERIP=""
LOCALSERVERUSER=""
LOCALSERVERPASSWORD=""
LOCALCONNECTION="-h ${LOCALSERVERIP} -u ${LOCALSERVERUSER} --password=${LOCALSERVERPASSWORD} "

IGNOREVIEWS=""
MYVIEWS=""
IGNOREDATABASES="select schema_name from information_schema.SCHEMATA where schema_name != 'information_schema' and schema_name != 'mysql' and schema_name != 'performance_schema'  ;"

# GET A LIST OF DATABASES
databases=`$MYSQL $REMOTECONNECTIONSTR -e "${IGNOREDATABASES}" | tr -d "| " | grep -v schema_name`

# COPY ALL TABLES
for db in $databases; do
    # GET LIST OF ITEMS
    views=`$MYSQL $REMOTECONNECTIONSTR --batch -N -e "select table_name from information_schema.tables where table_type='VIEW' and table_schema='$db';"
    IGNOREVIEWS=""
    for view in $views; do
        IGNOREVIEWS=${IGNOREVIEWS}" --ignore-table=$db.$view " 
    done
    echo "TABLES "$db
    $MYSQL $LOCALCONNECTION --batch -N -e "create database $db; "
    $MYSQLDUMP $REMOTECONNECTIONSTR $IGNOREVIEWS --compress --quick --extended-insert  --skip-add-locks --skip-comments --skip-disable-keys --default-character-set=latin1 --skip-triggers --single-transaction  $db | mysql $LOCALCONNECTION  $db 
done

# COPY ALL PROCEDURES
for db in $databases; do
    echo "PROCEDURES "$db
    #PROCEDURES
    $MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick --routines --no-create-info --no-data --no-create-db --skip-opt --skip-triggers $db | \
    sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION  $db 
done

# COPY ALL TRIGGERS
for db in $databases; do
    echo "TRIGGERS "$db
    #TRIGGERS
    $MYSQLDUMP $REMOTECONNECTIONSTR  --compress --quick --no-create-info --no-data --no-create-db --skip-opt --triggers $db | \
    sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g' | mysql $LOCALCONNECTION  $db 
done

# COPY ALL VIEWS
for db in $databases; do
    # GET LIST OF ITEMS
    views=`$MYSQL $REMOTECONNECTIONSTR --batch -N -e "select table_name from information_schema.tables where table_type='VIEW' and table_schema='$db';"`
    MYVIEWS=""
    for view in $views; do
        MYVIEWS=${MYVIEWS}" "$view" " 
    done
    echo "VIEWS "$db    
    if [ -n "$MYVIEWS" ]; then
      #VIEWS
      $MYSQLDUMP $REMOTECONNECTIONSTR --compress --quick -Q -f --no-data --skip-comments --skip-triggers --skip-opt --no-create-db --complete-insert --add-drop-table $db $MYVIEWS | \
      sed -r 's/DEFINER=`[^`]+`@`[^`]+`/DEFINER=CURRENT_USER/g'  | mysql $LOCALCONNECTION  $db  
    fi    
done

echo   "OK!"

How do I disable orientation change on Android?

Update April 2013: Don't do this. It wasn't a good idea in 2009 when I first answered the question and it really isn't a good idea now. See this answer by hackbod for reasons:

Avoid reloading activity with asynctask on orientation change in android

Add android:configChanges="keyboardHidden|orientation" to your AndroidManifest.xml. This tells the system what configuration changes you are going to handle yourself - in this case by doing nothing.

<activity android:name="MainActivity"
     android:screenOrientation="portrait"
     android:configChanges="keyboardHidden|orientation">

See Developer reference configChanges for more details.

However, your application can be interrupted at any time, e.g. by a phone call, so you really should add code to save the state of your application when it is paused.

Update: As of Android 3.2, you also need to add "screenSize":

<activity
    android:name="MainActivity"
    android:screenOrientation="portrait"
    android:configChanges="keyboardHidden|orientation|screenSize">

From Developer guide Handling the Configuration Change Yourself

Caution: Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in addition to the "orientation" value. That is, you must declare android:configChanges="orientation|screenSize". However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).

Fill an array with random numbers

If the randomness is controlled like this there can always generate any number of data points of a given range. If the random method in java is only used, we cannot guarantee that all the numbers will be unique.

_x000D_
_x000D_
package edu.iu.common;_x000D_
_x000D_
import java.util.ArrayList;_x000D_
import java.util.Random;_x000D_
_x000D_
public class RandomCentroidLocator {_x000D_
_x000D_
public static void main(String [] args){_x000D_
 _x000D_
 int min =0;_x000D_
 int max = 10;_x000D_
 int numCentroids = 10;_x000D_
 ArrayList<Integer> values = randomCentroids(min, max, numCentroids); _x000D_
 for(Integer i : values){_x000D_
  System.out.print(i+" ");_x000D_
 }_x000D_
 _x000D_
}_x000D_
_x000D_
private static boolean unique(ArrayList<Integer> arr, int num, int numCentroids) {_x000D_
_x000D_
 boolean status = true;_x000D_
 int count=0;_x000D_
 for(Integer i : arr){_x000D_
  if(i==num){_x000D_
   count++;_x000D_
  }_x000D_
 }_x000D_
 if(count==1){_x000D_
  status = true;_x000D_
 }else if(count>1){_x000D_
  status =false;_x000D_
 }_x000D_
 _x000D_
_x000D_
 return status;_x000D_
}_x000D_
_x000D_
// generate random centroid Ids -> these Ids can be used to retrieve data_x000D_
// from the data Points generated_x000D_
// simply we are picking up random items from the data points_x000D_
// in this case all the random numbers are unique_x000D_
// it provides the necessary number of unique and random centroids_x000D_
private static ArrayList<Integer> randomCentroids(int min, int max, int numCentroids) {_x000D_
_x000D_
 Random random = new Random();_x000D_
 ArrayList<Integer> values = new ArrayList<Integer>();_x000D_
 int num = -1;_x000D_
 int count = 0;_x000D_
 do {_x000D_
  num = random.nextInt(max - min + 1) + min;_x000D_
  values.add(num);_x000D_
  int index =values.size()-1;_x000D_
  if(unique(values, num, numCentroids)){    _x000D_
   count++;_x000D_
  }else{_x000D_
   values.remove(index);_x000D_
  }_x000D_
  _x000D_
 } while (!( count == numCentroids));_x000D_
_x000D_
 return values;_x000D_
_x000D_
}_x000D_
_x000D_
}
_x000D_
_x000D_
_x000D_

What is the best way to conditionally apply a class?

partial

  <div class="col-md-4 text-right">
      <a ng-class="campaign_range === 'thismonth' ? 'btn btn-blue' :  'btn btn-link'" href="#" ng-click='change_range("thismonth")'>This Month</a>
      <a ng-class="campaign_range === 'all' ? 'btn btn-blue' :  'btn btn-link'" href="#" ng-click='change_range("all")'>All Time</a>
  </div>

controller

  $scope.campaign_range = "all";
  $scope.change_range = function(range) { 
        if (range === "all")
        {
            $scope.campaign_range = "all"
        }
        else
        {  
            $scope.campaign_range = "thismonth"
        }
  };

Extract data from log file in specified range of time

You can use sed for this. For example:

$ sed -n '/Feb 23 13:55/,/Feb 23 14:00/p' /var/log/mail.log
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: connect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: lost connection after CONNECT from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: disconnect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie pop3d: Connection, ip=[::ffff:127.0.0.1]
...

How it works

The -n switch tells sed to not output each line of the file it reads (default behaviour).

The last p after the regular expressions tells it to print lines that match the preceding expression.

The expression '/pattern1/,/pattern2/' will print everything that is between first pattern and second pattern. In this case it will print every line it finds between the string Feb 23 13:55 and the string Feb 23 14:00.

More info here.

App not setup: This app is still in development mode

Issue Log: App Not Setup. This app is still in development mode. and you dont have access to it. register test user or ask an app admin for permission

  1. The app are not in Live Mode
  2. You are not listed as admin or a tester in
    https://developers.facebook.com/app/yourapp
  3. Your App Hashkey are not set. if Facebook app cant be on Live Mode you need a hashkey to test it. because the app are not yet Live. Facebook wont allow an access.

HOW TO CHANGE TO LIVE MODE
1. go to : https://developers.facebook.com
2. select your app on "My Apps" List
3. toggle the switch from OFF to ON

enter image description hereenter image description here

HOW TO ADD AS TEST OR ADMIN
1. go to : https://developers.facebook.com
2. select your app on "My Apps" List
3. go to : Roles > Roles > Press Add for example administratorenter image description here 4. Search your new admin/tester Facebook account.
enter image description here 5. admin must enter facebook password to confirm.then submit enter image description here
the new admin must go to developer.facebook page and accept the request
6. go to : https://developers.facebook.com

7. Profile > Requests > Confirm
enter image description here List item 8. Congratulation you have been assign as new Admin

HOW TO GET AND SET HASHKEY FOR DEVELOPMENT
as Refer to Facebook Login Documentation
https://developers.facebook.com/docs/android/getting-started/#create_hash
The most preferable solution by me is by code ( Troubleshooting Sample Apps )
it will print out the hash key. you can update it on
https://developers.facebook.com/apps/yourFacebookappID/settings/basic/
on Android > Key Hashes section

a step by step process on how to get the hashKey.

  1. Firstly Add the code to any oncreate method enter image description here

  2. Run The app and Search the KeyHash at Logcat enter image description here

step by step process on how Update on Facebook Developer.

  1. Open Facebook Developer Page. You need access as to update the Facebook Developer page.
    https://developers.facebook.com

  2. Follow the step as follow.enter image description here

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

I believe this might be just repeat answer, but just to clarify, I got this on a @OneToOne mapping as well as a @OneToMany. In both cases, it was the fact that the Child object I was adding to the Parent wasn't saved in the database yet. So when I added the Child to the Parent, then saved the Parent, Hibernate would toss the "object references an unsaved transient instance - save the transient instance before flushing" message when saving the Parent.

Adding in the cascade = {CascadeType.ALL} on the Parent's reference to the Child solved the problem in both cases. This saved the Child and the Parent.

Sorry for any repeat answers, just wanted to further clarify for folks.

@OneToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "performancelog_id")
public PerformanceLog getPerformanceLog() {
    return performanceLog;
}

How to get MAC address of your machine using a C program?

Assuming that c++ code (c++11) is okay as well and the interface is known.

#include <cstdint>
#include <fstream>
#include <streambuf>
#include <regex>

using namespace std;

uint64_t getIFMAC(const string &ifname) {
  ifstream iface("/sys/class/net/" + ifname + "/address");
  string str((istreambuf_iterator<char>(iface)), istreambuf_iterator<char>());
  if (str.length() > 0) {
    string hex = regex_replace(str, std::regex(":"), "");
    return stoull(hex, 0, 16);
  } else {
    return 0;
  }
} 
int main()
{
  string iface = "eth0";
  printf("%s: mac=%016llX\n", iface.c_str(), getIFMAC(iface));
}

How do I compile jrxml to get jasper?

 **A full example of POM file**.

Command to Build All **Jrxml** to **Jasper File** in maven
If you used eclipse then right click on the project and Run as maven Build and add goals antrun:run@compile-jasper-reports 


compile-jasper-reports is the id you gave in the pom file.
**<id>compile-jasper-reports</id>**




<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.test.jasper</groupId>
  <artifactId>testJasper</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>TestJasper</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <dependency>
        <groupId>net.sf.jasperreports</groupId>
        <artifactId>jasperreports</artifactId>
        <version>6.3.0</version>
    </dependency>
    <dependency>
        <groupId>net.sf.jasperreports</groupId>
        <artifactId>jasperreports-fonts</artifactId>
        <version>6.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.groovy</groupId>
        <artifactId>groovy-all</artifactId>
        <version>2.4.6</version>
    </dependency>
    <dependency>
        <groupId>com.itextpdf</groupId>
        <artifactId>itextpdf</artifactId>
        <version>5.5.6</version>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>


  </dependencies>
    <build>
    <pluginManagement>
    <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.5</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>       
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>1.8</version>
            <executions>
                <execution>
                    <id>compile-jasper-reports</id>
                    <goals>
                        <goal>run</goal>
                    </goals>
                    <phase>generate-sources</phase>
                    <configuration>
                        <target>
                            <echo message="Start compile of jasper reports" />
                            <mkdir dir="${project.build.directory}/classes/reports"/>
                            <echo message="${basedir}/src/main/resources/jasper/jasperreports" />
                            <taskdef name="jrc" classname="net.sf.jasperreports.ant.JRAntCompileTask"
                                classpathref="maven.compile.classpath" />
                                <jrc srcdir="${basedir}/src/main/resources/jasper/jasperreports" destdir="${basedir}/src/main/resources/jasper/jasperclassfile"
                                  xmlvalidation="true">
                                <classpath refid="maven.compile.classpath"/>
                                <include name="**/*.jrxml" />
                            </jrc>
                        </target>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
    </pluginManagement>
</build>
</project>

laravel select where and where condition

After rigorous testing, I found out that the source of my problem is Hash::make('password'). Apparently this kept generating a different hash each time. SO I replaced this with my own hashing function (wrote previously in codeigniter) and viola! things worked well.

Thanks again for helping out :) Really appreciate it!

OPTION (RECOMPILE) is Always Faster; Why?

There are times that using OPTION(RECOMPILE) makes sense. In my experience the only time this is a viable option is when you are using dynamic SQL. Before you explore whether this makes sense in your situation I would recommend rebuilding your statistics. This can be done by running the following:

EXEC sp_updatestats

And then recreating your execution plan. This will ensure that when your execution plan is created it will be using the latest information.

Adding OPTION(RECOMPILE) rebuilds the execution plan every time that your query executes. I have never heard that described as creates a new lookup strategy but maybe we are just using different terms for the same thing.

When a stored procedure is created (I suspect you are calling ad-hoc sql from .NET but if you are using a parameterized query then this ends up being a stored proc call) SQL Server attempts to determine the most effective execution plan for this query based on the data in your database and the parameters passed in (parameter sniffing), and then caches this plan. This means that if you create the query where there are 10 records in your database and then execute it when there are 100,000,000 records the cached execution plan may no longer be the most effective.

In summary - I don't see any reason that OPTION(RECOMPILE) would be a benefit here. I suspect you just need to update your statistics and your execution plan. Rebuilding statistics can be an essential part of DBA work depending on your situation. If you are still having problems after updating your stats, I would suggest posting both execution plans.

And to answer your question - yes, I would say it is highly unusual for your best option to be recompiling the execution plan every time you execute the query.

Posting JSON Data to ASP.NET MVC

The simplest way of doing this

I urge you to read this blog post that directly addresses your problem.

Using custom model binders isn't really wise as Phil Haack pointed out (his blog post is linked in the upper blog post as well).

Basically you have three options:

  1. Write a JsonValueProviderFactory and use a client side library like json2.js to communicate wit JSON directly.

  2. Write a JQueryValueProviderFactory that understands the jQuery JSON object transformation that happens in $.ajax or

  3. Use the very simple and quick jQuery plugin outlined in the blog post, that prepares any JSON object (even arrays that will be bound to IList<T> and dates that will correctly parse on the server side as DateTime instances) that will be understood by Asp.net MVC default model binder.

Of all three, the last one is the simplest and doesn't interfere with Asp.net MVC inner workings thus lowering possible bug surface. Using this technique outlined in the blog post will correctly data bind your strong type action parameters and validate them as well. So it is basically a win win situation.

Firing a Keyboard Event in Safari, using JavaScript

I am not very good with this but KeyboardEvent => see KeyboardEvent is initialized with initKeyEvent .
Here is an example for emitting event on <input type="text" /> element

_x000D_
_x000D_
document.getElementById("txbox").addEventListener("keypress", function(e) {_x000D_
  alert("Event " + e.type + " emitted!\nKey / Char Code: " + e.keyCode + " / " + e.charCode);_x000D_
}, false);_x000D_
_x000D_
document.getElementById("btn").addEventListener("click", function(e) {_x000D_
  var doc = document.getElementById("txbox");_x000D_
  var kEvent = document.createEvent("KeyboardEvent");_x000D_
  kEvent.initKeyEvent("keypress", true, true, null, false, false, false, false, 74, 74);_x000D_
  doc.dispatchEvent(kEvent);_x000D_
}, false);
_x000D_
<input id="txbox" type="text" value="" />_x000D_
<input id="btn" type="button" value="CLICK TO EMIT KEYPRESS ON TEXTBOX" />
_x000D_
_x000D_
_x000D_

Highcharts - how to have a chart with dynamic height?

Just don't set the height property in HighCharts and it will handle it dynamically for you so long as you set a height on the chart's containing element. It can be a fixed number or a even a percent if position is absolute.

Highcharts docs:

By default the height is calculated from the offset height of the containing element

Example: http://jsfiddle.net/wkkAd/149/

#container {
    height:100%;
    width:100%;
    position:absolute;
}

Run a script in Dockerfile

WORKDIR /scripts
COPY bootstrap.sh .
RUN ./bootstrap.sh 

ROW_NUMBER() in MySQL

From MySQL 8.0.0 and above you could natively use windowed functions.

1.4 What Is New in MySQL 8.0:

Window functions.

MySQL now supports window functions that, for each row from a query, perform a calculation using rows related to that row. These include functions such as RANK(), LAG(), and NTILE(). In addition, several existing aggregate functions now can be used as window functions; for example, SUM() and AVG().

ROW_NUMBER() over_clause :

Returns the number of the current row within its partition. Rows numbers range from 1 to the number of partition rows.

ORDER BY affects the order in which rows are numbered. Without ORDER BY, row numbering is indeterminate.

Demo:

CREATE TABLE Table1(
  id INT AUTO_INCREMENT PRIMARY KEY, col1 INT,col2 INT, col3 TEXT);

INSERT INTO Table1(col1, col2, col3)
VALUES (1,1,'a'),(1,1,'b'),(1,1,'c'),
       (2,1,'x'),(2,1,'y'),(2,2,'z');

SELECT 
    col1, col2,col3,
    ROW_NUMBER() OVER (PARTITION BY col1, col2 ORDER BY col3 DESC) AS intRow
FROM Table1;

DBFiddle Demo

How do I fix certificate errors when running wget on an HTTPS URL in Cygwin?

I have the similar problem and fixed it by temporarily disabling my antivirus(Kaspersky Free 18.0.0.405). This AV has HTTPS interception module that automatically self-sign all certificates it finds in HTTPS responses.

Wget from Cygwin does not know anything about AV root certificate, so when it finds that website's certificate was signed with non trust certificate it prints that error.

To fix this permanently without disabling AV you should copy the AV root certificate from Windows certificate store to /etc/pki/ca-trust/source/anchors as .pem file(base64 encoding) and run update-ca-trust

Calculate execution time of a SQL query?

I found this one more helpful and simple

DECLARE @StartTime datetime,@EndTime datetime   
SELECT @StartTime=GETDATE() 
--Your Query to be run goes here--  
SELECT @EndTime=GETDATE()   
SELECT DATEDIFF(ms,@StartTime,@EndTime) AS [Duration in milliseconds]   

BadImageFormatException. This will occur when running in 64 bit mode with the 32 bit Oracle client components installed

I had the same issue, then I fix it by change configuration manager x86 -> x64 and build

image

Node.js connect only works on localhost

Most probably your server socket is bound to the loopback IP address 127.0.0.1 instead of the "all IP addresses" symbolic IP 0.0.0.0 (note this is NOT a netmask). To confirm this, run sudo netstat -ntlp (If you are on linux) or netstat -an -f inet -p tcp | grep LISTEN (OSX) and check which IP your process is bound to (look for the line with ":3000"). If you see "127.0.0.1", that's the problem. Fix it by passing "0.0.0.0" to the listen call:

var app = connect().use(connect.static('public')).listen(3000, "0.0.0.0");

Content Type application/soap+xml; charset=utf-8 was not supported by service

I run into naming problem. Service name has to be exactly name of your implementation. If mismatched, it uses by default basicHttpBinding resulting in text/xml content type.

Name of your class is on two places - SVC markup and CS file.

Check endpoint contract too - again exact name of your interface, nothing more. I've added assembly name which just can't be there.

<service name="MyNamespace.MyService">
    <endpoint address="" binding="wsHttpBinding" contract="MyNamespace.IMyService" />
    <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
  </service>

Check if string contains a value in array

  $search = "web"
    $owned_urls = array('website1.com', 'website2.com', 'website3.com');
          foreach ($owned_urls as $key => $value) {
         if (stristr($value, $search) == '') {
        //not fount
        }else{
      //found
       }

this is the best approach search for any substring , case-insensitive and fast

just like like im mysql

ex:

select * from table where name = "%web%"

Show message box in case of exception

There are many ways, for example:

Method one:

public string test()
{
string ErrMsg = string.Empty;
 try
    {
        int num = int.Parse("gagw");
    }
    catch (Exception ex)
    {
        ErrMsg = ex.Message;
    }
return ErrMsg
}

Method two:

public void test(ref string ErrMsg )
{

    ErrMsg = string.Empty;
     try
        {
            int num = int.Parse("gagw");
        }
        catch (Exception ex)
        {
            ErrMsg = ex.Message;
        }
}

How to get request url in a jQuery $.get/ajax request

Since jQuery.get is just a shorthand for jQuery.ajax, another way would be to use the latter one's context option, as stated in the documentation:

The this reference within all callbacks is the object in the context option passed to $.ajax in the settings; if context is not specified, this is a reference to the Ajax settings themselves.

So you would use

$.ajax('http://www.example.org', {
  dataType: 'xml',
  data: {'a':1,'b':2,'c':3},
  context: {
    url: 'http://www.example.org'
  }
}).done(function(xml) {alert(this.url});

Jquery Chosen plugin - dynamically populate list by Ajax

The solution of @Ashivad mostly fixed my problem, but I needed to make this one-line addition to prevent the input to be erased after the results dropdown is displayed:

in success callback of the autocomplete added this line after triggering chosen:updated:

$combosearchChosen.find('input').val(request.term);

Complete listing:

var $combosearch = $('[data-combosearch]');
if (!$combosearch.length) {
  return;
}

var options = $combosearch.data('options');
console.log('combosearch', $combosearch, options);

$combosearch.chosen({
  no_results_text: "Oops, nothing found!",
  width: "60%"
});

// actual chosen container
var $combosearchChosen = $combosearch.next();

$combosearchChosen.find('input').autocomplete({
  source: function( request, response ) {
    $.ajax({
      url: options.remote_source + "&query=" + request.term,
      dataType: "json",
      beforeSend: function(){
        $('ul.chosen-results').empty();
      },
      success: function( data ) {
        response( $.map( data, function( item, index ) {
          $combosearch.append('<option value="' + item.id + '">' + item.label + '</option>');
        }));
        $combosearch.trigger('chosen:updated');
        $combosearchChosen.find('input').val(request.term);
      }
    });
  }
});

How to define multiple CSS attributes in jQuery?

You Can Try This

$("p:first").css("background-color", "#B2E0FF").css("border", "3px solid red");

'NOT LIKE' in an SQL query

You've missed the id out before the NOT; it needs to be specified.

SELECT * FROM transactions WHERE id NOT LIKE '1%' AND id NOT LIKE '2%'

How to get a list of column names

The result set of a query in PHP offers a couple of functions allowing just that:

    numCols() 
    columnName(int $column_number )

Example

    $db = new SQLIte3('mysqlite.db');
    $table = 'mytable';

    $tableCol = getColName($db, $table);

    for ($i=0; $i<count($tableCol); $i++){
        echo "Column $i = ".$tableCol[$i]."\n";
    }           

    function getColName($db, $table){
        $qry = "SELECT * FROM $table LIMIT 1";
        $result = $db->query($qry);
        $nCols = $result->numCols();
        for ($i = 0; $i < $ncols; $i++) {
            $colName[$i] = $result->columnName($i);
        }
        return $colName;
    }

How to create an Array, ArrayList, Stack and Queue in Java?

Just a small correction to the first answer in this thread.

Even for Stack, you need to create new object with generics if you are using Stack from java util packages.

Right usage:
    Stack<Integer> s = new Stack<Integer>();
    Stack<String> s1 = new Stack<String>();

    s.push(7);
    s.push(50);

    s1.push("string");
    s1.push("stack");

if used otherwise, as mentioned in above post, which is:

    /*
    Stack myStack = new Stack();
    // add any type of elements (String, int, etc..)
    myStack.push("Hello");
    myStack.push(1);
    */

Although this code works fine, has unsafe or unchecked operations which results in error.

How do I set the colour of a label (coloured text) in Java?

object.setForeground(Color.green);

*any colour you wish *object being declared earlier

Javascript ES6 export const vs export let

In ES6, imports are live read-only views on exported-values. As a result, when you do import a from "somemodule";, you cannot assign to a no matter how you declare a in the module.

However, since imported variables are live views, they do change according to the "raw" exported variable in exports. Consider the following code (borrowed from the reference article below):

//------ lib.js ------
export let counter = 3;
export function incCounter() {
    counter++;
}

//------ main1.js ------
import { counter, incCounter } from './lib';

// The imported value `counter` is live
console.log(counter); // 3
incCounter();
console.log(counter); // 4

// The imported value can’t be changed
counter++; // TypeError

As you can see, the difference really lies in lib.js, not main1.js.


To summarize:

  • You cannot assign to import-ed variables, no matter how you declare the corresponding variables in the module.
  • The traditional let-vs-const semantics applies to the declared variable in the module.
    • If the variable is declared const, it cannot be reassigned or rebound in anywhere.
    • If the variable is declared let, it can only be reassigned in the module (but not the user). If it is changed, the import-ed variable changes accordingly.

Reference: http://exploringjs.com/es6/ch_modules.html#leanpub-auto-in-es6-imports-are-live-read-only-views-on-exported-values

Possible to make labels appear when hovering over a point in matplotlib?

I have made a multi-line annotation system to add to: https://stackoverflow.com/a/47166787/10302020. for the most up to date version: https://github.com/AidenBurgess/MultiAnnotationLineGraph

Simply change the data in the bottom section.

import matplotlib.pyplot as plt


def update_annot(ind, line, annot, ydata):
    x, y = line.get_data()
    annot.xy = (x[ind["ind"][0]], y[ind["ind"][0]])
    # Get x and y values, then format them to be displayed
    x_values = " ".join(list(map(str, ind["ind"])))
    y_values = " ".join(str(ydata[n]) for n in ind["ind"])
    text = "{}, {}".format(x_values, y_values)
    annot.set_text(text)
    annot.get_bbox_patch().set_alpha(0.4)


def hover(event, line_info):
    line, annot, ydata = line_info
    vis = annot.get_visible()
    if event.inaxes == ax:
        # Draw annotations if cursor in right position
        cont, ind = line.contains(event)
        if cont:
            update_annot(ind, line, annot, ydata)
            annot.set_visible(True)
            fig.canvas.draw_idle()
        else:
            # Don't draw annotations
            if vis:
                annot.set_visible(False)
                fig.canvas.draw_idle()


def plot_line(x, y):
    line, = plt.plot(x, y, marker="o")
    # Annotation style may be changed here
    annot = ax.annotate("", xy=(0, 0), xytext=(-20, 20), textcoords="offset points",
                        bbox=dict(boxstyle="round", fc="w"),
                        arrowprops=dict(arrowstyle="->"))
    annot.set_visible(False)
    line_info = [line, annot, y]
    fig.canvas.mpl_connect("motion_notify_event",
                           lambda event: hover(event, line_info))


# Your data values to plot
x1 = range(21)
y1 = range(0, 21)
x2 = range(21)
y2 = range(0, 42, 2)
# Plot line graphs
fig, ax = plt.subplots()
plot_line(x1, y1)
plot_line(x2, y2)
plt.show()

ASP.NET DateTime Picker

@Html.EditorFor(model => model.Date, new { htmlAttributes = new { @class = "form-control", @type = "date" } })

this works well

Is it possible to use if...else... statement in React render function?

If you want to use If, else if, and else then use this method

           {this.state.value === 0 ? (
                <Component1 />
            ) : this.state.value === 1 ? (
              <Component2 />
            ) : (
              <Component3 />
            )}

Rails: Check output of path helper from console

Remember if your route is name-spaced, Like:

product GET  /products/:id(.:format)  spree/products#show

Then try :

helper.link_to("test", app.spree.product_path(Spree::Product.first), method: :get)

output

Spree::Product Load (0.4ms)  SELECT  "spree_products".* FROM "spree_products"  WHERE "spree_products"."deleted_at" IS NULL  ORDER BY "spree_products"."id" ASC LIMIT 1
=> "<a data-method=\"get\" href=\"/products/this-is-the-title\">test</a>" 

What's the Android ADB shell "dumpsys" tool and what are its benefits?

According to official Android information about dumpsys:

The dumpsys tool runs on the device and provides information about the status of system services.

To get a list of available services use

adb shell dumpsys -l

How to output (to a log) a multi-level array in a format that is human-readable?

Drupal's Devel module has other useful functions including ones that can print formatted arrays and objects to log files. See the guide at http://ratatosk.net/drupal/tutorials/debugging-drupal.html

dd()

Logs any variable to a file named “drupal_debug.txt” in the site’s temp directory. All output from this function is appended to the log file, making it easy to see how the contents of a variable change as you modify your code.

If you’re using Mac OS X you can use the Logging Console to monitor the contents of the log file.

If you’re using a flavor of Linux you can use the command “tail -f drupal_debug.txt” to watch the data being logged to the file.

How to calculate UILabel width based on text length?

Swift 4 Answer who are using Constraint

label.text = "Hello World"

var rect: CGRect = label.frame //get frame of label
rect.size = (label.text?.size(attributes: [NSFontAttributeName: UIFont(name: label.font.fontName , size: label.font.pointSize)!]))! //Calculate as per label font
labelWidth.constant = rect.width // set width to Constraint outlet

Swift 5 Answer who are using Constraint

label.text = "Hello World"

var rect: CGRect = label.frame //get frame of label
rect.size = (label.text?.size(withAttributes: [NSAttributedString.Key.font: UIFont(name: label.font.fontName , size: label.font.pointSize)!]))! //Calculate as per label font
labelWidth.constant = rect.width // set width to Constraint outlet

How to wait for a process to terminate to execute another process in batch file

This is an updated version of aphoria's Answer.

I Replaced PSLIST and PSEXEC with TASKKILL and TASKLIST`. As they seem to work better, I couldn't get PSLIST to run in Windows 7.

Also replaced Sleep with TIMEOUT.

This Was everything i needed to get the script running well, and all the additions was provided by the great guys who posted the comments.

Also if there is a delay before the .exe starts it might be worth inserting a Timeout before the :loop.

@ECHO OFF

TASKKILL NOTEPAD

START "" "C:\Program Files\Windows NT\Accessories\wordpad.exe"

:LOOP
tasklist | find /i "WORDPAD" >nul 2>&1
IF ERRORLEVEL 1 (
  GOTO CONTINUE
) ELSE (
  ECHO Wordpad is still running
  Timeout /T 5 /Nobreak
  GOTO LOOP
)

:CONTINUE
NOTEPAD

How to connect to a remote Git repository?

Like you said remote_repo_url is indeed the IP of the server, and yes it needs to be added on each PC, but it's easier to understand if you create the server first then ask each to clone it.

There's several ways to connect to the server, you can use ssh, http, or even a network drive, each has it's pros and cons. You can refer to the documentation about protocols and how to connect to the server

You can check the rest of chapter 4 for more detailed information, as it's talking about how to set up your own server

Disable cross domain web security in Firefox

While the question mentions Chrome and Firefox, there are other software without cross domain security. I mention it for people who ignore that such software exists.

For example, PhantomJS is an engine for browser automation, it supports cross domain security deactivation.

phantomjs.exe --web-security=no script.js

See this other comment of mine: Userscript to bypass same-origin policy for accessing nested iframes

Extract the last substring from a cell

Try this:

=RIGHT(TRIM(A2),LEN(TRIM(A2))-FIND(" ",TRIM(A2)))

I was able to copy/paste the formula and it worked fine.

Here is a list of Excel text functions (which worked in May 2011, and but is subject to being broken the next time Microsoft changes their website). :-(

You can use a multiple-stage-nested IF() functions to handle middle names or initials, titles, etc. if you expect them. Excel formulas do not support looping, so there are some limits to what you can do.

Date in to UTC format Java

Try this... Worked for me and printed 10/22/2013 01:37:56 AM Ofcourse this is your code only with little modifications.

final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));   // This line converts the given date into UTC time zone
final java.util.Date dateObj = sdf.parse("2013-10-22T01:37:56");

aRevisedDate = new SimpleDateFormat("MM/dd/yyyy KK:mm:ss a").format(dateObj);
System.out.println(aRevisedDate);

How do I keep jQuery UI Accordion collapsed by default?

Add the active: false option (documentation)..

$("#accordion").accordion({ header: "h3", collapsible: true, active: false });

Deploying just HTML, CSS webpage to Tomcat

Here's my setup: I am on Ubuntu 9.10.

Now, Here's what I did.

  1. Create a folder named "tomcat6-myapp" in /usr/share.
  2. Create a folder "myapp" under /usr/share/tomcat6-myapp.
  3. Copy the HTML file (that I need to deploy) to /usr/share/tomcat6-myapp/myapp. It must be named index.html.
  4. Go to /etc/tomcat6/Catalina/localhost.
  5. Create an xml file "myapp.xml" (i guess it must have the same name as the name of the folder in step 2) inside /etc/tomcat6/Catalina/localhost with the following contents.

    < Context path="/myapp" docBase="/usr/share/tomcat6-myapp/myapp" />
    
  6. This xml is called the 'Deployment Descriptor' which Tomcat reads and automatically deploys your app named "myapp".

  7. Now go to http://localhost:8080/myapp in your browser - the index.html gets picked up by tomcat and is shown.

I hope this helps!

Comparing two strings in C?

if(strcmp(sr1,str2)) // this returns 0 if strings r equal 
    flag=0;
else flag=1; // then last check the variable flag value and print the message 

                         OR

char str1[20],str2[20];
printf("enter first str > ");
gets(str1);
printf("enter second str > ");
gets(str2);

for(int i=0;str1[i]!='\0';i++)
{
    if(str[i]==str2[i])
         flag=0;
    else {flag=1; break;}
}

 //check the value of flag if it is 0 then strings r equal simple :)

C# - Simplest way to remove first occurrence of a substring from another string

If you'd like a simple method to resolve this problem. (Can be used as an extension)

See below:

    public static string RemoveFirstInstanceOfString(this string value, string removeString)
    {
        int index = value.IndexOf(removeString, StringComparison.Ordinal);
        return index < 0 ? value : value.Remove(index, removeString.Length);
    }

Usage:

    string valueWithPipes = "| 1 | 2 | 3";
    string valueWithoutFirstpipe = valueWithPipes.RemoveFirstInstanceOfString("|");
    //Output, valueWithoutFirstpipe = " 1 | 2 | 3";

Inspired by and modified @LukeH's and @Mike's answer.

Don't forget the StringComparison.Ordinal to prevent issues with Culture settings. https://www.jetbrains.com/help/resharper/2018.2/StringIndexOfIsCultureSpecific.1.html

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

it seems when target sdk is pie (api level 28.0) and windowIsTranslucent is true

<item name="android:windowIsTranslucent">true</item>

and you try to access orientation. problem comes with android oreo 8.0 (api level 26) there are two ways to solve this

  1. remove the orientation
  2. or set windowIsTranslucent to false

if you are setting orientation in manifest like this

android:screenOrientation="portrait"

or in activity class like this

 setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

remove form both places.

and observed when u set windowIsTranslucent to true, it takes orientation from parent activity.

How do I set the driver's python version in spark?

I just faced the same issue and these are the steps that I follow in order to provide Python version. I wanted to run my PySpark jobs with Python 2.7 instead of 2.6.

  1. Go to the folder where $SPARK_HOME is pointing to (in my case is /home/cloudera/spark-2.1.0-bin-hadoop2.7/)

  2. Under folder conf, there is a file called spark-env.sh. In case you have a file called spark-env.sh.template you will need to copy the file to a new file called spark-env.sh.

  3. Edit the file and write the next three lines

    export PYSPARK_PYTHON=/usr/local/bin/python2.7

    export PYSPARK_DRIVER_PYTHON=/usr/local/bin/python2.7

    export SPARK_YARN_USER_ENV="PYSPARK_PYTHON=/usr/local/bin/python2.7"

  4. Save it and launch your application again :)

In that way, if you download a new Spark standalone version, you can set the Python version which you want to run PySpark to.

non static method cannot be referenced from a static context

Violating the Java naming conventions (variable names and method names start with lowercase, class names start with uppercase) is contributing to your confusion.

The variable Random is only "in scope" inside the main method. It's not accessible to any methods called by main. When you return from main, the variable disappears (it's part of the stack frame).

If you want all of the methods of your class to use the same Random instance, declare a member variable:

class MyObj {
  private final Random random = new Random();
  public void compTurn() {
    while (true) {
      int a = random.nextInt(10);
      if (possibles[a] == 1) 
        break;
    }
  }
}

JavaScript Promises - reject vs. throw

Another important fact is that reject() DOES NOT terminate control flow like a return statement does. In contrast throw does terminate control flow.

Example:

_x000D_
_x000D_
new Promise((resolve, reject) => {_x000D_
  throw "err";_x000D_
  console.log("NEVER REACHED");_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
_x000D_
_x000D_

vs

_x000D_
_x000D_
new Promise((resolve, reject) => {_x000D_
  reject(); // resolve() behaves similarly_x000D_
  console.log("ALWAYS REACHED"); // "REJECTED" will print AFTER this_x000D_
})_x000D_
.then(() => console.log("RESOLVED"))_x000D_
.catch(() => console.log("REJECTED"));
_x000D_
_x000D_
_x000D_

How to simulate target="_blank" in JavaScript

This might help you to open all page links:

$(".myClass").each(
     function(i,e){
        window.open(e, '_blank');
     }
);

It will open every <a href="" class="myClass"></a> link items to another tab like you would had clicked each one.

You only need to paste it to browser console. jQuery framework required

Is it possible that one domain name has multiple corresponding IP addresses?

Yes this is possible, however not convenient as Jens said. Using Next generation load balancers like Alteon, which Uses a proprietary protocol called DSSP(Distributed site state Protocol) which performs regular site checks to make sure that the service is available both Locally or Globally i.e different geographical areas. You need to however in your Master DNS to delegate the URL or Service to the device by configuring it as an Authoritative Name Server for that IP or Service. By doing this, the device answers DNS queries where it will resolve the IP that has a service by Round-Robin or is not congested according to how you have chosen from several metrics.

How to detect incoming calls, in an Android device?

With Android P - Api Level 28: You need to get READ_CALL_LOG permission

Restricted access to call logs

Android P moves the CALL_LOG, READ_CALL_LOG, WRITE_CALL_LOG, and PROCESS_OUTGOING_CALLS permissions from the PHONE permission group to the new CALL_LOG permission group. This group gives users better control and visibility to apps that need access to sensitive information about phone calls, such as reading phone call records and identifying phone numbers.

To read numbers from the PHONE_STATE intent action, you need both the READ_CALL_LOG permission and the READ_PHONE_STATE permission. To read numbers from onCallStateChanged(), you now need the READ_CALL_LOG permission only. You no longer need the READ_PHONE_STATE permission.

Secure hash and salt for PHP passwords

DISCLAIMER: This answer was written in 2008.

Since then, PHP has given us password_hash and password_verify and, since their introduction, they are the recommended password hashing & checking method.

The theory of the answer is still a good read though.

TL;DR

Don'ts

  • Don't limit what characters users can enter for passwords. Only idiots do this.
  • Don't limit the length of a password. If your users want a sentence with supercalifragilisticexpialidocious in it, don't prevent them from using it.
  • Don't strip or escape HTML and special characters in the password.
  • Never store your user's password in plain-text.
  • Never email a password to your user except when they have lost theirs, and you sent a temporary one.
  • Never, ever log passwords in any manner.
  • Never hash passwords with SHA1 or MD5 or even SHA256! Modern crackers can exceed 60 and 180 billion hashes/second (respectively).
  • Don't mix bcrypt and with the raw output of hash(), either use hex output or base64_encode it. (This applies to any input that may have a rogue \0 in it, which can seriously weaken security.)

Dos

  • Use scrypt when you can; bcrypt if you cannot.
  • Use PBKDF2 if you cannot use either bcrypt or scrypt, with SHA2 hashes.
  • Reset everyone's passwords when the database is compromised.
  • Implement a reasonable 8-10 character minimum length, plus require at least 1 upper case letter, 1 lower case letter, a number, and a symbol. This will improve the entropy of the password, in turn making it harder to crack. (See the "What makes a good password?" section for some debate.)

Why hash passwords anyway?

The objective behind hashing passwords is simple: preventing malicious access to user accounts by compromising the database. So the goal of password hashing is to deter a hacker or cracker by costing them too much time or money to calculate the plain-text passwords. And time/cost are the best deterrents in your arsenal.

Another reason that you want a good, robust hash on a user accounts is to give you enough time to change all the passwords in the system. If your database is compromised you will need enough time to at least lock the system down, if not change every password in the database.

Jeremiah Grossman, CTO of Whitehat Security, stated on White Hat Security blog after a recent password recovery that required brute-force breaking of his password protection:

Interestingly, in living out this nightmare, I learned A LOT I didn’t know about password cracking, storage, and complexity. I’ve come to appreciate why password storage is ever so much more important than password complexity. If you don’t know how your password is stored, then all you really can depend upon is complexity. This might be common knowledge to password and crypto pros, but for the average InfoSec or Web Security expert, I highly doubt it.

(Emphasis mine.)

What makes a good password anyway?

Entropy. (Not that I fully subscribe to Randall's viewpoint.)

In short, entropy is how much variation is within the password. When a password is only lowercase roman letters, that's only 26 characters. That isn't much variation. Alpha-numeric passwords are better, with 36 characters. But allowing upper and lower case, with symbols, is roughly 96 characters. That's a lot better than just letters. One problem is, to make our passwords memorable we insert patterns—which reduces entropy. Oops!

Password entropy is approximated easily. Using the full range of ascii characters (roughly 96 typeable characters) yields an entropy of 6.6 per character, which at 8 characters for a password is still too low (52.679 bits of entropy) for future security. But the good news is: longer passwords, and passwords with unicode characters, really increase the entropy of a password and make it harder to crack.

There's a longer discussion of password entropy on the Crypto StackExchange site. A good Google search will also turn up a lot of results.

In the comments I talked with @popnoodles, who pointed out that enforcing a password policy of X length with X many letters, numbers, symbols, etc, can actually reduce entropy by making the password scheme more predictable. I do agree. Randomess, as truly random as possible, is always the safest but least memorable solution.

So far as I've been able to tell, making the world's best password is a Catch-22. Either its not memorable, too predictable, too short, too many unicode characters (hard to type on a Windows/Mobile device), too long, etc. No password is truly good enough for our purposes, so we must protect them as though they were in Fort Knox.

Best practices

Bcrypt and scrypt are the current best practices. Scrypt will be better than bcrypt in time, but it hasn't seen adoption as a standard by Linux/Unix or by webservers, and hasn't had in-depth reviews of its algorithm posted yet. But still, the future of the algorithm does look promising. If you are working with Ruby there is an scrypt gem that will help you out, and Node.js now has its own scrypt package. You can use Scrypt in PHP either via the Scrypt extension or the Libsodium extension (both are available in PECL).

I highly suggest reading the documentation for the crypt function if you want to understand how to use bcrypt, or finding yourself a good wrapper or use something like PHPASS for a more legacy implementation. I recommend a minimum of 12 rounds of bcrypt, if not 15 to 18.

I changed my mind about using bcrypt when I learned that bcrypt only uses blowfish's key schedule, with a variable cost mechanism. The latter lets you increase the cost to brute-force a password by increasing blowfish's already expensive key schedule.

Average practices

I almost can't imagine this situation anymore. PHPASS supports PHP 3.0.18 through 5.3, so it is usable on almost every installation imaginable—and should be used if you don't know for certain that your environment supports bcrypt.

But suppose that you cannot use bcrypt or PHPASS at all. What then?

Try an implementation of PDKBF2 with the maximum number of rounds that your environment/application/user-perception can tolerate. The lowest number I'd recommend is 2500 rounds. Also, make sure to use hash_hmac() if it is available to make the operation harder to reproduce.

Future Practices

Coming in PHP 5.5 is a full password protection library that abstracts away any pains of working with bcrypt. While most of us are stuck with PHP 5.2 and 5.3 in most common environments, especially shared hosts, @ircmaxell has built a compatibility layer for the coming API that is backward compatible to PHP 5.3.7.

Cryptography Recap & Disclaimer

The computational power required to actually crack a hashed password doesn't exist. The only way for computers to "crack" a password is to recreate it and simulate the hashing algorithm used to secure it. The speed of the hash is linearly related to its ability to be brute-forced. Worse still, most hash algorithms can be easily parallelized to perform even faster. This is why costly schemes like bcrypt and scrypt are so important.

You cannot possibly foresee all threats or avenues of attack, and so you must make your best effort to protect your users up front. If you do not, then you might even miss the fact that you were attacked until it's too late... and you're liable. To avoid that situation, act paranoid to begin with. Attack your own software (internally) and attempt to steal user credentials, or modify other user's accounts or access their data. If you don't test the security of your system, then you cannot blame anyone but yourself.

Lastly: I am not a cryptographer. Whatever I've said is my opinion, but I happen to think it's based on good ol' common sense ... and lots of reading. Remember, be as paranoid as possible, make things as hard to intrude as possible, and then, if you are still worried, contact a white-hat hacker or cryptographer to see what they say about your code/system.

collapse cell in jupyter notebook

I had a similar issue and the "nbextensions" pointed out by @Energya worked very well and effortlessly. The install instructions are straight forward (I tried with anaconda on Windows) for the notebook extensions and for their configurator.

That said, I would like to add that the following extensions should be of interest.

  • Hide Input | This extension allows hiding of an individual codecell in a notebook. This can be achieved by clicking on the toolbar button: Hide Input

  • Collapsible Headings | Allows notebook to have collapsible sections, separated by headings Collapsible Headings

  • Codefolding | This has been mentioned but I add it for completeness Codefolding

How to call javascript from a href?

 <a href="javascript:
  console.dir(Object.getOwnPropertyDescriptors(HTMLDivElement))">
       1. Direct Action Without Following href Link
  </a>

<br><br>

  <a href="javascript:my_func('http://diasmath.blogg.org')">
      2. Indirect Action (Function Call) Without Following Normal href Link
  </a>

<br><br>

 <!-- Avec « return false » l'action par défaut de l'élément
 // <a></a> (ouverture de l'URL pointée par
 // « href="http://www.centerblog.net/gha" »)
 // ne s'exécute pas.
 -->
 <a target=_new href="http://www.centerblog.net/gha"
          onclick="my_func('http://diasmath.blogg.org');
 return false">
     3. Suivi par défaut du Lien Normal href Désactivé avec
     « return false »
  </a>

<br><br>

 <!-- Avec ou sans « return true » l'action par défaut de l'élément
 // s'exécute pas.
 -->
 <a target=_new href="http://gha.centerblog.net"
          onclick="my_func('http://diasmath.blogg.org');">
     4. Suivi par défaut du Lien Normal href Conservé avec ou sans
     « return true » qui est la valeur retournée par défaut.
  </a>

<br><br>

<!-- Le diese tout seul ne suit pas le lien href. -->
  <a href="#" onclick="my_func('http://diasmath.blogg.org')">
      5. Lien Dièse en Singleton (pas de suivi href)
  </a>

  <script language="JavaScript">
   function my_func(s) {
       console.dir(Object.getOwnPropertyDescriptors(Document));
       window.open(s)
   }
  </script>

<br>
<br>

 <!-- Avec GESTION D'ÉVÉNEMENT.
 // Événement (event) = click du lien
 // Event Listener = "click"
 // my_func2 = gestionnaire d'événement
 -->
  <script language="JavaScript">
   function my_func2(event) {
      console.dir(event);
      window.open(event.originalTarget["href"])
   }
  </script>
 <a target=_blank href="http://dmedit.centerblog.net"
     id="newel" onclick="return false">
     6. By specifying another eventlistener
     (and deactivating the default).
  </a>
  <script language="JavaScript">
      let a=document.getElementById("newel");
      a.addEventListener("click",my_func2)
  </script>

Android - Dynamically Add Views into View

See the LayoutInflater class.

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup parent = (ViewGroup)findViewById(R.id.where_you_want_to_insert);
inflater.inflate(R.layout.the_child_view, parent);

How to resize an image to a specific size in OpenCV?

Make a useful function like this:

IplImage* img_resize(IplImage* src_img, int new_width,int new_height)
{
    IplImage* des_img;
    des_img=cvCreateImage(cvSize(new_width,new_height),src_img->depth,src_img->nChannels);
    cvResize(src_img,des_img,CV_INTER_LINEAR);
    return des_img;
} 

How to get Time from DateTime format in SQL?

Try this:

select  convert(nvarchar,CAST(getdate()as time),100)

Where to install Android SDK on Mac OS X?

From http://developer.android.com/sdk/index.html, it seems that you can install the SDK anywhere, so long as you

  1. "execute the android tool in the <sdk>/tools/ folder"
  2. Add the <sdk>/tools directory to your system path

More info can be found here: http://developer.android.com/sdk/installing.html

How to compare Boolean?

As long as checker is not null, you may use !checker as posted. This is possible since Java 5, because this Boolean variable will be autoboxed to the primivite boolean value.

Error "The connection to adb is down, and a severe error has occurred."

Add android-sdks/platform-tools to the Windows PATH environment variable.

git pull fails "unable to resolve reference" "unable to update local ref"

Explanation: It appears your remote repo (in Github / bitbucket) branches were removed ,though your local references were not updated and pointing to non existent references.

In order to solve this issue:

git fetch --prune
git fetch --all
git pull

For extra reading - Reference from Github documentation :

git-fetch - Download objects and refs from another repository

--all Fetch all remotes.

--prune After fetching, remove any remote tracking branches which no longer exist on the remote.

How to remove a build from itunes connect?

UPDATE:

Time has changed, you can now remove (expire) TestFlight Builds as in this answer but you still cannot delete the build.

OLD:

I asked apple and here is their answer:

I understand you would like to remove a build from iTunes Connect as shown in your screenshot.

Please be advised this is expected behavior as you can remove a build from being the current build but you cannot delete it from iTunes Connect. For more information, please refer to the iTunes Connect Developer Guide: https://developer.apple.com/library/content/documentation/LanguagesUtilities/Conceptual/iTunesConnect_Guide/

So i just can't.

Spring @PropertySource using YAML

From Spring Boot 1.4, you can use the new @SpringBootTest annotation to achieve this more easily (and to simplify your integration test setup in general) by bootstrapping your integration tests using Spring Boot support.

Details on the Spring Blog.

As far as I can tell, this means you get all the benefits of Spring Boot's externalized config goodness just like in your production code, including automatically picking up YAML config from the classpath.

By default, this annotation will

... first attempt to load @Configuration from any inner-classes, and if that fails, it will search for your primary @SpringBootApplication class.

but you can specify other configuration classes if required.

For this particular case, you can combine @SpringBootTest with @ActiveProfiles( "test" ) and Spring will pick up your YAML config, provided it follows the normal Boot naming standards (i.e. application-test.yml).

@RunWith( SpringRunner.class )
@SpringBootTest
@ActiveProfiles( "test" )
public class SpringBootITest {

    @Value("${db.username}")
    private String username;

    @Autowired
    private MyBean myBean;

    ...

}

Note: SpringRunner.class is the new name for SpringJUnit4ClassRunner.class

Contain form within a bootstrap popover?

I would put my form into the markup and not into some data tag. This is how it could work:

JS Code:

$('#popover').popover({ 
    html : true,
    title: function() {
      return $("#popover-head").html();
    },
    content: function() {
      return $("#popover-content").html();
    }
});

HTML Markup:

<a href="#" id="popover">the popover link</a>
<div id="popover-head" class="hide">
  some title
</div>
<div id="popover-content" class="hide">
  <!-- MyForm -->
</div>

Demo

Alternative Approaches:

X-Editable

You might want to take a look at X-Editable. A library that allows you to create editable elements on your page based on popovers.

X-Editable demo

Webcomponents

Mike Costello has released Bootstrap Web Components. This nifty library has a Popovers Component that lets you embed the form as markup:

<button id="popover-target" data-original-title="MyTitle" title="">Popover</button>

<bs-popover title="Popover with Title" for="popover-target">
  <!-- MyForm -->
</bs-popover>

Demo

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

Removing u in list

u'AB' is just a text representation of the corresponding Unicode string. Here're several methods that create exactly the same Unicode string:

L = [u'AB', u'\x41\x42', u'\u0041\u0042', unichr(65) + unichr(66)]
print u", ".join(L)

Output

AB, AB, AB, AB

There is no u'' in memory. It is just the way to represent the unicode object in Python 2 (how you would write the Unicode string literal in a Python source code). By default print L is equivalent to print "[%s]" % ", ".join(map(repr, L)) i.e., repr() function is called for each list item:

print L
print "[%s]" % ", ".join(map(repr, L))

Output

[u'AB', u'AB', u'AB', u'AB']
[u'AB', u'AB', u'AB', u'AB']

If you are working in a REPL then a customizable sys.displayhook is used that calls repr() on each object by default:

>>> L = [u'AB', u'\x41\x42', u'\u0041\u0042', unichr(65) + unichr(66)]
>>> L
[u'AB', u'AB', u'AB', u'AB']
>>> ", ".join(L)
u'AB, AB, AB, AB'
>>> print ", ".join(L)
AB, AB, AB, AB

Don't encode to bytes. Print unicode directly.


In your specific case, I would create a Python list and use json.dumps() to serialize it instead of using string formatting to create JSON text:

#!/usr/bin/env python2
import json
# ...
test = [dict(email=player.email, gem=player.gem)
        for player in players]
print test
print json.dumps(test)

Output

[{'email': u'[email protected]', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test', 'gem': 0}, {'email': u'test1', 'gem': 0}]
[{"email": "[email protected]", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test", "gem": 0}, {"email": "test1", "gem": 0}]

How to download a folder from github?

Use GitZip online tool. It allows to download a sub-directory of a github repository as a zip file. No git commands needed!

Dynamically replace img src attribute with jQuery

This is what you wanna do:

var oldSrc = 'http://example.com/smith.gif';
var newSrc = 'http://example.com/johnson.gif';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);

Python, print all floats to 2 decimal places in output

I have just discovered the round function - it is in Python 2.7, not sure about 2.6. It takes a float and the number of dps as arguments, so round(22.55555, 2) gives the result 22.56.

ERROR: ld.so: object LD_PRELOAD cannot be preloaded: ignored

If you want to make sure that the library is loaded if and only if the program lunar-calendar-gtk is launched, you can apply this:

You set the environment variable per command by prefixing the command with it:

$ LD_PRELOAD="liblunar-calendar-preload.so" printenv "LD_PRELOAD"
liblunar-calendar-preload.so
$ printenv "LD_PRELOAD"
$

You can then choose to put this in a shell script and make lunar-calendar-gtk a symlink to this shell script, replaceing the original referencee. This effectively makes sure that the library is loaded everytime the original application is executed.

You will have to rename the original lunar-calendar-gtk to something else, which might not be too intriguing as it possibly may cause issues with uninstallation and upgrading. However, I found it useful with a former version of Skype.

Prevent scroll-bar from adding-up to the Width of page on Chrome

I can't add comment for the first answer and it's been a long time... but that demo has a problem:

if(b.prop('scrollHeight')>b.height()){
    normalw = window.innerWidth;
    scrollw = normalw - b.width();
    $('#container').css({marginRight:'-'+scrollw+'px'});
}

b.prop('scrollHeight') always equals b.height(),

I think it should be like this:

if(b.prop('scrollHeight')>window.innerHeight) ...

At last I recommend a method:

html {
 overflow-y: scroll;
}

:root {
  overflow-y: auto;
  overflow-x: hidden;
}

:root body {
  position: absolute;
}

body {
 width: 100vw;
 overflow: hidden;
}

How to comment multiple lines with space or indent

I was able to achieve the desired result by using Alt + Shift + up/down and then typing the desired comment characters and additional character.

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME

Storing database records into array

You shouldn't search through that array, but use database capabilities for this
Suppose you're passing username through GET form:

if (isset($_GET['search'])) {
  $search = mysql_real_escape_string($_GET['search']);
  $sql = "SELECT * FROM users WHERE username = '$search'";
  $res = mysql_query($sql) or trigger_error(mysql_error().$sql);
  $row = mysql_fetch_assoc($res);
  if ($row){
    print_r($row); //do whatever you want with found info
  }
}

No matching bean of type ... found for dependency

Add annotation @Repository to the head of userDao Class.If userDao is a interface,add this annotation to the implements of the interface.

File path to resource in our war/WEB-INF folder?

There's a couple ways of doing this. As long as the WAR file is expanded (a set of files instead of one .war file), you can use this API:

ServletContext context = getContext();
String fullPath = context.getRealPath("/WEB-INF/test/foo.txt");

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getRealPath(java.lang.String)

That will get you the full system path to the resource you are looking for. However, that won't work if the Servlet Container never expands the WAR file (like Tomcat). What will work is using the ServletContext's getResource methods.

ServletContext context = getContext();
URL resourceUrl = context.getResource("/WEB-INF/test/foo.txt");

or alternatively if you just want the input stream:

InputStream resourceContent = context.getResourceAsStream("/WEB-INF/test/foo.txt");

http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContext.html#getResource(java.lang.String)

The latter approach will work no matter what Servlet Container you use and where the application is installed. The former approach will only work if the WAR file is unzipped before deployment.

EDIT: The getContext() method is obviously something you would have to implement. JSP pages make it available as the context field. In a servlet you get it from your ServletConfig which is passed into the servlet's init() method. If you store it at that time, you can get your ServletContext any time you want after that.

Why do 64-bit DLLs go to System32 and 32-bit DLLs to SysWoW64 on 64-bit Windows?

Other folks have already done a good job of explaining this ridiculus conundrum ... and I think Chris Hoffman did an even better job here: https://www.howtogeek.com/326509/whats-the-difference-between-the-system32-and-syswow64-folders-in-windows/

My two thoughts:

  1. We all make stupid short-sighted mistakes in life. When Microsoft named their (at the time) Win32 DLL directory "System32", it made sense at the time ... they just didn't take into consideration what would happen if/when a 64-bit (or 128-bit) version of their OS got developed later - and the massive backward compatibility issue such a directory name would cause. Hindsight is always 20-20, so I can't really blame them (too much) for such a mistake. ...HOWEVER... When Microsoft did later develop their 64-bit operating system, even with the benefit of hindsight, why oh why would they make not only the exact same short-sighted mistake AGAIN but make it even worse by PURPOSEFULLY giving it such a misleading name?!? Shame on them!!! Why not AT LEAST actually name the directory "SysWin32OnWin64" to avoid confusion?!? And what happens when they eventually produce a 128-bit OS ... then where are they going to put their 32-bit, 64-bit, and 128-bit DLLs?!?

  2. All of this logic still seems completely flawed to me. On 32-bit versions of Windows, System32 contains 32-bit DLLs; on 64-bit versions of Windows, System32 contains 64-bit DLLs ... so that developers wouldn't have to make code changes, correct? The problem with this logic is that those developers are either now making 64-bit apps needing 64-bit DLLs or they're making 32-bit apps needing 32-bit DLLs ... either way, aren't they still screwed? I mean, if they're still making a 32-bit app, for it to now run on a 64-bit Windows, they'll now need to make a code change to find/reference the same ol' 32-bit DLL they used before (now located in SysWOW64). Or, if they're working on a 64-bit app, they're going to need to re-write their old app for the new OS anyway ... so a recompile/rebuild was going to be needed anyway!!!

Microsoft just hurts me sometimes.