Programs & Examples On #Debugging

Debugging is a methodical process of finding and fixing bugs in a computer program. **IMPORTANT NOTE:** This tag is ONLY for questions about debugging techniques or the process of debugging itself, NOT for requesting help debugging your code.

Is there a good Valgrind substitute for Windows?

Does Jochen Kalmbach's Memory Leak Detector qualify?

PS: The URL to the latest version is buried somewhere in the article's comment thread.

JavaScript: How do I print a message to the error console?

If you use Safari, you can write

console.log("your message here");

and it appears right on the console of the browser.

Is there a C++ gdb GUI for Linux?

As someone familiar with Visual Studio, I've looked at several open source IDE's to replace it, and KDevelop comes the closest IMO to being something that a Visual C++ person can just sit down and start using. When you run the project in debugging mode, it uses gdb but kdevelop pretty much handles the whole thing so that you don't have to know it's gdb; you're just single stepping or assigning watches to variables.

It still isn't as good as the Visual Studio Debugger, unfortunately.

How can I inspect the file system of a failed `docker build`?

Everytime docker successfully executes a RUN command from a Dockerfile, a new layer in the image filesystem is committed. Conveniently you can use those layers ids as images to start a new container.

Take the following Dockerfile:

FROM busybox
RUN echo 'foo' > /tmp/foo.txt
RUN echo 'bar' >> /tmp/foo.txt

and build it:

$ docker build -t so-2622957 .
Sending build context to Docker daemon 47.62 kB
Step 1/3 : FROM busybox
 ---> 00f017a8c2a6
Step 2/3 : RUN echo 'foo' > /tmp/foo.txt
 ---> Running in 4dbd01ebf27f
 ---> 044e1532c690
Removing intermediate container 4dbd01ebf27f
Step 3/3 : RUN echo 'bar' >> /tmp/foo.txt
 ---> Running in 74d81cb9d2b1
 ---> 5bd8172529c1
Removing intermediate container 74d81cb9d2b1
Successfully built 5bd8172529c1

You can now start a new container from 00f017a8c2a6, 044e1532c690 and 5bd8172529c1:

$ docker run --rm 00f017a8c2a6 cat /tmp/foo.txt
cat: /tmp/foo.txt: No such file or directory

$ docker run --rm 044e1532c690 cat /tmp/foo.txt
foo

$ docker run --rm 5bd8172529c1 cat /tmp/foo.txt
foo
bar

of course you might want to start a shell to explore the filesystem and try out commands:

$ docker run --rm -it 044e1532c690 sh      
/ # ls -l /tmp
total 4
-rw-r--r--    1 root     root             4 Mar  9 19:09 foo.txt
/ # cat /tmp/foo.txt 
foo

When one of the Dockerfile command fails, what you need to do is to look for the id of the preceding layer and run a shell in a container created from that id:

docker run --rm -it <id_last_working_layer> bash -il

Once in the container:

  • try the command that failed, and reproduce the issue
  • then fix the command and test it
  • finally update your Dockerfile with the fixed command

If you really need to experiment in the actual layer that failed instead of working from the last working layer, see Drew's answer.

Watching variables in SSIS during debug

I know this is very old and possibly talking about an older version of Visual studio and so this might not have been an option before but anyway, my way would be when at a breakpoint use the locals window to see all current variable values ( Debug >> Windows >> Locals )

Step-by-step debugging with IPython

the right, easy, cool, exact answer for the question is to use %run macro with -d flag.

In [4]: run -d myscript.py
NOTE: Enter 'c' at the ipdb>  prompt to continue execution.        
> /cygdrive/c/Users/mycodefolder/myscript.py(4)<module>()
      2                                                            
      3                        
----> 4 a=1                                            
      5 b=2

The thread has exited with code 0 (0x0) with no unhandled exception

In order to complete BlueM's accepted answer, you can desactivate it here:

Tools > Options > Debugging > General Output Settings > Thread Exit Messages : Off

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

Like @Nycen I also got this error because of a link to Cloudfare. Mine was for the Select2 plugin.

to fix it I just removed

 src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"

and the error went away.

Watching variables contents in Eclipse IDE

This video does an excellent job of showing you how to set breakpoints and watch variables in the Eclipse Debugger. http://youtu.be/9gAjIQc4bPU

Visual Studio: How to break on handled exceptions?

A technique I use is something like the following. Define a global variable that you can use for one or multiple try catch blocks depending on what you're trying to debug and use the following structure:

if(!GlobalTestingBool)
{
   try
   {
      SomeErrorProneMethod();
   }
   catch (...)
   {
      // ... Error handling ...
   }
}
else
{
   SomeErrorProneMethod();
}

I find this gives me a bit more flexibility in terms of testing because there are still some exceptions I don't want the IDE to break on.

How to track down a "double free or corruption" error

Are you using smart pointers such as Boost shared_ptr? If so, check if you are directly using the raw pointer anywhere by calling get(). I've found this to be quite a common problem.

For example, imagine a scenario where a raw pointer is passed (maybe as a callback handler, say) to your code. You might decide to assign this to a smart pointer in order to cope with reference counting etc. Big mistake: your code doesn't own this pointer unless you take a deep copy. When your code is done with the smart pointer it will destroy it and attempt to destroy the memory it points to since it thinks that no-one else needs it, but the calling code will then try to delete it and you'll get a double free problem.

Of course, that might not be your problem here. At it's simplest here's an example which shows how it can happen. The first delete is fine but the compiler senses that it's already deleted that memory and causes a problem. That's why assigning 0 to a pointer immediately after deletion is a good idea.

int main(int argc, char* argv[])
{
    char* ptr = new char[20];

    delete[] ptr;
    ptr = 0;  // Comment me out and watch me crash and burn.
    delete[] ptr;
}

Edit: changed delete to delete[], as ptr is an array of char.

Break when a value changes using the Visual Studio debugger

Really old post but in case someone is unaware...

In Visual Studio 2015, you can place a breakpoint on the set accessor of an Auto-Implemented Property and the debugger will break when the property is updated

public bool IsUpdated
{
    get;
    set;    //set breakpoint on this line
}

Update

Alternatively; @AbdulRaufMujahid has pointed out in the comments that if the auto implemented property is on a single line, you can position your cursor at the get; or set; and hit F9 and a breakpoint will be placed accordingly. Nice!

public bool IsUpdated { get; set; }

Write to rails console

In addition to already suggested p and puts — well, actually in most cases you do can write logger.info "blah" just as you suggested yourself. It works in console too, not only in server mode.

But if all you want is console debugging, puts and p are much shorter to write, anyway.

How do you get assembler output from C/C++ source in gcc?

Use the -S switch

g++ -S main.cpp

or also with gcc

gcc -S main.c

Also see this

Using NSLog for debugging

type : BOOL DATA (YES/NO) OR(1/0)

BOOL dtBool = 0; 

OR

BOOL dtBool = NO;
NSLog(dtBool ? @"Yes" : @"No");

OUTPUT : NO

type : Long

long aLong = 2015;
NSLog(@"Display Long: %ld”, aLong);

OUTPUT : Display Long: 2015

long long veryLong = 20152015;
NSLog(@"Display very Long: %lld", veryLong);

OUTPUT : Display very Long: 20152015

type : String

NSString *aString = @"A string";
NSLog(@"Display string: %@", aString);

OUTPUT : Display String: a String

type : Float

float aFloat = 5.34245;
NSLog(@"Display Float: %F", aFloat);

OUTPUT : isplay Float: 5.342450

type : Integer

int aInteger = 3;    
NSLog(@"Display Integer: %i", aInteger);

OUTPUT : Display Integer: 3

NSLog(@"\nDisplay String: %@ \n\n Display Float: %f \n\n Display Integer: %i", aString, aFloat, aInteger);

OUTPUT : String: a String

Display Float: 5.342450

Display Integer: 3

http://luterr.blogspot.sg/2015/04/example-code-nslog-console-commands-to.html

Eclipse doesn't stop at breakpoints

Please un check this from the Eclipse Menu.

Run->Skip all breakpoints.

I think this will be enabled permanently once You select the Remove all Break points option in the Debug/Breakpoints window.

How can one grab a stack trace in C?

You should be using the unwind library.

unw_cursor_t cursor; unw_context_t uc;
unw_word_t ip, sp;
unw_getcontext(&uc);
unw_init_local(&cursor, &uc);
unsigned long a[100];
int ctr = 0;

while (unw_step(&cursor) > 0) {
  unw_get_reg(&cursor, UNW_REG_IP, &ip);
  unw_get_reg(&cursor, UNW_REG_SP, &sp);
  if (ctr >= 10) break;
  a[ctr++] = ip;
}

Your approach also would work fine unless you make a call from a shared library.

You can use the addr2line command on Linux to get the source function / line number of the corresponding PC.

How can I get the full object in Node.js's console.log(), rather than '[Object]'?

You can simply add an inspect() method to your object which will override the representation of object in console.log messages

eg:

var myObject = {
   "a":"a",
   "b":{
      "c":"c",
      "d":{
         "e":"e",
         "f":{
            "g":"g",
            "h":{
               "i":"i"
            }
         }
      }
   }
};
myObject.inspect = function(){ return JSON.stringify( this, null, ' ' ); }

then, your object will be represented as required in both console.log and node shell


Update:

object.inspect has been deprecated ( https://github.com/nodejs/node/issues/15549). Use myObject[util.inspect.custom] instead:

const util = require('util')

var myObject = {
  /* nested properties not shown */
}

myObject[util.inspect.custom] = function(){ return JSON.stringify( this, null, 4 ); }


console.log(util.inspect(myObject))

What is a stack trace, and how can I use it to debug my application errors?

The other posts describe what a stack trace is, but it can still be hard to work with.

If you get a stack trace and want to trace the cause of the exception, a good start point in understanding it is to use the Java Stack Trace Console in Eclipse. If you use another IDE there may be a similar feature, but this answer is about Eclipse.

First, ensure that you have all of your Java sources accessible in an Eclipse project.

Then in the Java perspective, click on the Console tab (usually at the bottom). If the Console view is not visible, go to the menu option Window -> Show View and select Console.

Then in the console window, click on the following button (on the right)

Consoles button

and then select Java Stack Trace Console from the drop-down list.

Paste your stack trace into the console. It will then provide a list of links into your source code and any other source code available.

This is what you might see (image from the Eclipse documentation):

Diagram from Eclipse documentation

The most recent method call made will be the top of the stack, which is the top line (excluding the message text). Going down the stack goes back in time. The second line is the method that calls the first line, etc.

If you are using open-source software, you might need to download and attach to your project the sources if you want to examine. Download the source jars, in your project, open the Referenced Libraries folder to find your jar for your open-source module (the one with the class files) then right click, select Properties and attach the source jar.

Console.log not working at all

I feel a bit stupid on this but let this be a lesson to everyone...Make sure you target the right selector!

Basically the console wasn't logging anything because this particular code snippet was attempting to grab the scrolling area of my window, when in fact my code was setup differently to scroll an entire DIV instead. As soon as I changed:

$(window).scroll(function() {

to this:

$('#scroller').scroll(function() {

The console started logging the correct messages.

Visual Studio loading symbols

Configure in Tools, Options, Debugging, Symbols.

You can watch the output window (view, output) to see what it's doing usually. If it's really slow that probably means it's hitting a symbol server, probably Microsoft's, to download missing symbols. This takes three HTTP hits for each file it can't find on every startup - you can sometimes see this in the status bar at the bottom or in e.g. Fiddler. You can see which modules have loaded symbols in Debug, Windows, Modules whilst you're debugging.

Symbols mean you get useful stack trace information into third party and system assemblies. You definitely need them for your own code, but I think those get loaded regardless. Your best bet is to turn off any non-local symbol sources in that menu and, if you're loading lots of symbols for system assemblies that you don't need to debug into you can temporarily disable loading those to speed up debug start - but they're often useful to have loaded.

How to use conditional breakpoint in Eclipse?

From Eclipsepedia on how to set a conditional breakpoint:

First, set a breakpoint at a given location. Then, use the context menu on the breakpoint in the left editor margin or in the Breakpoints view in the Debug perspective, and select the breakpoint’s properties. In the dialog box, check Enable Condition, and enter an arbitrary Java condition, such as list.size()==0. Now, each time the breakpoint is reached, the expression is evaluated in the context of the breakpoint execution, and the breakpoint is either ignored or honored, depending on the outcome of the expression.

Conditions can also be expressed in terms of other breakpoint attributes, such as hit count.

How to enable loglevel debug on Apache2 server

You need to use LogLevel rewrite:trace3 to your httpd.conf in newer version http://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#logging

How to determine whether code is running in DEBUG / RELEASE build?

zitao xiong's answer is pretty close to what I use; I also include the file name (by stripping off the path of FILE).

#ifdef DEBUG
    #define NSLogDebug(format, ...) \
    NSLog(@"<%s:%d> %s, " format, \
    strrchr("/" __FILE__, '/') + 1, __LINE__, __PRETTY_FUNCTION__, ## __VA_ARGS__)
#else
    #define NSLogDebug(format, ...)
#endif

How do I debug a stand-alone VBScript script?

Run cscript.exe for full command args, I think

cscript //X scriptfile.vbs MyArg1 MyArg2

will run the script in a debugger.

How to debug in Django, the good way?

I use pyDev with Eclipse really good, set break points, step into code, view values on any objects and variables, try it.

__FILE__, __LINE__, and __FUNCTION__ usage in C++

FYI: g++ offers the non-standard __PRETTY_FUNCTION__ macro. Until just now I did not know about C99 __func__ (thanks Evan!). I think I still prefer __PRETTY_FUNCTION__ when it's available for the extra class scoping.

PS:

static string  getScopedClassMethod( string thePrettyFunction )
{
  size_t index = thePrettyFunction . find( "(" );
  if ( index == string::npos )
    return thePrettyFunction;  /* Degenerate case */

  thePrettyFunction . erase( index );

  index = thePrettyFunction . rfind( " " );
  if ( index == string::npos )
    return thePrettyFunction;  /* Degenerate case */

  thePrettyFunction . erase( 0, index + 1 );

  return thePrettyFunction;   /* The scoped class name. */
}

Visual Studio debugger error: Unable to start program Specified file cannot be found

Guessing from the information I have, you're not actually compiling the program, but trying to run it. That is, ALL_BUILD is set as your startup project. (It should be in a bold font, unlike the other projects in your solution) If you then try to run/debug, you will get the error you describe, because there is simply nothing to run.

The project is most likely generated via CMAKE and included in your Visual Studio solution. Set any of the projects that do generate a .exe as the startup project (by right-clicking on the project and selecting "set as startup project") and you will most likely will be able to start those from within Visual Studio.

Not Able To Debug App In Android Studio

    <application android:debuggable="true">
</application>

This no longer works! No need to use debuggable="true" in manifest.

Instead, you should set the Build Variants to "debug"

Debug Mode

In Android Studio, go to BUILD -> Select Build Variant

Now try debugging. Thanks

Chrome: Uncaught SyntaxError: Unexpected end of input

I faced similar problem using ui bootstrap directive for angularjs - uib-datepicker, when pressing am/pm toggle.

Error in event handler for (unknown): SyntaxError: Unexpected end of JSON input angular timepicker

Turned out it was because of plugin 'Trans-over' (which translates a word when it is clicked). Maybe my answer will help someone, because I didn't found anything on the internet.

Run/install/debug Android applications over Wi-Fi?

The best way is using ADBConnect (Eclipse plugin) and ADB Wireless (app for Android device).

"Debug only" code that should run only when "turned on"

I think it may be worth mentioning that [ConditionalAttribute] is in the System.Diagnostics; namespace. I stumbled a bit when I got:

Error 2 The type or namespace name 'ConditionalAttribute' could not be found (are you missing a using directive or an assembly reference?)

after using it for the first time (I thought it would have been in System).

How do I print debug messages in the Google Chrome JavaScript Console?

Improving on Andru's idea, you can write a script which creates console functions if they don't exist:

if (!window.console) console = {};
console.log = console.log || function(){};
console.warn = console.warn || function(){};
console.error = console.error || function(){};
console.info = console.info || function(){};

Then, use any of the following:

console.log(...);
console.error(...);
console.info(...);
console.warn(...);

These functions will log different types of items (which can be filtered based on log, info, error or warn) and will not cause errors when console is not available. These functions will work in Firebug and Chrome consoles.

Javascript Debugging line by line using Google Chrome

...How can I step through my javascript code line by line using Google Chromes developer tools without it going into javascript libraries?...


For the record: At this time (Feb/2015) both Google Chrome and Firefox have exactly what you (and I) need to avoid going inside libraries and scripts, and go beyond the code that we are interested, It's called Black Boxing:

enter image description here

When you blackbox a source file, the debugger will not jump into that file when stepping through code you're debugging.

More info:

How do I get the backtrace for all the threads in GDB?

Generally, the backtrace is used to get the stack of the current thread, but if there is a necessity to get the stack trace of all the threads, use the following command.

thread apply all bt

Increment variable value by 1 ( shell programming)

There are more than one way to increment a variable in bash, but what you tried is not correct.

You can use for example arithmetic expansion:

i=$((i+1))

or only:

((i=i+1))

or:

((i+=1))

or even:

((i++))

Or you can use let:

let "i=i+1"

or only:

let "i+=1"

or even:

let "i++"

See also: http://tldp.org/LDP/abs/html/dblparens.html.

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

ddd is a graphical front-end to gdb that is pretty nice. One of the down sides is a classic X interface, but I seem to recall it being pretty intuitive.

Visual studio equivalent of java System.out

Try: Console.WriteLine (type out for a Visual Studio snippet)

Console.WriteLine(stuff);

Another way is to use System.Diagnostics.Debug.WriteLine:

System.Diagnostics.Debug.WriteLine(stuff);

Debug.WriteLine may suit better for Output window in IDE because it will be rendered for both Console and Windows applications. Whereas Console.WriteLine won't be rendered in Output window but only in the Console itself in case of Console Application type.

Another difference is that Debug.WriteLine will not print anything in Release configuration.

What does status=canceled for a resource mean in Chrome Developer Tools?

One the reasons could be that the XMLHttpRequest.abort() was called somewhere in the code, in this case, the request will have the cancelled status in the Chrome Developer tools Network tab.

How can I write output from a unit test?

I've accidentally found that DebugView (with enabled Capture > Capture Win32 option) will capture writes to System.Console.

Example test:

[Test]
public void FooTest()
{
    for (int i = 0; i < 5; i++)
        Console.WriteLine($"[{DateTime.UtcNow.ToString("G")}] Hello World");
}

enter image description here

PHP - print all properties of an object

<?php var_dump(obj) ?>

or

<?php print_r(obj) ?>

These are the same things you use for arrays too.

These will show protected and private properties of objects with PHP 5. Static class members will not be shown according to the manual.

If you want to know the member methods you can use get_class_methods():

$class_methods = get_class_methods('myclass');
// or
$class_methods = get_class_methods(new myclass());
foreach ($class_methods as $method_name) 
{
    echo "$method_name<br/>";
}

Related stuff:

get_object_vars()

get_class_vars()

get_class() <-- for the name of the instance

How do you debug MySQL stored procedures?

I just simply place select statements in key areas of the stored procedure to check on current status of data sets, and then comment them out (--select...) or remove them before production.

Debug JavaScript in Eclipse

In 2015, there are at least six choices for JavaScript debugging in Eclipse:

Adding to the above, here are a couple of videos which focus on "debugging JavaScript using eclipse"

Outdated

Attach IntelliJ IDEA debugger to a running Java process

in AndroidStudio or idea

  1. Config the application will be debug, open Edit Configurations

add "VM Options" Config “-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005” remember "address"

enter image description here

  1. Config Remote Debugger if not exits, Click + to add

specify "Port" same as in Step 1 "address" enter image description here

how can I debug a jar at runtime?

http://www.eclipsezone.com/eclipse/forums/t53459.html

Basically run it with:

-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=1044

The application, at launch, will wait until you connect from another source.

How to use breakpoints in Eclipse

Put breakpoints - double click on the margin. Run > Debug > Yes (if dialog appears), then use commands from Run menu or shortcuts - F5, F6, F7, F8.

Editing in the Chrome debugger

I was looking for a way to change the script and debug that new script. Way I managed to do that is:

  1. Set the breakpoint in the first line of the script you want to change and debug.

  2. Reload the page so the breakpoint is being hit

  3. Paste your new script and set desired breakpoints in it

  4. Ctrl+s, and the page will refresh causing that breakpoint in first line to be hit.

  5. F8 to continue, and now your newly pasted script replaces original one as long as no redirections and reloads are made.

What is the purpose of the vshost.exe file?

  • .exe - the 'normal' executable

  • .vshost.exe - a special version of the executable to aid debuging; see MSDN for details

  • .pdb - the Program Data Base with debug symbols

  • .vshost.exe.manifest - a kind of configuration file containing mostly dependencies on libraries

How do I pass a command line argument while starting up GDB in Linux?

I'm using GDB7.1.1, as --help shows:

gdb [options] --args executable-file [inferior-arguments ...]

IMHO, the order is a bit unintuitive at first.

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

HTTPScoop is awesome for inspecting the web traffic on your Mac. It's been incredibly helpful for me. I didn't think twice about the $15 price tag. There is a 14 day trial.

What are Java command line options to set to allow JVM to be remotely debugged?

Before Java 5.0, use -Xdebug and -Xrunjdwp arguments. These options will still work in later versions, but it will run in interpreted mode instead of JIT, which will be slower.

From Java 5.0, it is better to use the -agentlib:jdwp single option:

-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=1044

Options on -Xrunjdwp or agentlib:jdwp arguments are :

  • transport=dt_socket : means the way used to connect to JVM (socket is a good choice, it can be used to debug a distant computer)
  • address=8000 : TCP/IP port exposed, to connect from the debugger,
  • suspend=y : if 'y', tell the JVM to wait until debugger is attached to begin execution, otherwise (if 'n'), starts execution right away.

gdb: how to print the current line or find the current line number?

Command where or frame can be used. where command will give more info with the function name

Is it possible to change javascript variable values while debugging in Google Chrome?

I was having the same issue, went to the 'About Google Chrome'->Help and it said I needed to restart my browser to get the latest updates.

I did this, and suddenly, I can now change local variables. Simply click the variable you want to edit in the Scope Variables window, and type in your new value.

I did notice some oddities though, that I had to step over some unrelated var assignments before I could alter the text in the right hand window (Scope Variables).

Debugging iframes with Chrome developer tools

In the Developer Tools in Chrome, there is a bar along the top, called the Execution Context Selector (h/t felipe-sabino), just under the Elements, Network, Sources... tabs, that changes depending on the context of the current tab. When in the Console tab there is a dropdown in that bar that allows you to select the frame context in which the Console will operate. Select your frame in this drop down and you will find yourself in the appropriate frame context. :D

Chrome v59 Chrome version 59

Chrome v33 Chrome version 33

Chrome v32 & lower Chrome pre-version 32

Where does VBA Debug.Print log to?

Where do you want to see the output?

Messages being output via Debug.Print will be displayed in the immediate window which you can open by pressing Ctrl+G.

You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar

enter image description here

How do I set specific environment variables when debugging in Visual Studio?

If you can't use bat files to set up your environment, then your only likely option is to set up a system wide environment variable. You can find these by doing

  1. Right click "My Computer"
  2. Select properties
  3. Select the "advanced" tab
  4. Click the "environment variables" button
  5. In the "System variables" section, add the new environment variable that you desire
  6. "Ok" all the way out to accept your changes

I don't know if you'd have to restart visual studio, but seems unlikely. HTH

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

I tried renaming the .pdb file in obj\debug folder and did a clean solution and rebuild.
It created a new .pdb file and I was able to hit breakpoints correctly.

How do I print the elements of a C++ vector in GDB?

'Watching' STL containers while debugging is somewhat of a problem. Here are 3 different solutions I have used in the past, none of them is perfect.

1) Use GDB scripts from http://clith.com/gdb_stl_utils/ These scripts allow you to print the contents of almost all STL containers. The problem is that this does not work for nested containers like a stack of sets.

2) Visual Studio 2005 has fantastic support for watching STL containers. This works for nested containers but this is for their implementation for STL only and does not work if you are putting a STL container in a Boost container.

3) Write your own 'print' function (or method) for the specific item you want to print while debugging and use 'call' while in GDB to print the item. Note that if your print function is not being called anywhere in the code g++ will do dead code elimination and the 'print' function will not be found by GDB (you will get a message saying that the function is inlined). So compile with -fkeep-inline-functions

How to have PHP display errors? (I've added ini_set and error_reporting, but just gives 500 on errors)

Adding to what deceze said above. This is a parse error, so in order to debug a parse error, create a new file in the root named debugSyntax.php. Put this in it:

<?php

///////    SYNTAX ERROR CHECK    ////////////
error_reporting(E_ALL);
ini_set('display_errors','On');

//replace "pageToTest.php" with the file path that you want to test. 
include('pageToTest.php'); 

?>

Run the debugSyntax.php page and it will display parse errors from the page that you chose to test.

Print debugging info from stored procedure in MySQL

One workaround is just to use select without any other clauses.

http://lists.mysql.com/mysql/197901

Maven build debug in Eclipse

probleme : unit test result are not the same runing with eclipse and maven due ti order of library used by eclipse and maven. In my case the test was success with maven but i want to debug my unit test using eclipse, so the most easy way to debug unit test class with eclipse and runing maven is :

1) mvn -Dtest=MySuperClassTest -Dmaven.surefire.debug test ==> it will listen to the 5005 port (default port)

2) Go to eclipse, open a debug configuration, add a new java remote application and change the port to 5005 and debug

3) of course you must add break point somewhere in the class that you want to debug

How to debug a Flask app

You can use app.run(debug=True) for the Werkzeug Debugger edit as mentioned below, and I should have known.

How can I debug a .BAT script?

you can use cmd \k at the end of your script to see the error. it won't close your command prompt after the execution is done

How to debug Spring Boot application with Eclipse?

Please see http://java.dzone.com/articles/how-debug-remote-java-applicat to enable the remote debugging. If you are using tomcat to run your application, start tomcat with remote debug parameters or you can start tomcat with JPDA support by using following command.

Windows

<tomcat bin dir>/startup.bat jpda

*nix

<tomcat bin dir>/startup.sh jpda

this will enable remote debugging on port 8000

Android Debug Bridge (adb) device - no permissions

The cause of that problem has to do with system permissions (thanks @ IsaacCisneros for this suggestion). Somehow HTC Wildfire (and maybe the others) need something more from the system than Samsung devices. Simple solution is to run Eclipse as a root, but this is not very comfortable with non-sudo Linux systems like Fedora.

I've found another way of achieving the same goal, which seems to be more user friendly and is lesser security hole then running entire IDE with super user privileges. Mind this is still only a workaround of the problem. System root usage should be minimalized only to administrative tasks, and “adb” was designed to work with normal user account without SUID. Despite of the fact that the proper setting of SUID is quite secure, every single permission increase is a potential system security hole.

1.Setting ownership of the adb binary (owner – root, owner group - user_group):

chown root:user_group adb

2.Setting permissions with SUID:

chmod 4550 adb

This should result something similar to this (ls -llh):

-r-sr-x---. 1 root user_name 1.2M Jan 8 11:42 adb

After that you will be able to run adb as a root, event though you'll be using your normal user account. You can run Eclipse as a normal user and your HTC should be discovered properly.

./adb devices 
List of devices attached 
HT0BPPY15230    device 

Is it possible to disable the network in iOS Simulator?

Just turn off your WiFi in Mac OSX this works a treat!

Print current call stack from a method in Python code

import traceback
traceback.print_stack()

JavaScript: Is there a way to get Chrome to break on all errors?

Unfortunately, it the Developer Tools in Chrome seem to be unable to "stop on all errors", as Firebug does.

Can I use GDB to debug a running process?

Easiest way is to provide the process id.

gdb -p `pidof your_running_program_name`

Please get the full list of option in man gdb command.

In case there are multiple process for the same program running, then the following command will list the processes.

ps -C program -o pid h
<number>

Then the output process id (number) can be used as argument to gdb.

gdb -p <process id>

How to debug an apache virtual host configuration?

I had a new VirtualHost configuration file that was not showing when using the apachectl -S command. After much head scratching I realised that my file did not have suffix ".conf". Once I renamed the file with that suffix my Vhost started showing and working!

What is private bytes, virtual bytes, working set?

There is an interesting discussion here: http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/307d658a-f677-40f2-bdef-e6352b0bfe9e/ My understanding of this thread is that freeing small allocations are not reflected in Private Bytes or Working Set.

Long story short:

if I call

p=malloc(1000);
free(p);

then the Private Bytes reflect only the allocation, not the deallocation.

if I call

p=malloc(>512k);
free(p);

then the Private Bytes correctly reflect the allocation and the deallocation.

What is w3wp.exe?

  • A worker process runs as an executables file named W3wp.exe
  • A Worker Process is user mode code whose role is to process requests, such as processing requests to return a static page.

  • The worker process is controlled by the www service.

  • worker processes also run application code, Such as ASP .NET applications and XML web Services.

  • When Application pool receive the request, it simply pass the request to worker process (w3wp.exe) . The worker process“w3wp.exe” looks up the URL of the request in order to load the correct ISAPI extension. ISAPI extensions are the IIS way to handle requests for different resources. Once ASP.NET is installed, it installs its own ISAPI extension (aspnet_isapi.dll)and adds the mapping into IIS.

  • When Worker process loads the aspnet_isapi.dll, it start an HTTPRuntime, which is the entry point of an application. HTTPRuntime is a class which calls the ProcessRequest method to start Processing.

For more detail refer URL http://aspnetnova.blogspot.in/2011/12/how-iis-process-for-aspnet-requests.htmlenter image description here

Test iOS app on device without apple developer program or jailbreak

I never tried, but doing a google search, Jailcoder looks like a solution. The problem is the device need to be jailbroken. If anyone try this, please comment and let us know how it worked.

Spring RestTemplate - how to enable full debugging/logging of requests/responses?

As @MilacH pointed out, there is an error in the implementation. If an statusCode > 400 is returned a IOException is thrown, as the errorHandler is not invoked, from interceptors. The exception can be ignored and is then caught again in the handler method.

package net.sprd.fulfillment.common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import static java.nio.charset.StandardCharsets.UTF_8;

public class LoggingRequestInterceptor implements ClientHttpRequestInterceptor {

    final static Logger log = LoggerFactory.getLogger(LoggingRequestInterceptor.class);

    @SuppressWarnings("HardcodedLineSeparator")
    public static final char LINE_BREAK = '\n';

    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        try {
            traceRequest(request, body);
        } catch (Exception e) {
            log.warn("Exception in LoggingRequestInterceptor while tracing request", e);
        }

        ClientHttpResponse response = execution.execute(request, body);

        try {
            traceResponse(response);
        } catch (IOException e) {
            // ignore the exception here, as it will be handled by the error handler of the restTemplate
            log.warn("Exception in LoggingRequestInterceptor", e);
        }
        return response;
    }

    private void traceRequest(HttpRequest request, byte[] body) {
        log.info("===========================request begin================================================");
        log.info("URI         : {}", request.getURI());
        log.info("Method      : {}", request.getMethod());
        log.info("Headers     : {}", request.getHeaders());
        log.info("Request body: {}", new String(body, UTF_8));
        log.info("==========================request end================================================");
    }

    private void traceResponse(ClientHttpResponse response) throws IOException {
        StringBuilder inputStringBuilder = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getBody(), UTF_8))) {
            String line = bufferedReader.readLine();
            while (line != null) {
                inputStringBuilder.append(line);
                inputStringBuilder.append(LINE_BREAK);
                line = bufferedReader.readLine();
            }
        }

        log.info("============================response begin==========================================");
        log.info("Status code  : {}", response.getStatusCode());
        log.info("Status text  : {}", response.getStatusText());
        log.info("Headers      : {}", response.getHeaders());
        log.info("Response body: {}", inputStringBuilder);
        log.info("=======================response end=================================================");
    }

}

Easier way to debug a Windows service

To debug Windows Services I combine GFlags and a .reg file created by regedit.

  1. Run GFlags, specifying the exe-name and vsjitdebugger
  2. Run regedit and go to the location where GFlags sets his options
  3. Choose "Export Key" from the file-menu
  4. Save that file somewhere with the .reg extension
  5. Anytime you want to debug the service: doubleclick on the .reg file
  6. If you want to stop debugging, doubleclick on the second .reg file

Or save the following snippets and replace servicename.exe with the desired executable name.


debugon.reg:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\servicename.exe]
"GlobalFlag"="0x00000000"
"Debugger"="vsjitdebugger.exe"

debugoff.reg:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\servicename.exe]
"GlobalFlag"="0x00000000"

Will #if RELEASE work like #if DEBUG does in C#?

Nope.

While in debug configuration there is a DEBUG defined constant (automatically defined by Visual Studio) while there is no such constant defined for release mode. Check your project settings under build.

Selecting [Define DEBUG constant] under Project -> Build is like including #define DEBUG at the beginning of every file.

If you want to define a RELEASE constant for the release configuration go to:

  • Project Properties -> Build
  • Select Release Mode
  • in the Conditional compilation symbols textbox enter: RELEASE

program cant start because php5.dll is missing

When you open phpinfo() see if the thread safety is enable or not enable also see the version of php and see MSVC-- what is the number in place of -- and see the architecture these all things help u to get the suitable php driver

here a url help u to get a php driver https://s3.amazonaws.com/drivers.mongodb.org/php/index.html

_DEBUG vs NDEBUG

Visual Studio defines _DEBUG when you specify the /MTd or /MDd option, NDEBUG disables standard-C assertions. Use them when appropriate, ie _DEBUG if you want your debugging code to be consistent with the MS CRT debugging techniques and NDEBUG if you want to be consistent with assert().

If you define your own debugging macros (and you don't hack the compiler or C runtime), avoid starting names with an underscore, as these are reserved.

Debugging with command-line parameters in Visual Studio

Yes, it's in the Debugging section of the properties page of the project.

In Visual Studio since 2008: right-click the project, choose Properties, go to the Debugging section -- there is a box for "Command Arguments". (Tip: not solution, but project).

filename and line number of Python script

Here's what works for me to get the line number in Python 3.7.3 in VSCode 1.39.2 (dmsg is my mnemonic for debug message):

import inspect

def dmsg(text_s):
    print (str(inspect.currentframe().f_back.f_lineno) + '| ' + text_s)

To call showing a variable name_s and its value:

name_s = put_code_here
dmsg('name_s: ' + name_s)

Output looks like this:

37| name_s: value_of_variable_at_line_37

How do I remedy "The breakpoint will not currently be hit. No symbols have been loaded for this document." warning?

My coworker had this problem, followed similar steps as those here, but the solution was different than any of these given.

The code she wanted to debug was in a project referenced by the current project, and it was never running within the Visual Studio session. The DLL was running from the GAC folder, after she deleted that the project wouldn't run at all, throwing an exception as soon as it tried to run. The solution was to include the referenced project in the local folder.

From the SolutionExplorer:

  1. Select the "debugging" project you will run out of
  2. Expand References (if not visible, select menu Project, item Show all files)
  3. Right-click the project which has the break point that is not working, select Properties
  4. Change value of Copy Local from False to True

Try again. (It worked for her!)

How to debug a GLSL shader?

I have found Transform Feedback to be a useful tool for debugging vertex shaders. You can use this to capture the values of VS outputs, and read them back on the CPU side, without having to go through the rasterizer.

Here is another link to a tutorial on Transform Feedback.

How can I inspect element in chrome when right click is disabled?

CTRL+SHIFT+I brings up the developers tools.

How to debug Google Apps Script (aka where does Logger.log log to?)

If you have the script editor open you will see the logs under View->Logs. If your script has an onedit trigger, make a change to the spreadsheet which should trigger the function with the script editor opened in a second tab. Then go to the script editor tab and open the log. You will see whatever your function passes to the logger.

Basically as long as the script editor is open, the event will write to the log and show it for you. It will not show if someone else is in the file elsewhere.

How to quickly and conveniently disable all console.log statements in my code?

My comprehensive solution to disable/override all console.* functions is here.

Of course, please make sure you are including it after checking necessary context. For example, only including in production release, it's not bombing any other crucial components etc.

Quoting it here:

_x000D_
_x000D_
"use strict";_x000D_
(() => {_x000D_
  var console = (window.console = window.console || {});_x000D_
  [_x000D_
    "assert", "clear", "count", "debug", "dir", "dirxml",_x000D_
    "error", "exception", "group", "groupCollapsed", "groupEnd",_x000D_
    "info", "log", "markTimeline", "profile", "profileEnd", "table",_x000D_
    "time", "timeEnd", "timeStamp", "trace", "warn"_x000D_
  ].forEach(method => {_x000D_
    console[method] = () => {};_x000D_
  });_x000D_
  console.log("This message shouldn't be visible in console log");_x000D_
})();
_x000D_
_x000D_
_x000D_

Python memory leaks

I tried out most options mentioned previously but found this small and intuitive package to be the best: pympler

It's quite straight forward to trace objects that were not garbage-collected, check this small example:

install package via pip install pympler

from pympler.tracker import SummaryTracker
tracker = SummaryTracker()

# ... some code you want to investigate ...

tracker.print_diff()

The output shows you all the objects that have been added, plus the memory they consumed.

Sample output:

                                 types |   # objects |   total size
====================================== | =========== | ============
                                  list |        1095 |    160.78 KB
                                   str |        1093 |     66.33 KB
                                   int |         120 |      2.81 KB
                                  dict |           3 |       840 B
      frame (codename: create_summary) |           1 |       560 B
          frame (codename: print_diff) |           1 |       480 B

This package provides a number of more features. Check pympler's documentation, in particular the section Identifying memory leaks.

View array in Visual Studio debugger?

Hover your mouse cursor over the name of the array, then hover over the little (+) icon that appears.

Determine the line of code that causes a segmentation fault?

All of the above answers are correct and recommended; this answer is intended only as a last-resort if none of the aforementioned approaches can be used.

If all else fails, you can always recompile your program with various temporary debug-print statements (e.g. fprintf(stderr, "CHECKPOINT REACHED @ %s:%i\n", __FILE__, __LINE__);) sprinkled throughout what you believe to be the relevant parts of your code. Then run the program, and observe what the was last debug-print printed just before the crash occurred -- you know your program got that far, so the crash must have happened after that point. Add or remove debug-prints, recompile, and run the test again, until you have narrowed it down to a single line of code. At that point you can fix the bug and remove all of the temporary debug-prints.

It's quite tedious, but it has the advantage of working just about anywhere -- the only times it might not is if you don't have access to stdout or stderr for some reason, or if the bug you are trying to fix is a race-condition whose behavior changes when the timing of the program changes (since the debug-prints will slow down the program and change its timing)

Debugging Stored Procedure in SQL Server 2008

Well the answer was sitting right in front of me the whole time.

In SQL Server Management Studio 2008 there is a Debug button in the toolbar. Set a break point in a query window to step through.

I dismissed this functionality at the beginning because I didn't think of stepping INTO the stored procedure, which you can do with ease.

SSMS basically does what FinnNK mentioned with the MSDN walkthrough but automatically.

So easy! Thanks for your help FinnNK.

Edit: I should add a step in there to find the stored procedure call with parameters I used SQL Profiler on my database.

Paused in debugger in chrome?

If you navigate to Sources you can see the pauseenter image description here button at the bottom of the DevTools. Basically there are 3 possible pause option in DevTools while debugging js file,

  • Don't pause on exceptions(enter image description here) :

    The pause button will be in grey colour as if "Don't pause on exceptions" is active. enter image description here

  • Pause on all exceptions(enter image description here) :

    The pause button will be in blue colour as if "Pause on all exceptions" is active. enter image description here

  • Pause on uncaught exceptions(enter image description here) :

    The pause button will be in purple colour as if "Pause on uncaught exceptions" is active. enter image description here

In your case, if you don't want to pause, select Don't pause on exceptions. To select, toggle the pause button till it become greyenter image description here.

How do you debug PHP scripts?

In all honesty, a combination of print and print_r() to print out the variables. I know that many prefer to use other more advanced methods but I find this the easiest to use.

I will say that I didn't fully appreciate this until I did some Microprocessor programming at Uni and was not able to use even this.

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

Since GDB 7.5 you can use these native Convenience Functions:

$_memeq(buf1, buf2, length)
$_regex(str, regex)
$_streq(str1, str2)
$_strlen(str)

Seems quite less problematic than having to execute a "foreign" strcmp() on the process' stack each time the breakpoint is hit. This is especially true for debugging multithreaded processes.

Note your GDB needs to be compiled with Python support, which is not an issue with current linux distros. To be sure, you can check it by running show configuration inside GDB and searching for --with-python. This little oneliner does the trick, too:

$ gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python'
             --with-python=/usr (relocatable)

For your demo case, the usage would be

break <where> if $_streq(x, "hello")

or, if your breakpoint already exists and you just want to add the condition to it

condition <breakpoint number> $_streq(x, "hello")

$_streq only matches the whole string, so if you want something more cunning you should use $_regex, which supports the Python regular expression syntax.

How to change the default browser to debug with in Visual Studio 2008?

I find that the Browse With.. menu item only appears in Visual Studio 2010 when I Run as administrator. And in that case it is available even while in debug mode.

How to print a debug log?

This a great tool for debugging & logging php: PHp Debugger & Logger

It works right out of the box with just 3 lines of code. It can send messages to the js console for ajax debugging and can replace the error handler. It also dumps information about variables like var_dump() and print_r(), but in a more readable format. Very nice tool!

How can I debug javascript on Android?

Chrome has a wonderful feature that simply takes the actual Android Chrome contents (incl. inspection etc.) onto the PC screen...

  • Enable USB debugging on the device, maybe you also need to connect once via adb devices to trigger the "allow communication with..." dialogue on the mobile device,
  • connect the Android device to the PC,
  • start Chrome on both, and
  • then navigate to chrome://inspect/#devices on the PC.
  • Here, the tabs from the mobile phone Chrome are listed and can be inspected.

There's also a detailled manual on the net: https://www.till.net/technologie/html-javascript/remote-web-debugging-unter-android-und-chrome

(found that after adb logcat showed nothing from the browser)

Firebug-like debugger for Google Chrome

You can set this bookmarklet in your "Bookmarks Bar" in order to have Firebug lite always available in Chrome/Chromium browser (put this as the URL):

javascript:var firebug=document.createElement('script');firebug.setAttribute('src','http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js');document.body.appendChild(firebug);(function(){if(window.firebug.version){firebug.init();}else{setTimeout(arguments.callee);}})();void(firebug);

Where does System.Diagnostics.Debug.Write output appear?

While you are debugging in Visual Studio, display the "Output" window (View->Output). It will show there.

Unfortunately MyApp has stopped. How can I solve this?

You have to check the Stack trace

How to do that?

on Your IDE Check the windows form LOGCAT

If you cant see the logcat windows go to this path and open it

window->show view->others->Android->Logcat

if you are using Google-Api go to this path

adb logcat > logcat.txt

Is there a way I can retrieve sa password in sql server 2005

There is no way to get the old password back. Log into the SQL server management console as a machine or domain admin using integrated authentication, you can then change any password (including sa).

Start the SQL service again and use the new created login (recovery in my example) Go via the security panel to the properties and change the password of the SA account.

enter image description here

Now write down the new SA password.

Using CookieContainer with WebClient class

I think there's cleaner way where you don't have to create a new webclient (and it'll work with 3rd party libraries as well)

internal static class MyWebRequestCreator
{
    private static IWebRequestCreate myCreator;

    public static IWebRequestCreate MyHttp
    {
        get
        {
            if (myCreator == null)
            {
                myCreator = new MyHttpRequestCreator();
            }
            return myCreator;
        }
    }

    private class MyHttpRequestCreator : IWebRequestCreate
    {
        public WebRequest Create(Uri uri)
        {
            var req = System.Net.WebRequest.CreateHttp(uri);
            req.CookieContainer = new CookieContainer();
            return req;
        }
    }
}

Now all you have to do is opt in for which domains you want to use this:

    WebRequest.RegisterPrefix("http://example.com/", MyWebRequestCreator.MyHttp);

That means ANY webrequest that goes to example.com will now use your custom webrequest creator, including the standard webclient. This approach means you don't have to touch all you code. You just call the register prefix once and be done with it. You can also register for "http" prefix to opt in for everything everywhere.

How can I format a number into a string with leading zeros?

use:

i.ToString("D10")

See Int32.ToString (MSDN), and Standard Numeric Format Strings (MSDN).

Or use String.PadLeft. For example,

int i = 321;
Key = i.ToString().PadLeft(10, '0');

Would result in 0000000321. Though String.PadLeft would not work for negative numbers.

See String.PadLeft (MSDN).

DateTime and CultureInfo

Use CultureInfo class to change your culture info.

var dutchCultureInfo = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCultureInfo);

Regular expression for a string that does not start with a sequence

You could use a negative look-ahead assertion:

^(?!tbd_).+

Or a negative look-behind assertion:

(^.{1,3}$|^.{4}(?<!tbd_).*)

Or just plain old character sets and alternations:

^([^t]|t($|[^b]|b($|[^d]|d($|[^_])))).*

How to create EditText with cross(x) button at end of it?

You can use this snippet with Jaydip answer for more than one button. just call it after getting a reference to the ET and Button Elements. I used vecotr button so you have to change the Button element to ImageButton:

private void setRemovableET(final EditText et, final ImageButton resetIB) {

        et.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (hasFocus && et.getText().toString().length() > 0)
                    resetIB.setVisibility(View.VISIBLE);
                else
                    resetIB.setVisibility(View.INVISIBLE);
            }
        });

        resetIB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                et.setText("");
                resetIB.setVisibility(View.INVISIBLE);
            }
        });

        et.addTextChangedListener(new TextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {}
            @Override
            public void beforeTextChanged(CharSequence s, int start,
                                          int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start,
                                      int before, int count) {
                if(s.length() != 0){
                    resetIB.setVisibility(View.VISIBLE);
                }else{
                    resetIB.setVisibility(View.INVISIBLE);
                }
            }
        });
    }

What's the best practice to round a float to 2 decimals?

//by importing Decimal format we can do...

import java.util.Scanner;
import java.text.DecimalFormat;
public class Average
{
public static void main(String[] args)
{
int sub1,sub2,sub3,total;
Scanner in = new Scanner(System.in);
System.out.print("Enter Subject 1 Marks : ");
sub1 = in.nextInt();
System.out.print("Enter Subject 2 Marks : ");
sub2 = in.nextInt();
System.out.print("Enter Subject 3 Marks : ");
sub3 = in.nextInt();
total = sub1 + sub2 + sub3;
System.out.println("Total Marks of Subjects = " + total);
res = (float)total;
average = res/3;
System.out.println("Before Rounding Decimal.. Average = " +average +"%");
DecimalFormat df = new DecimalFormat("###.##");
System.out.println("After Rounding Decimal.. Average = " +df.format(average)+"%");
}
}
/* Output
Enter Subject 1 Marks : 72
Enter Subject 2 Marks : 42
Enter Subject 3 Marks : 52
Total Marks of Subjects = 166
Before Rounding Decimal.. Average = 55.333332%
After Rounding Decimal.. Average = 55.33%
*/

/* Output
Enter Subject 1 Marks : 98
Enter Subject 2 Marks : 88
Enter Subject 3 Marks : 78
Total Marks of Subjects = 264
Before Rounding Decimal.. Average = 88.0%
After Rounding Decimal.. Average = 88%
*/

/* You can Find Avrerage values in two ouputs before rounding average
And After rounding Average..*/

Using the rJava package on Win7 64 bit with R

For me, setting JAVA_HOME did the trick (instead of unsetting, as in another answer given here). Either in Windows:

set JAVA_HOME="C:\Program Files\Java\jre7\"

Or inside R:

Sys.setenv(JAVA_HOME="C:\\Program Files\\Java\\jre7\\")

But what's probably the best solution (since rJava 0.9-4) is overriding within R the Windows JAVA_HOME setting altogether:

options(java.home="C:\\Program Files\\Java\\jre7\\")
library(rJava)

Getting a count of objects in a queryset in django

Another way of doing this would be using Aggregation. You should be able to achieve a similar result using a single query. Such as this:

Item.objects.values("contest").annotate(Count("id"))

I did not test this specific query, but this should output a count of the items for each value in contests as a dictionary.

Apply CSS rules if browser is IE

In browsers up to and including IE9, this is done through conditional comments.

<!--[if IE]>
<style type="text/css">
  IE specific CSS rules go here
</style>
<![endif]-->

How do I get the XML SOAP request of an WCF Web service request?

I think you meant that you want to see the XML at the client, not trace it at the server. In that case, your answer is in the question I linked above, and also at How to Inspect or Modify Messages on the Client. But, since the .NET 4 version of that article is missing its C#, and the .NET 3.5 example has some confusion (if not a bug) in it, here it is expanded for your purpose.

You can intercept the message before it goes out using an IClientMessageInspector:

using System.ServiceModel.Dispatcher;
public class MyMessageInspector : IClientMessageInspector
{ }

The methods in that interface, BeforeSendRequest and AfterReceiveReply, give you access to the request and reply. To use the inspector, you need to add it to an IEndpointBehavior:

using System.ServiceModel.Description;
public class InspectorBehavior : IEndpointBehavior
{
    public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
        clientRuntime.MessageInspectors.Add(new MyMessageInspector());
    }
}

You can leave the other methods of that interface as empty implementations, unless you want to use their functionality, too. Read the how-to for more details.

After you instantiate the client, add the behavior to the endpoint. Using default names from the sample WCF project:

ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
client.Endpoint.Behaviors.Add(new InspectorBehavior());
client.GetData(123);

Set a breakpoint in MyMessageInspector.BeforeSendRequest(); request.ToString() is overloaded to show the XML.

If you are going to manipulate the messages at all, you have to work on a copy of the message. See Using the Message Class for details.

Thanks to Zach Bonham's answer at another question for finding these links.

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

this query will alter the multiple column test it.

create table test(a int,B int,C int);

alter table test drop(a,B);

Setting the Vim background colors

As vim's own help on set background says, "Setting this option does not change the background color, it tells Vim what the background color looks like. For changing the background color, see |:hi-normal|."

For example

:highlight Normal ctermfg=grey ctermbg=darkblue

will write in white on blue on your color terminal.

Getting Excel to refresh data on sheet from within VBA

After a data connection update, some UDF's were not executing. Using a subroutine, I was trying to recalcuate a single column with:

Sheets("mysheet").Columns("D").Calculate

But above statement had no effect. None of above solutions helped, except kambeeks suggestion to replace formulas worked and was fast if manual recalc turned on during update. Below code solved my problem, even if not exactly responsible to OP "kluge" comment, it provided a fast/reliable solution to force recalculation of user-specified cells.

Application.Calculation = xlManual
DoEvents
For Each mycell In Sheets("mysheet").Range("D9:D750").Cells
    mycell.Formula = mycell.Formula
Next
DoEvents
Application.Calculation = xlAutomatic

Vue.js : How to set a unique ID for each component instance?

Each component has a unique id which can be accessed as this._uid.

<template>
  <div>
    <label :for="id">Label text for {{id}}</label>
    <input :id="id" type="text" />
  </div>
</template>

<script>
export default {
  data () {
    return {
      id: null
    }
  }, 
  mounted () {
    this.id = this._uid
  }
}
</script>

If you want more control over the ids you can for example, generate them inside a parent component.

Python string to unicode

>>> a="Hello\u2026"
>>> print a.decode('unicode-escape')
Hello…

Is an anchor tag without the href attribute safe?

The <a> tag without the "href" can be handy when using multi-level menus and you need to expand the next level but don't want that menu label to be an active link. I have never had any issues using it that way.

Get the value of input text when enter key pressed

Something like this (not tested, but should work)

Pass this as parameter in Html:

<input type="text" placeholder="some text" class="search" onkeydown="search(this)"/>

And alert the value of the parameter passed into the search function:

function search(e){
  alert(e.value);
}

How to split one text file into multiple *.txt files?

Using bash:

readarray -t LINES < file.txt
COUNT=${#LINES[@]}
for I in "${!LINES[@]}"; do
    INDEX=$(( (I * 12 - 1) / COUNT + 1 ))
    echo "${LINES[I]}" >> "file${INDEX}.txt"
done

Using awk:

awk '{
    a[NR] = $0
}
END {
    for (i = 1; i in a; ++i) {
        x = (i * 12 - 1) / NR + 1
        sub(/\..*$/, "", x)
        print a[i] > "file" x ".txt"
    }
}' file.txt

Unlike split this one makes sure that number of lines are most even.

How to populate a dropdownlist with json data in jquery?

To populate ComboBox with JSON, you can consider using the: jqwidgets combobox, too.

do-while loop in R

See ?Control or the R Language Definition:

> y=0
> while(y <5){ print( y<-y+1) }
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5

So do_while does not exist as a separate construct in R, but you can fake it with:

repeat( { expressions}; if (! end_cond_expr ) {break} )

If you want to see the help page you cannot type ?while or ?repeat at the console but rather need to use ?'repeat' or ?'while'. All the "control-constructs" including if are on the same page and all need character quoting after the "?" so the interpreter doesn't see them as incomplete code and give you a continuation "+".

Find a string between 2 known values

    public string between2finer(string line, string delimiterFirst, string delimiterLast)
    {
        string[] splitterFirst = new string[] { delimiterFirst };
        string[] splitterLast = new string[] { delimiterLast };
        string[] splitRes;
        string buildBuffer;
        splitRes = line.Split(splitterFirst, 100000, System.StringSplitOptions.RemoveEmptyEntries);
        buildBuffer = splitRes[1];
        splitRes = buildBuffer.Split(splitterLast, 100000, System.StringSplitOptions.RemoveEmptyEntries);
        return splitRes[0];
    }


    private void button1_Click(object sender, EventArgs e)
    {
        string manyLines = "Received: from exim by isp2.ihc.ru with local (Exim 4.77) \nX-Failed-Recipients: [email protected]\nFrom: Mail Delivery System <[email protected]>";
        MessageBox.Show(between2finer(manyLines, "X-Failed-Recipients: ", "\n"));
    }

Pandas aggregate count distinct

How about either of:

>>> df
         date  duration user_id
0  2013-04-01        30    0001
1  2013-04-01        15    0001
2  2013-04-01        20    0002
3  2013-04-02        15    0002
4  2013-04-02        30    0002
>>> df.groupby("date").agg({"duration": np.sum, "user_id": pd.Series.nunique})
            duration  user_id
date                         
2013-04-01        65        2
2013-04-02        45        1
>>> df.groupby("date").agg({"duration": np.sum, "user_id": lambda x: x.nunique()})
            duration  user_id
date                         
2013-04-01        65        2
2013-04-02        45        1

Google Maps: How to create a custom InfoWindow?

Below piece of code may help you out.

var infowindow = new google.maps.InfoWindow();
 google.maps.event.addListener(marker, 'mouseover', (function(marker) {
            return function() {
                var content = address;
                infowindow.setContent(content);
                infowindow.open(map, marker);
            }
          })(marker));

Here is an article < How to locate multiple addresses on google maps with perfect zoom > that helped me achieved this. You can refer it for working JS Fiddle link and complete example.

Get element type with jQuery

you should use tagName property and attr('type') for inputs

Uncaught ReferenceError: function is not defined with onclick

Never use .onclick(), or similar attributes from a userscript! (It's also poor practice in a regular web page).

The reason is that userscripts operate in a sandbox ("isolated world"), and onclick operates in the target-page scope and cannot see any functions your script creates.

Always use addEventListener()Doc (or an equivalent library function, like jQuery .on()).

So instead of code like:

something.outerHTML += '<input onclick="resetEmotes()" id="btnsave" ...>'


You would use:

something.outerHTML += '<input id="btnsave" ...>'

document.getElementById ("btnsave").addEventListener ("click", resetEmotes, false);

For the loop, you can't pass data to an event listener like that See the doc. Plus every time you change innerHTML like that, you destroy the previous event listeners!

Without refactoring your code much, you can pass data with data attributes. So use code like this:

for (i = 0; i < EmoteURLLines.length; i++) {
    if (checkIMG (EmoteURLLines[i])) {
        localStorage.setItem ("nameEmotes", JSON.stringify (EmoteNameLines));
        localStorage.setItem ("urlEmotes", JSON.stringify (EmoteURLLines));
        localStorage.setItem ("usageEmotes", JSON.stringify (EmoteUsageLines));
        if (i == 0) {
            console.log (resetSlot ());
        }
        emoteTab[2].innerHTML  += '<span style="cursor:pointer;" id="' 
                                + EmoteNameLines[i] 
                                + '" data-usage="' + EmoteUsageLines[i] + '">'
                                + '<img src="' + EmoteURLLines[i] + '" /></span>'
                                ;
    } else {
        alert ("The maximum emote (" + EmoteNameLines[i] + ") size is (36x36)");
    }
}
//-- Only add events when innerHTML overwrites are done.
var targetSpans = emoteTab[2].querySelectorAll ("span[data-usage]");
for (var J in targetSpans) {
    targetSpans[J].addEventListener ("click", appendEmote, false);
}

Where appendEmote is like:

function appendEmote (zEvent) {
    //-- this and the parameter are special in event handlers.  see the linked doc.
    var emoteUsage  = this.getAttribute ("data-usage");
    shoutdata.value += emoteUsage;
}


WARNINGS:

  • Your code reuses the same id for several elements. Don't do this, it's invalid. A given ID should occur only once per page.
  • Every time you use .outerHTML or .innerHTML, you trash any event handlers on the affected nodes. If you use this method beware of that fact.

How do I pass a value from a child back to the parent form?

Create a property (or method) on FormOptions, say GetMyResult:

using (FormOptions formOptions = new FormOptions())
{
    formOptions.ShowDialog();

    string result = formOptions.GetMyResult;

    // do what ever with result...
}

Event handler not working on dynamic content

You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content).

See http://api.jquery.com/on/#direct-and-delegated-events

Change your code to

$(document.body).on('click', '.update' ,function(){

The jQuery set receives the event then delegates it to elements matching the selector given as argument. This means that contrary to when using live, the jQuery set elements must exist when you execute the code.

As this answers receives a lot of attention, here are two supplementary advises :

1) When it's possible, try to bind the event listener to the most precise element, to avoid useless event handling.

That is, if you're adding an element of class b to an existing element of id a, then don't use

$(document.body).on('click', '#a .b', function(){

but use

$('#a').on('click', '.b', function(){

2) Be careful, when you add an element with an id, to ensure you're not adding it twice. Not only is it "illegal" in HTML to have two elements with the same id but it breaks a lot of things. For example a selector "#c" would retrieve only one element with this id.

.jar error - could not find or load main class

Thanks jbaliuka for the suggestion. I opened the registry editor (by typing regedit in cmd) and going to HKEY_CLASSES_ROOT > jarfile > shell > open > command, then opening (Default) and changing the value from

"C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %*

to

"C:\Program Files\Java\jre7\bin\java.exe" -jar "%1" %*

(I just removed the w in javaw.exe.) After that you have to right click a jar -> open with -> choose default program -> navigate to your java folder and open \jre7\bin\java.exe (or any other java.exe file in you java folder). If it doesn't work, try switching to javaw.exe, open a jar file with it, then switch back.

I don't know anything about editing the registry except that it's dangerous, so you might wanna back it up before doing this (in the top bar, File>Export).

Git keeps asking me for my ssh key passphrase

If the above solutions are not working for me, one thing to check is that you actually have the public key too (typically id_rsa.pub). It is unusual not to, but that was the cause for me.

To create your public key from your private key:

ssh-keygen -y -f ~/.ssh/id_rsa > ~/.ssh/id_rsa.pub

How to use SearchView in Toolbar Android

Implementing the SearchView without the use of the menu.xml file and open through button

In your Activity we need to use the method of the onCreateOptionsMenumethod in which we will programmatically inflate the SearchView

private MenuItem searchMenu;
private String mSearchString="";

@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);

        SearchManager searchManager = (SearchManager) StoreActivity.this.getSystemService(Context.SEARCH_SERVICE);


        SearchView mSearchView = new SearchView(getSupportActionBar().getThemedContext());
        mSearchView.setQueryHint(getString(R.string.prompt_search)); /// YOUR HINT MESSAGE
        mSearchView.setMaxWidth(Integer.MAX_VALUE);

        searchMenu = menu.add("searchMenu").setVisible(false).setActionView(mSearchView);
        searchMenu.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);


        assert searchManager != null;
        mSearchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        mSearchView.setIconifiedByDefault(false);

        SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
            public boolean onQueryTextChange(String newText) {
                mSearchString = newText;

                return true;
            }

            public boolean onQueryTextSubmit(String query) {
                mSearchString = query;

                searchMenu.collapseActionView();


                return true;
            }
        };

        mSearchView.setOnQueryTextListener(queryTextListener);


        return true;
    }

And in your Activity class, you can open the SearchView on any button click on toolbar like below

YOUR_BUTTON.setOnClickListener(view -> {

            searchMenu.expandActionView();

        });

How to change spinner text size and text color?

I have done this as following.I have use getDropDownView() and getView() methods.

Use getDropDownView() for opened Spinner.

@Override
public View getDropDownView(int position, View convertView, ViewGroup parent) {
  View view = convertView;
  if (view == null) {
    LayoutInflater vi = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = vi.inflate(R.layout.context_row_icon, null);
  }
  TextView mTitle = (TextView) view.findViewById(R.id.context_label);
  ImageView flag = (ImageView) view.findViewById(R.id.context_icon);                

  mTitle.setText(values[position].getLabel(activity));

  if (!((LabelItem) getItem(position)).isEnabled()) {
    mTitle.setTextColor(activity.getResources().getColor(R.color.context_item_disabled));
  } else {
    mTitle.setTextColor(activity.getResources().getColor(R.color.context_item));
  }
  return view;
}

And Use getView() for closed Spinner.

@Override
public View getView(int position, View convertView, ViewGroup parent) {
  View view = convertView;
  if (view == null) {
    LayoutInflater vi = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = vi.inflate(R.layout.context_row_icon, null);
  }
  TextView mTitle = (TextView) view.findViewById(R.id.context_label);
  ImageView flag = (ImageView) view.findViewById(R.id.context_icon);

  mTitle.setText(values[position].getLabel(activity));
  mTitle.setTextColor(activity.getResources().getColor(R.color.context_item_disabled));

  return view;
}

How to pass an array into a SQL Server stored procedure

You need to pass it as an XML parameter.

Edit: quick code from my project to give you an idea:

CREATE PROCEDURE [dbo].[GetArrivalsReport]
    @DateTimeFrom AS DATETIME,
    @DateTimeTo AS DATETIME,
    @HostIds AS XML(xsdArrayOfULong)
AS
BEGIN
    DECLARE @hosts TABLE (HostId BIGINT)

    INSERT INTO @hosts
        SELECT arrayOfUlong.HostId.value('.','bigint') data
        FROM @HostIds.nodes('/arrayOfUlong/u') as arrayOfUlong(HostId)

Then you can use the temp table to join with your tables. We defined arrayOfUlong as a built in XML schema to maintain data integrity, but you don't have to do that. I'd recommend using it so here's a quick code for to make sure you always get an XML with longs.

IF NOT EXISTS (SELECT * FROM sys.xml_schema_collections WHERE name = 'xsdArrayOfULong')
BEGIN
    CREATE XML SCHEMA COLLECTION [dbo].[xsdArrayOfULong]
    AS N'<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
    <xs:element name="arrayOfUlong">
        <xs:complexType>
            <xs:sequence>
                <xs:element maxOccurs="unbounded"
                            name="u"
                            type="xs:unsignedLong" />
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>';
END
GO

How do I hide javascript code in a webpage?

'Is not possible!'

Oh yes it is ....

//------------------------------
function unloadJS(scriptName) {
  var head = document.getElementsByTagName('head').item(0);
  var js = document.getElementById(scriptName);
  js.parentNode.removeChild(js);
}


//----------------------
function unloadAllJS() {
  var jsArray = new Array();
  jsArray = document.getElementsByTagName('script');
  for (i = 0; i < jsArray.length; i++){
    if (jsArray[i].id){
      unloadJS(jsArray[i].id)
    }else{
      jsArray[i].parentNode.removeChild(jsArray[i]);
    }
  }      
}

Check if XML Element exists

How about trying this:

using (XmlTextReader reader = new XmlTextReader(xmlPath))
{
    while (reader.Read())
    {
        if (reader.NodeType == XmlNodeType.Element)
        { 
            //do your code here
        }
    }
}

Run a string as a command within a Bash script

I usually place commands in parentheses $(commandStr), if that doesn't help I find bash debug mode great, run the script as bash -x script

Concatenate a list of pandas dataframes together

You also can do it with functional programming:

from functools import reduce
reduce(lambda df1, df2: df1.merge(df2, "outer"), mydfs)

If '<selector>' is an Angular component, then verify that it is part of this module

  1. Declare your MyComponentComponent in MyComponentModule
  2. Add your MyComponentComponent to exports attribute of MyComponentModule

mycomponentModule.ts

@NgModule({
   imports: [],
   exports: [MyComponentComponent],
   declarations: [MyComponentComponent],
   providers: [],
})

export class MyComponentModule {
}
  1. Add your MyComponentModule to your AppModule imports attribute

app.module.ts

    @NgModule({
       imports: [MyComponentModule]
       declarations: [AppComponent],
       providers: [],
       bootstrap: [AppComponent]
    })
    export class AppModule {} 

Important If your still have that error, Stop your server ctrl+c from terminal, and run it again ng serve -o

How can I convert an MDB (Access) file to MySQL (or plain SQL file)?

OSX users can follow by Nicolay77 or mikkom that uses the mdbtools utility. You can install it via Homebrew. Just have your homebrew installed and then go

$ homebrew install mdbtools

Then create one of the scripts described by the guys and use it. I've used mikkom's one, converted all my mdb files into sql.

$ ./to_mysql.sh myfile.mdb > myfile.sql

(which btw contains more than 1 table)

Java Singleton and Synchronization

Enum singleton

The simplest way to implement a Singleton that is thread-safe is using an Enum

public enum SingletonEnum {
  INSTANCE;
  public void doSomething(){
    System.out.println("This is a singleton");
  }
}

This code works since the introduction of Enum in Java 1.5

Double checked locking

If you want to code a “classic” singleton that works in a multithreaded environment (starting from Java 1.5) you should use this one.

public class Singleton {

  private static volatile Singleton instance = null;

  private Singleton() {
  }

  public static Singleton getInstance() {
    if (instance == null) {
      synchronized (Singleton.class){
        if (instance == null) {
          instance = new Singleton();
        }
      }
    }
    return instance ;
  }
}

This is not thread-safe before 1.5 because the implementation of the volatile keyword was different.

Early loading Singleton (works even before Java 1.5)

This implementation instantiates the singleton when the class is loaded and provides thread safety.

public class Singleton {

  private static final Singleton instance = new Singleton();

  private Singleton() {
  }

  public static Singleton getInstance() {
    return instance;
  }

  public void doSomething(){
    System.out.println("This is a singleton");
  }

}

Getting an error "fopen': This function or variable may be unsafe." when compling

This is not an error, it is a warning from your Microsoft compiler.

Select your project and click "Properties" in the context menu.

In the dialog, chose Configuration Properties -> C/C++ -> Preprocessor

In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS to turn those warnings off.

Check whether a value is a number in JavaScript or jQuery

You've an number of options, depending on how you want to play it:

isNaN(val)

Returns true if val is not a number, false if it is. In your case, this is probably what you need.

isFinite(val)

Returns true if val, when cast to a String, is a number and it is not equal to +/- Infinity

/^\d+$/.test(val)

Returns true if val, when cast to a String, has only digits (probably not what you need).

Can I do Android Programming in C++, C?

You can use the Android NDK, but answers should note that the Android NDK app is not free to use and there's no clear open source route to programming Android on Android in an increasingly Android-driven market that began as open source, with Android developer support or the extensiveness of the NDK app, meaning you're looking at abandoning Android as any kind of first steps programming platform without payments.

Note: I consider subscription requests as payments under duress and this is a freemium context which continues to go undefeated by the open source community.

Maximum value of maxRequestLength?

2,147,483,647 bytes, since the value is a signed integer (Int32). That's probably more than you'll need.

Why I get 'list' object has no attribute 'items'?

result_list = [int(v) for k,v in qs[0].items()]

qs is a list, qs[0] is the dict which you want!

Get Context in a Service

  1. Service extends ContextWrapper
  2. ContextWrapper extends Context

So....

Context context = this;

(in Service or Activity Class)

Simple bubble sort c#

public static void BubbleSort(int[] a)
    {

       for (int i = 1; i <= a.Length - 1; ++i)

            for (int j = 0; j < a.Length - i; ++j)

                if (a[j] > a[j + 1])


                    Swap(ref a[j], ref a[j + 1]);

    }

    public static void Swap(ref int x, ref int y)
    {
        int temp = x;
        x = y;
        y = temp;
    }

sql select with column name like

Thank you @Blorgbeard for the genious idea.

By the way Blorgbeard's query was not working for me so I edited it:

DECLARE @Table_Name as VARCHAR(50) SET @Table_Name = 'MyTable'          -- put here you table name
DECLARE @Column_Like as VARCHAR(20) SET @Column_Like = '%something%'    -- put here you element
DECLARE @sql NVARCHAR(MAX) SET @sql = 'select '

SELECT @sql = @sql + '[' + sys.columns.name + '],'
FROM sys.columns 
JOIN sys.tables ON sys.columns.object_id = tables.object_id
WHERE sys.columns.name like @Column_Like
and sys.tables.name = @Table_Name

SET @sql = left(@sql,len(@sql)-1) -- remove trailing comma
SET @sql = @sql + ' from ' + @Table_Name

EXEC sp_executesql @sql

How to get relative path from absolute path

Use:

RelPath = AbsPath.Replace(ApplicationPath, ".")

Can Javascript read the source of any web page?

On linux

  1. download slimerjs (slimerjs.org)

  2. download firefox version 59

  3. add this environment variable: export SLIMERJSLAUNCHER=/home/en/Letöltések/firefox59/firefox/firefox

  4. on slimerjs download page use this .js program (./slomerjs program.js):

     var page = require('webpage').create();
     page.open(
      'http://www.google.com/search?q=görény',
       function() 
       {
         page.render('goo2.pdf');
         phantom.exit();
       }
     );
    

Use pdftotext to get text on the page.

How to pass anonymous types as parameters?

I think you should make a class for this anonymous type. That'd be the most sensible thing to do in my opinion. But if you really don't want to, you could use dynamics:

public void LogEmployees (IEnumerable<dynamic> list)
{
    foreach (dynamic item in list)
    {
        string name = item.Name;
        int id = item.Id;
    }
}

Note that this is not strongly typed, so if, for example, Name changes to EmployeeName, you won't know there's a problem until runtime.

Using Chrome, how to find to which events are bound to an element

For Chrome Version 52.0.2743.116:

  1. In Chrome's Developer Tools, bring up the 'Search' panel by hitting Ctrl+Shift+F.

  2. Type in the name of the element you're trying to find.

Results for binded elements should appear in the panel and state the file they're located in.

Python re.sub replace with matched content

For the replacement portion, Python uses \1 the way sed and vi do, not $1 the way Perl, Java, and Javascript (amongst others) do. Furthermore, because \1 interpolates in regular strings as the character U+0001, you need to use a raw string or \escape it.

Python 3.2 (r32:88445, Jul 27 2011, 13:41:33) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> method = 'images/:id/huge'
>>> import re
>>> re.sub(':([a-z]+)', r'<span>\1</span>', method)
'images/<span>id</span>/huge'
>>> 

How to get complete month name from DateTime

DateTime birthDate = new DateTime(1981, 8, 9);
Console.WriteLine ("I was born on the {0}. of {1}, {2}.", birthDate.Day, birthDate.ToString("MMMM"), birthDate.Year);

/* The above code will say:
"I was born on the 9. of august, 1981."

"dd" converts to the day (01 thru 31).
"ddd" converts to 3-letter name of day (e.g. mon).
"dddd" converts to full name of day (e.g. monday).
"MMM" converts to 3-letter name of month (e.g. aug).
"MMMM" converts to full name of month (e.g. august).
"yyyy" converts to year.
*/

Displaying better error message than "No JSON object could be decoded"

I've found that the simplejson module gives more descriptive errors in many cases where the built-in json module is vague. For instance, for the case of having a comma after the last item in a list:

json.loads('[1,2,]')
....
ValueError: No JSON object could be decoded

which is not very descriptive. The same operation with simplejson:

simplejson.loads('[1,2,]')
...
simplejson.decoder.JSONDecodeError: Expecting object: line 1 column 5 (char 5)

Much better! Likewise for other common errors like capitalizing True.

Java: Why is the Date constructor deprecated, and what do I use instead?

You can make a method just like new Date(year,month,date) in your code by using Calendar class.

private Date getDate(int year,int month,int date){
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, year);
    cal.set(Calendar.MONTH, month-1);
    cal.set(Calendar.DAY_OF_MONTH, day);
    return cal.getTime();
}

It will work just like the deprecated constructor of Date

How to handle login pop up window using Selenium WebDriver?

You can use this Autoit script to handle the login popup:

WinWaitActive("Authentication Required","","10")
If WinExists("Authentication Required") Then
Send("username{TAB}")
Send("Password{Enter}")
EndIf'

Getting the ID of the element that fired an event

The source element as a jQuery object should be obtained via

var $el = $(event.target);

This gets you the source of the click, rather than the element that the click function was assigned too. Can be useful when the click event is on a parent object EG.a click event on a table row, and you need the cell that was clicked

$("tr").click(function(event){
    var $td = $(event.target);
});

Passing parameter via url to sql server reporting service

As per this link you may also have to prefix your param with &rp if not using proxy syntax

How to change ProgressBar's progress indicator color in Android

A simpler solution:

progess_drawable_blue

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@android:id/background">
    <shape>
        <solid
                android:color="@color/disabled" />
    </shape>
</item>

<item
    android:id="@android:id/progress">
    <clip>
        <shape>
            <solid
                android:color="@color/blue" />
        </shape>
    </clip>
</item>

</layer-list>

Render Content Dynamically from an array map function in React Native

lapsList() {

    return this.state.laps.map((data) => {
      return (
        <View><Text>{data.time}</Text></View>
      )
    })
}

You forgot to return the map. this code will resolve the issue.

How to use mouseover and mouseout in Angular 6

In HTML:

<div (mouseover)="funcName1() (mouseout)="funcName2()">
   // Do what you want 
</div>

In TypeScript:

funcName1(){
 //Do Something
}
funcName2(){
//Do Something
}

VBScript -- Using error handling

You can regroup your steps functions calls in a facade function :

sub facade()
    call step1()
    call step2()
    call step3()
    call step4()
    call step5()
end sub

Then, let your error handling be in an upper function that calls the facade :

sub main()
    On error resume next

    call facade()

    If Err.Number <> 0 Then
        ' MsgBox or whatever. You may want to display or log your error there
        msgbox Err.Description
        Err.Clear
    End If

    On Error Goto 0
end sub

Now, let's suppose step3() raises an error. Since facade() doesn't handle errors (there is no On error resume next in facade()), the error will be returned to main() and step4() and step5() won't be executed.

Your error handling is now refactored in 1 code block

ImportError: No module named 'Queue'

I just copy the file name Queue.py in the */lib/python2.7/ to queue.py and that solved my problem.

OpenCV - Saving images to a particular folder of choice

The solution provided by ebeneditos works perfectly.

But if you have cv2.imwrite() in several sections of a large code snippet and you want to change the path where the images get saved, you will have to change the path at every occurrence of cv2.imwrite() individually.

As Soltius stated, here is a better way. Declare a path and pass it as a string into cv2.imwrite()

import cv2
import os
img = cv2.imread('1.jpg', 1)
path = 'D:/OpenCV/Scripts/Images'
cv2.imwrite(os.path.join(path , 'waka.jpg'), img)
cv2.waitKey(0)

Now if you want to modify the path, you just have to change the path variable.

Edited based on solution provided by Kallz

sort json object in javascript

Here is a simple snippet that sorts a javascript representation of a Json.

function isObject(v) {
    return '[object Object]' === Object.prototype.toString.call(v);
};

JSON.sort = function(o) {
if (Array.isArray(o)) {
        return o.sort().map(JSON.sort);
    } else if (isObject(o)) {
        return Object
            .keys(o)
        .sort()
            .reduce(function(a, k) {
                a[k] = JSON.sort(o[k]);

                return a;
            }, {});
    }

    return o;
}

It can be used as follows:

JSON.sort({
    c: {
        c3: null,
        c1: undefined,
        c2: [3, 2, 1, 0],
    },
    a: 0,
    b: 'Fun'
});

That will output:

{
  a: 0,
  b: 'Fun',
  c: {
    c2: [3, 2, 1, 0],
    c3: null
  }
}

Static image src in Vue.js template

@Pantelis answer somehow steered me to a solution for a similar misunderstanding. A message board project I'm working on needs to show an optional image. I was having fits trying to get the src=imagefile to concatenate a fixed path and variable filename string until I saw the quirky use of "''" quotes :-)

<template id="symp-tmpl">
  <div>
    <div v-for="item in items" style="clear: both;">
      <div v-if="(item.imagefile !== '[none]')">
        <img v-bind:src="'/storage/userimages/' + item.imagefile">
      </div>
      sub: <span>@{{ item.subject }}</span>
      <span v-if="(login == item.author)">[edit]</span>
      <br>@{{ item.author }}
      <br>msg: <span>@{{ item.message }}</span>
    </div>
  </div>
</template>

Open PDF in new browser full window

var pdf = MyPdf.pdf;
window.open(pdf);

This will open the pdf document in a full window from JavaScript

A function to open windows would look like this:

function openPDF(pdf){
  window.open(pdf);
  return false;
}

GCC dump preprocessor defines

Late answer - I found the other answers useful - and wanted to add a bit extra.


How do I dump preprocessor macros coming from a particular header file?

echo "#include <sys/socket.h>" | gcc -E -dM -

or (thanks to @mymedia for the suggestion):

gcc -E -dM -include sys/socket.h - < /dev/null

In particular, I wanted to see what SOMAXCONN was defined to on my system. I know I could just open up the standard header file, but sometimes I have to search around a bit to find the header file locations. Instead I can just use this one-liner:

$ gcc -E -dM -include sys/socket.h - < /dev/null | grep SOMAXCONN
#define SOMAXCONN 128
$ 

How to send email from SQL Server?

You can send email natively from within SQL Server using Database Mail. This is a great tool for notifying sysadmins about errors or other database events. You could also use it to send a report or an email message to an end user. The basic syntax for this is:

EXEC msdb.dbo.sp_send_dbmail  
@recipients='[email protected]',
@subject='Testing Email from SQL Server',
@body='<p>It Worked!</p><p>Email sent successfully</p>',
@body_format='HTML',
@from_address='Sender Name <[email protected]>',
@reply_to='[email protected]'

Before use, Database Mail must be enabled using the Database Mail Configuration Wizard, or sp_configure. A database or Exchange admin might need to help you configure this. See http://msdn.microsoft.com/en-us/library/ms190307.aspx and http://www.codeproject.com/Articles/485124/Configuring-Database-Mail-in-SQL-Server for more information.

How to pass parameters to $http in angularjs?

Here is how you do it:

$http.get("/url/to/resource/", {params:{"param1": val1, "param2": val2}})
    .then(function (response) { /* */ })...

Angular takes care of encoding the parameters.

Maxim Shoustin's answer does not work ({method:'GET', url:'/search', jsonData} is not a valid JavaScript literal) and JeyTheva's answer, although simple, is dangerous as it allows XSS (unsafe values are not escaped when you concatenate them).

Install apk without downloading

For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.

    Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);

If you want it to download and install from your own server then use the following code

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
    startActivity(intent);

How is returning the output of a function different from printing it?

The below examples might help understand:

def add_nums1(x,y):
    print(x+y)

def add_nums2(x,y):
    return x+y 

#----Function output is usable for further processing
add_nums2(10,20)/2
15.0

#----Function output can't be used further (gives TypeError)
add_nums1(10,20)/2

30
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-124-e11302d7195e> in <module>
----> 1 add_nums1(10,20)/2

TypeError: unsupported operand type(s) for /: 'NoneType' and 'int'

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

How do I increase modal width in Angular UI Bootstrap?

I solved the problem using Dmitry Komin solution, but with different CSS syntax to make it works directly in browser.

CSS

@media(min-width: 1400px){
    .my-modal > .modal-lg {
        width: 1308px;
    }
}

JS is the same:

var modal = $modal.open({
    animation: true,
    templateUrl: 'modalTemplate.html',
    controller: 'modalController',
    size: 'lg',
    windowClass: 'my-modal'
});

C# - What does the Assert() method do? Is it still useful?

The way I think of it is Debug.Assert is a way to establish a contract about how a method is supposed to be called, focusing on specifics about the values of a paramter (instead of just the type). For example, if you are not supposed to send a null in the second parameter you add the Assert around that parameter to tell the consumer not to do that.

It prevents someone from using your code in a boneheaded way. But it also allows that boneheaded way to go through to production and not give the nasty message to a customer (assuming you build a Release build).

Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

All error codes are on "CFNetwork Errors Codes References" on the documentation (link)

A small extraction for CFURL and CFURLConnection Errors:

  kCFURLErrorUnknown   = -998,
  kCFURLErrorCancelled = -999,
  kCFURLErrorBadURL    = -1000,
  kCFURLErrorTimedOut  = -1001,
  kCFURLErrorUnsupportedURL = -1002,
  kCFURLErrorCannotFindHost = -1003,
  kCFURLErrorCannotConnectToHost    = -1004,
  kCFURLErrorNetworkConnectionLost  = -1005,
  kCFURLErrorDNSLookupFailed        = -1006,
  kCFURLErrorHTTPTooManyRedirects   = -1007,
  kCFURLErrorResourceUnavailable    = -1008,
  kCFURLErrorNotConnectedToInternet = -1009,
  kCFURLErrorRedirectToNonExistentLocation = -1010,
  kCFURLErrorBadServerResponse             = -1011,
  kCFURLErrorUserCancelledAuthentication   = -1012,
  kCFURLErrorUserAuthenticationRequired    = -1013,
  kCFURLErrorZeroByteResource        = -1014,
  kCFURLErrorCannotDecodeRawData     = -1015,
  kCFURLErrorCannotDecodeContentData = -1016,
  kCFURLErrorCannotParseResponse     = -1017,
  kCFURLErrorInternationalRoamingOff = -1018,
  kCFURLErrorCallIsActive               = -1019,
  kCFURLErrorDataNotAllowed             = -1020,
  kCFURLErrorRequestBodyStreamExhausted = -1021,
  kCFURLErrorFileDoesNotExist           = -1100,
  kCFURLErrorFileIsDirectory            = -1101,
  kCFURLErrorNoPermissionsToReadFile    = -1102,
  kCFURLErrorDataLengthExceedsMaximum   = -1103,

How to add a delay for a 2 or 3 seconds

You could use Thread.Sleep() function, e.g.

int milliseconds = 2000;
Thread.Sleep(milliseconds);

that completely stops the execution of the current thread for 2 seconds.

Probably the most appropriate scenario for Thread.Sleep is when you want to delay the operations in another thread, different from the main e.g. :

 MAIN THREAD        --------------------------------------------------------->
 (UI, CONSOLE ETC.)      |                                      |
                         |                                      |
 OTHER THREAD            ----- ADD A DELAY (Thread.Sleep) ------>

For other scenarios (e.g. starting operations after some time etc.) check Cody's answer.

What is the best data type to use for money in C#?

Decimal. If you choose double you're leaving yourself open to rounding errors

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

It's probably because MySQL is installed but not yet running.

To verify that it's running, open up Activity Monitor and under "All Processes", search and verify you see the process "mysqld".

You can start it by installing "MySQL.prefPane".

Here is the complete tutorial which helped me: http://obscuredclarity.blogspot.in/2009/08/install-mysql-on-mac-os-x.html

How to use random in BATCH script?

If you will divide by some large value you will get a huge amount of duplicates one after other. What you need to do is to take modulo of the %RANDOM% value:

@echo off
REM 
SET maxvalue=10
SET minvalue=1

SETLOCAL 
SET /A tmpRandom=((%RANDOM%)%%(%maxvalue%))+(%minvalue%)
echo "Tmp random: %tmpRandom%"
echo "Random:  %RANDOM%"
ENDLOCAL

I/O error(socket error): [Errno 111] Connection refused

I previously had this problem with my EC2 instance (I was serving couchdb to serve resources -- am considering Amazon's S3 for the future).

One thing to check (assuming Ec2) is that the couchdb port is added to your open ports within your security policy.

I specifically encountered

"[Errno 111] Connection refused"

over EC2 when the instance was stopped and started. The problem seems to be a pidfile race. The solution for me was killing couchdb (entirely and properly) via:

pkill -f couchdb

and then restarting with:

/etc/init.d/couchdb restart

how get yesterday and tomorrow datetime in c#

Use DateTime.AddDays() (MSDN Documentation DateTime.AddDays Method).

DateTime tomorrow = DateTime.Now.AddDays(1);
DateTime yesterday = DateTime.Now.AddDays(-1);

Why use the params keyword?

No need to create overload methods, just use one single method with params as shown below

// Call params method with one to four integer constant parameters.
//
int sum0 = addTwoEach();
int sum1 = addTwoEach(1);
int sum2 = addTwoEach(1, 2);
int sum3 = addTwoEach(3, 3, 3);
int sum4 = addTwoEach(2, 2, 2, 2);

PHP: How to get current time in hour:minute:second?

You can have both formats as an argument to the function date():

date("d-m-Y H:i:s")

Check the manual for more info : http://php.net/manual/en/function.date.php

As pointed out by @ThomasVdBerge to display minutes you need the 'i' character

What's the difference between a 302 and a 307 redirect?

A good example of the 307 Internal Redirect in action is when Google Chrome encounters a HTTP call to a domain it knows as requiring Strict Transport Security.

The browser redirects seamlessly, using the same method as the original call.

HTST 307 Internal Redirect

Clear image on picturebox

I've had a stubborn image too, that wouldn't go away by setting the Image and InitialImage to null. To remove the image from the pictureBox for good, I had to use the code below, by calling Application.DoEvents() repeatedly:

            Application.DoEvents();
            if (_pictureBox.Image != null)
                _pictureBox.Image.Dispose();
            _pictureBox.Image = null;
            Application.DoEvents();
            if (_pictureBox.InitialImage != null)
                _pictureBox.InitialImage.Dispose();
            _pictureBox.InitialImage = null;
            _pictureBox.Update();
            Application.DoEvents();
            _pictureBox.Refresh();

Typescript interface default values

It is depends on the case and the usage. Generally, in TypeScript there are no default values for interfaces.

If you don't use the default values
You can declare x as:

let x: IX | undefined; // declaration: x = undefined

Then, in your init function you can set real values:

x = {
    a: 'xyz'
    b: 123
    c: new AnotherType()
};

In this way, x can be undefined or defined - undefined represents that the object is uninitialized, without set the default values, if they are unnecessary. This is loggically better than define "garbage".

If you want to partially assign the object:
You can define the type with optional properties like:

interface IX {
    a: string,
    b?: any,
    c?: AnotherType
}

In this case you have to set only a. The other types are marked with ? which mean that they are optional and have undefined as default value.

In any case you can use undefined as a default value, it is just depends on your use case.

Firebase (FCM) how to get token

If are using some auth function of firebase, you can take token using this:

//------GET USER TOKEN-------
FirebaseUser mUser = FirebaseAuth.getInstance().getCurrentUser();
mUser.getToken(true)
        .addOnCompleteListener(new OnCompleteListener<GetTokenResult>() {
            public void onComplete(@NonNull Task<GetTokenResult> task) {
                if (task.isSuccessful()) {
                    String idToken = task.getResult().getToken();
                      // ...
                }
            }
        });

Work well if user are logged. getCurrentUser()

"Input string was not in a correct format."

I ran into this exact exception, except it had nothing to do with parsing numerical inputs. So this isn't an answer to the OP's question, but I think it's acceptable to share the knowledge.

I'd declared a string and was formatting it for use with JQTree which requires curly braces ({}). You have to use doubled curly braces for it to be accepted as a properly formatted string:

string measurements = string.empty;
measurements += string.Format(@"
    {{label: 'Measurement Name: {0}',
        children: [
            {{label: 'Measured Value: {1}'}},
            {{label: 'Min: {2}'}},
            {{label: 'Max: {3}'}},
            {{label: 'Measured String: {4}'}},
            {{label: 'Expected String: {5}'}},
        ]
    }},",
    drv["MeasurementName"] == null ? "NULL" : drv["MeasurementName"],
    drv["MeasuredValue"] == null ? "NULL" : drv["MeasuredValue"],
    drv["Min"] == null ? "NULL" : drv["Min"],
    drv["Max"] == null ? "NULL" : drv["Max"],
    drv["MeasuredString"] == null ? "NULL" : drv["MeasuredString"],
    drv["ExpectedString"] == null ? "NULL" : drv["ExpectedString"]);

Hopefully this will help other folks who find this question but aren't parsing numerical data.

Apply formula to the entire column

This is for those who want to overwrite the column cells quickly (without cutting and copying). This is the same as double-clicking the cell box but unlike double-clicking, it still works after the first try.

  1. Select the column cell you would like to copy downwards
  2. Press Ctrl+Shift+ to select the cells below
  3. Press Ctrl+Enter to copy the contents of the first cell into the cells below

BONUS:

The shortcut for going to the bottom-most content (to double-check the copy) is Ctrl+. To go back up you can use Ctrl+ but if your top rows are frozen you'll also have to press Enter a few times.

How to create nonexistent subdirectories recursively using Bash?

mkdir -p newDir/subdir{1..8}
ls newDir/
subdir1 subdir2 subdir3 subdir4 subdir5 subdir6 subdir7 subdir8

How to set Python's default version to 3.x on OS X?

Go to 'Applications', enter 'Python' folder, there should be a bash script called 'Update Shell Profile.command' or similar. Run that script and it should do it.

Update: It looks like you should not update it: how to change default python version?

Changing background color of text box input not working when empty

on body tag's onLoad try setting it like

document.getElementById("subEmail").style.backgroundColor = "yellow";

and after that on change of that input field check if some value is there, or paint it yellow like

function checkFilled() {
var inputVal = document.getElementById("subEmail");
if (inputVal.value == "") {
    inputVal.style.backgroundColor = "yellow";
            }
    }

How to disable spring security for particular url

If you want to ignore multiple API endpoints you can use as follow:

 @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeRequests() 
            .antMatchers("/api/v1/**").authenticated()
            .antMatchers("api/v1/authenticate**").permitAll()
            .antMatchers("**").permitAll()
            .and().exceptionHandling().and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

How to append data to a json file?

You can simply import the data from the source file, read it, and save what you want to append to a variable. Then open the destination file, assign the list data inside to a new variable (presumably this will all be valid JSON), then use the 'append' function on this list variable and append the first variable to it. Viola, you have appended to the JSON list. Now just overwrite your destination file with the newly appended list (as JSON).

The 'a' mode in your 'open' function will not work here because it will just tack everything on to the end of the file, which will make it non-valid JSON format.

firestore: PERMISSION_DENIED: Missing or insufficient permissions

Your rules should be like this for this case however the message says that it is not the suggested way, but if you do this you can do inserts with no permission error

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write;
    }
  }
}

Checkout one file from Subversion

cd C:\path\dir
svn checkout https://server/path/to/trunk/dir/dir/parent_dir--depth empty
cd C:\path\dir\parent_dir
svn update filename.log

(Edit filename.log)

svn commit -m "this is a comment."

How to convert string to boolean in typescript Angular 4

I have been trying different values with JSON.parse(value) and it seems to do the work:

// true
Boolean(JSON.parse("true"));
Boolean(JSON.parse("1"));
Boolean(JSON.parse(1));
Boolean(JSON.parse(true));

// false
Boolean(JSON.parse("0")); 
Boolean(JSON.parse(0));
Boolean(JSON.parse("false"));
Boolean(JSON.parse(false));

How to Inspect Element using Safari Browser

In your Safari menu bar click Safari > Preferences & then select the Advanced tab.

Select: "Show Develop menu in menu bar"

Now you can click Develop in your menu bar and choose Show Web Inspector

You can also right-click and press "Inspect element".

Non-static method requires a target

Normally it happens when the target is null. So better check the invoke target first then do the linq query.

Pass connection string to code-first DbContext

Can't see anything wrong with your code, I use SqlExpress and it works fine when I use a connection string in the constructor.

You have created an App_Data folder in your project, haven't you?

How to split a delimited string into an array in awk?

To split a string to an array in awk we use the function split():

 awk '{split($0, a, ":")}'
 #           ^^  ^  ^^^
 #            |  |   |
 #       string  |   delimiter
 #               |
 #               array to store the pieces

If no separator is given, it uses the FS, which defaults to the space:

$ awk '{split($0, a); print a[2]}' <<< "a:b c:d e"
c:d

We can give a separator, for example ::

$ awk '{split($0, a, ":"); print a[2]}' <<< "a:b c:d e"
b c

Which is equivalent to setting it through the FS:

$ awk -F: '{split($0, a); print a[1]}' <<< "a:b c:d e"
b c

In gawk you can also provide the separator as a regexp:

$ awk '{split($0, a, ":*"); print a[2]}' <<< "a:::b c::d e" #note multiple :
b c

And even see what the delimiter was on every step by using its fourth parameter:

$ awk '{split($0, a, ":*", sep); print a[2]; print sep[1]}' <<< "a:::b c::d e"
b c
:::

Let's quote the man page of GNU awk:

split(string, array [, fieldsep [, seps ] ])

Divide string into pieces separated by fieldsep and store the pieces in array and the separator strings in the seps array. The first piece is stored in array[1], the second piece in array[2], and so forth. The string value of the third argument, fieldsep, is a regexp describing where to split string (much as FS can be a regexp describing where to split input records). If fieldsep is omitted, the value of FS is used. split() returns the number of elements created. seps is a gawk extension, with seps[i] being the separator string between array[i] and array[i+1]. If fieldsep is a single space, then any leading whitespace goes into seps[0] and any trailing whitespace goes into seps[n], where n is the return value of split() (i.e., the number of elements in array).

Install apps silently, with granted INSTALL_PACKAGES permission

I tried on rooted Android 4.2.2 and this method works for me:

private void installApk(String filename) {
    File file = new File(filename); 
    if(file.exists()){
        try {   
            final String command = "pm install -r " + file.getAbsolutePath();
            Process proc = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
            proc.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
     }
}

How to display images from a folder using php - PHP

Here is a possible solution the solution #3 on my comments to blubill's answer:

yourscript.php
========================
<?php
    $dir = '/home/user/Pictures';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if (file_exists($dir) == false) 
    {
        echo 'Directory "', $dir, '" not found!';
    } 
    else 
    {
        $dir_contents = scandir($dir);

        foreach ($dir_contents as $file) 
        {
            $file_type = strtolower(end(explode('.', $file)));
            if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true)     
            {
                $name = basename($file);
                echo "<img src='img.php?name={$name}' />";
            }
        }
    }
?>


img.php
========================
<?php
    $name = $_GET['name'];
    $mimes = array
    (
        'jpg' => 'image/jpg',
        'jpeg' => 'image/jpg',
        'gif' => 'image/gif',
        'png' => 'image/png'
    );

    $ext = strtolower(end(explode('.', $name)));

    $file = '/home/users/Pictures/'.$name;
    header('content-type: '. $mimes[$ext]);
    header('content-disposition: inline; filename="'.$name.'";');
    readfile($file);
?>

How do I get length of list of lists in Java?

count of the contained lists in the outmost list

int count = data.size();

lambda to get the count of the contained inner lists

int count = data.stream().collect( summingInt(l -> l.size()) );

ASP.NET - How to write some html in the page? With Response.Write?

why don't you give LiteralControl a try?

 myLitCtrl.Text="<h2><p>Notify:</p> Alert</h2>";

Is there any way to configure multiple registries in a single npmrc file

You can have multiple registries for scoped packages in your .npmrc file. For example:

@polymer:registry=<url register A>
registry=http://localhost:4873/

Packages under @polymer scope will be received from https://registry.npmjs.org, but the rest will be received from your local NPM.

Most efficient way to see if an ArrayList contains an object in Java

There are three basic options:

1) If retrieval performance is paramount and it is practical to do so, use a form of hash table built once (and altered as/if the List changes).

2) If the List is conveniently sorted or it is practical to sort it and O(log n) retrieval is sufficient, sort and search.

3) If O(n) retrieval is fast enough or if it is impractical to manipulate/maintain the data structure or an alternate, iterate over the List.

Before writing code more complex than a simple iteration over the List, it is worth thinking through some questions.

  • Why is something different needed? (Time) performance? Elegance? Maintainability? Reuse? All of these are okay reasons, apart or together, but they influence the solution.

  • How much control do you have over the data structure in question? Can you influence how it is built? Managed later?

  • What is the life cycle of the data structure (and underlying objects)? Is it built up all at once and never changed, or highly dynamic? Can your code monitor (or even alter) its life cycle?

  • Are there other important constraints, such as memory footprint? Does information about duplicates matter? Etc.

What jar should I include to use javax.persistence package in a hibernate based application?

In general, i agree with above answers that recommend to add maven dependency, but i prefer following solution.

Add a dependency with API classes for full JavaEE profile:

<properties>
    <javaee-api.version>7.0</javaee-api.version>
    <hibernate-entitymanager.version>5.1.3.Final</hibernate-entitymanager.version>
</properties>

<depencies>
    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-api</artifactId>
        <version>${javaee-api.version}</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

Also add dependency with particular JPA provider like antonycc suggested:

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-entitymanager</artifactId>
    <version>${hibernate-entitymanager.version}</version>
</dependency>

Note <scope>provided</scope> in API dependency section: this means that corresponding jar will not be exported into artifact's lib/, but will be provided by application server. Make sure your application server implements specified version of JavaEE API.

How to get jSON response into variable from a jquery script

You should use data.response in your JS instead of json.response.

PHP call Class method / function

As th function is not using $this at all, you can add a static keyword just after public and then call

Functions::filter($_GET['params']);

Avoiding the creation of an object just for one method call

How to make a script wait for a pressed key?

If you want to wait for enter (so the user knocking the keyboard does not cause something un-intended to happen) use

sys.stdin.readline()

Javascript array declaration: new Array(), new Array(3), ['a', 'b', 'c'] create arrays that behave differently

Arrays in JS have two types of properties:

Regular elements and associative properties (which are nothing but objects)

When you define a = new Array(), you are defining an empty array. Note that there are no associative objects yet

When you define b = new Array(2), you are defining an array with two undefined locations.

In both your examples of 'a' and 'b', you are adding associative properties i.e. objects to these arrays.

console.log (a) or console.log(b) prints the array elements i.e. [] and [undefined, undefined] respectively. But since a1/a2 and b1/b2 are associative objects inside their arrays, they can be logged only by console.log(a.a1, a.a2) kind of syntax

Simple way to compare 2 ArrayLists

The answer is given in @dku-rajkumar post.

ArrayList commonList = CollectionUtils.retainAll(list1,list2);

How to send a simple email from a Windows batch file?

If you can't follow Max's suggestion of installing Blat (or any other utility) on your server, then perhaps your server already has software installed that can send emails.

I know that both Oracle and SqlServer have the capability to send email. You might have to work with your DBA to get that feature enabled and/or get the privilege to use it. Of course I can see how that might present its own set of problems and red tape. Assuming you can access the feature, it is fairly simple to have a batch file login to a database and send mail.

A batch file can easily run a VBScript via CSCRIPT. A quick google search finds many links showing how to send email with VBScript. The first one I happened to look at was http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/enterprise/mail/. It looks straight forward.

sys.argv[1] meaning in script

sys.argv is a list.

This list is created by your command line, it's a list of your command line arguments.

For example:

in your command line you input something like this,

python3.2 file.py something

sys.argv will become a list ['file.py', 'something']

In this case sys.argv[1] = 'something'

ASP.NET Background image

You can use this if you want to assign a background image on the backend:

divContent.Attributes.Add("style"," background-image:
url('images/icon_stock.gif');");

How to add Drop-Down list (<select>) programmatically?

_x000D_
_x000D_
const cars = ['Volvo', 'Saab', 'Mervedes', 'Audi'];_x000D_
_x000D_
let domSelect = document.createElement('select');_x000D_
domSelect.multiple = true;_x000D_
document.getElementsByTagName('body')[0].appendChild(domSelect);_x000D_
_x000D_
_x000D_
for (const i in cars) {_x000D_
  let optionSelect = document.createElement('option');_x000D_
_x000D_
  let optText = document.createTextNode(cars[i]);_x000D_
  optionSelect.appendChild(optText);_x000D_
_x000D_
  document.getElementsByTagName('select')[0].appendChild(optionSelect);_x000D_
}
_x000D_
_x000D_
_x000D_

Best way to get identity of inserted row?

  • @@IDENTITY returns the last identity value generated for any table in the current session, across all scopes. You need to be careful here, since it's across scopes. You could get a value from a trigger, instead of your current statement.

  • SCOPE_IDENTITY() returns the last identity value generated for any table in the current session and the current scope. Generally what you want to use.

  • IDENT_CURRENT('tableName') returns the last identity value generated for a specific table in any session and any scope. This lets you specify which table you want the value from, in case the two above aren't quite what you need (very rare). Also, as @Guy Starbuck mentioned, "You could use this if you want to get the current IDENTITY value for a table that you have not inserted a record into."

  • The OUTPUT clause of the INSERT statement will let you access every row that was inserted via that statement. Since it's scoped to the specific statement, it's more straightforward than the other functions above. However, it's a little more verbose (you'll need to insert into a table variable/temp table and then query that) and it gives results even in an error scenario where the statement is rolled back. That said, if your query uses a parallel execution plan, this is the only guaranteed method for getting the identity (short of turning off parallelism). However, it is executed before triggers and cannot be used to return trigger-generated values.

Dismissing a Presented View Controller

I like this one:

        (viewController.navigationController?.presentingViewController
            ?? viewController.presentingViewController
            ?? viewController).dismiss(animated: true)

How can I use xargs to copy files that have spaces and quotes in their names?

With Bash (not POSIX) you can use process substitution to get the current line inside a variable. This enables you to use quotes to escape special characters:

while read line ; do cp "$line" ~/bar ; done < <(find . | grep foo)

Remove Style on Element

Just use like this

 $("#sample_id").css("width", "");
 $("#sample_id").css("height", "");

What is meant with "const" at end of function declaration?

A "const function", denoted with the keyword const after a function declaration, makes it a compiler error for this class function to change a member variable of the class. However, reading of a class variables is okay inside of the function, but writing inside of this function will generate a compiler error.

Another way of thinking about such "const function" is by viewing a class function as a normal function taking an implicit this pointer. So a method int Foo::Bar(int random_arg) (without the const at the end) results in a function like int Foo_Bar(Foo* this, int random_arg), and a call such as Foo f; f.Bar(4) will internally correspond to something like Foo f; Foo_Bar(&f, 4). Now adding the const at the end (int Foo::Bar(int random_arg) const) can then be understood as a declaration with a const this pointer: int Foo_Bar(const Foo* this, int random_arg). Since the type of this in such case is const, no modifications of member variables are possible.

It is possible to loosen the "const function" restriction of not allowing the function to write to any variable of a class. To allow some of the variables to be writable even when the function is marked as a "const function", these class variables are marked with the keyword mutable. Thus, if a class variable is marked as mutable, and a "const function" writes to this variable then the code will compile cleanly and the variable is possible to change. (C++11)

As usual when dealing with the const keyword, changing the location of the const key word in a C++ statement has entirely different meanings. The above usage of const only applies when adding const to the end of the function declaration after the parenthesis.

const is a highly overused qualifier in C++: the syntax and ordering is often not straightforward in combination with pointers. Some readings about const correctness and the const keyword:

Const correctness

The C++ 'const' Declaration: Why & How

Removing duplicates in the lists

There are many other answers suggesting different ways to do this, but they're all batch operations, and some of them throw away the original order. That might be okay depending on what you need, but if you want to iterate over the values in the order of the first instance of each value, and you want to remove the duplicates on-the-fly versus all at once, you could use this generator:

def uniqify(iterable):
    seen = set()
    for item in iterable:
        if item not in seen:
            seen.add(item)
            yield item

This returns a generator/iterator, so you can use it anywhere that you can use an iterator.

for unique_item in uniqify([1, 2, 3, 4, 3, 2, 4, 5, 6, 7, 6, 8, 8]):
    print(unique_item, end=' ')

print()

Output:

1 2 3 4 5 6 7 8

If you do want a list, you can do this:

unique_list = list(uniqify([1, 2, 3, 4, 3, 2, 4, 5, 6, 7, 6, 8, 8]))

print(unique_list)

Output:

[1, 2, 3, 4, 5, 6, 7, 8]

MySQL "incorrect string value" error when save unicode string in Django

If you have this problem here's a python script to change all the columns of your mysql database automatically.

#! /usr/bin/env python
import MySQLdb

host = "localhost"
passwd = "passwd"
user = "youruser"
dbname = "yourdbname"

db = MySQLdb.connect(host=host, user=user, passwd=passwd, db=dbname)
cursor = db.cursor()

cursor.execute("ALTER DATABASE `%s` CHARACTER SET 'utf8' COLLATE 'utf8_unicode_ci'" % dbname)

sql = "SELECT DISTINCT(table_name) FROM information_schema.columns WHERE table_schema = '%s'" % dbname
cursor.execute(sql)

results = cursor.fetchall()
for row in results:
  sql = "ALTER TABLE `%s` convert to character set DEFAULT COLLATE DEFAULT" % (row[0])
  cursor.execute(sql)
db.close()

Reinitialize Slick js after successful ajax call

I was facing an issue where Slick carousel wasn't refreshing on new data, it was appending new slides to previous ones, I found an answer which solved my problem, it's very simple.

try unslick, then assign your new data which is being rendered inside slick carousel, and then initialize slick again. these were the steps for me:

jQuery('.class-or-#id').slick('unslick');
myData = my-new-data;
jQuery('.class-or-#id').slick({slick options});

Note: check slick website for syntax just in case. also make sure you are not using unslick before slick is even initialized, what that means is simply initialize (like this jquery('.my-class').slick({options}); the first ajax call and once it is initialized then follow above steps, you may wanna use if else

AttributeError("'str' object has no attribute 'read'")

You need to open the file first. This doesn't work:

json_file = json.load('test.json')

But this works:

f = open('test.json')
json_file = json.load(f)

How to add buttons like refresh and search in ToolBar in Android?

Try to do this:

getSupportActionBar().setDisplayShowTitleEnabled(false);
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
getSupportActionBar().setDisplayShowTitleEnabled(false);

and if you made your custom toolbar (which i presume you did) then you can use the simplest way possible to do this:

toolbarTitle = (TextView)findViewById(R.id.toolbar_title);
toolbarSubTitle = (TextView)findViewById(R.id.toolbar_subtitle);
toolbarTitle.setText("Title");
toolbarSubTitle.setText("Subtitle");

Same goes for any other views you put in your toolbar. Hope it helps.

How to reload the current route with the angular 2 router

reload current route in angular 2 very helpful link to reload current route in angualr 2 or 4

in this define two technique to do this

  1. with dummy query params
  2. with dummy route

for more see above link

Select records from today, this week, this month php mysql

A better solution for "today" is:

SELECT * FROM jokes WHERE DATE(date) = DATE(NOW())

How to add more than one machine to the trusted hosts list using winrm

winrm set winrm/config/client '@{TrustedHosts="machineA,machineB"}'

How to detect when keyboard is shown and hidden

There is a CocoaPods to facilitate the observation on NSNotificationCentr for the keyboard's visibility here: https://github.com/levantAJ/Keyhi

pod 'Keyhi'

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

It could also be because, it might not be able to found the .dll file required. Either the file is not in the folder or is renamed. I faced the same issue and found that .dll file was missing in my bin folder some how.

check output from CalledProcessError

According to the Python os module documentation os.popen has been deprecated since Python 2.6.

I think the solution for modern Python is to use check_output() from the subprocess module.

From the subprocess Python documentation:

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False) Run command with arguments and return its output as a byte string.

If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute.

If you run through the following code in Python 2.7 (or later):

import subprocess

try:
    print subprocess.check_output(["ping", "-n", "2", "-w", "2", "1.1.1.1"])
except subprocess.CalledProcessError, e:
    print "Ping stdout output:\n", e.output

You should see an output that looks something like this:

Ping stdout output:

Pinging 1.1.1.1 with 32 bytes of data:
Request timed out.
Request timed out.

Ping statistics for 1.1.1.1:
Packets: Sent = 2, Received = 0, Lost = 2 (100% loss),

The e.output string can be parsed to suit the OPs needs.

If you want the returncode or other attributes, they are in CalledProccessError as can be seen by stepping through with pdb

(Pdb)!dir(e)   

['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
 '__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__',
 '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
 '__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__', 
 '__unicode__', '__weakref__', 'args', 'cmd', 'message', 'output', 'returncode']

Angular bootstrap datepicker date format does not format ng-model value

Although similar answers have been posted I'd like to contribute what seemed to be the easiest and cleanest fix to me. Assuming you are using the AngularUI datepicker and your initial value for the ng-Model does not get formatted simply adding the following directive to your project will fix the issue:

angular.module('yourAppName')
.directive('datepickerPopup', function (){
    return {
        restrict: 'EAC',
        require: 'ngModel',
        link: function(scope, element, attr, controller) {
      //remove the default formatter from the input directive to prevent conflict
      controller.$formatters.shift();
  }
}
});

I found this solution in the Github AngularUI issues and therefore all credit goes to the people over there.

How to remove text before | character in notepad++

To replace anything that starts with "text" until the last character:

text.+(.*)$

Example

text             hsjh sdjh sd          jhsjhsdjhsdj hsd
                                                      ^
                                                      last character


To replace anything that starts with "text" until "123"

text.+(\ 123)

Example

text fuhfh283nfnd03no3 d90d3nd 3d 123 udauhdah au dauh ej2e
^                                   ^
From here                     To here

ASP.NET MVC ActionLink and post method

This is taken from the MVC sample project

@if (ViewBag.ShowRemoveButton)
      {
         using (Html.BeginForm("RemoveLogin", "Manage"))
           {
              @Html.AntiForgeryToken()
                  <div>
                     @Html.Hidden("company_name", account)
                     @Html.Hidden("returnUrl", Model.returnUrl)
                     <input type="submit" class="btn btn-default" value="Remove" title="Remove your email address from @account" />
                  </div>
            }
        }

How to detect Safari, Chrome, IE, Firefox and Opera browser?

You can use try and catch to use the different browser error messages. IE and edge were mixed up, but I used the duck typing from Rob W (based on this project here: https://www.khanacademy.org/computer-programming/i-have-opera/2395080328).

var getBrowser = function() {        
    try {
        var e;
        var f = e.width;
    } catch(e) {
        var err = e.toString();

        if(err.indexOf("not an object") !== -1) {
            return "safari";
        } else if(err.indexOf("Cannot read") !== -1) {
            return "chrome";
        } else if(err.indexOf("e is undefined") !== -1) {
            return "firefox";
        } else if(err.indexOf("Unable to get property 'width' of undefined or null reference") !== -1) {
            if(!(false || !!document.documentMode) && !!window.StyleMedia) {
                return "edge";
            } else {
                return "IE";
            }
        } else if(err.indexOf("cannot convert e into object") !== -1) {
            return "opera";
        } else {
            return undefined;
        }
    }
};

Why is Visual Studio 2013 very slow?

Performance Explorer

Have you been using menu AnalyzePerformance and Diagnostics? I have! It's awesome! But you may want to clean up.

Open the Performance Explorer. If you collapse all of the items in there, select all, then you can right click and do Delete.

My solution opens faster and is in general running much faster now.

Also you may notice changes to your sln file as shown. For me, this section was deleted from the sln.

GlobalSection(Performance) = preSolution
    HasPerformanceSessions = true
EndGlobalSection

Proper MIME type for OTF fonts

FWIW regarding Apache 2.2 VirtualHosting and mod_mime tested on Debian Linux and OS X Leopard and Snow Leopard:

If you have a VirtualHost configuration you will want to add the types via the AddType Directive as follows at least at the bottom of the configuration as follows:

....
   AddType font/opentype .otf
   AddType font/ttf .ttf
</VirtualHost>

Tested against Chrome Unstable/Trunk and Safari WebKit Nightly which eliminates the mime octet-stream warnings for both the ttf and otf font types.

Note: .htaccess has zero effect when dealing with VirtualHosting. If you're developing for several sites you'll be using VirtualHosting development and each configuration will need these AddType additions.

MVC pattern on Android

Android's MVC pattern is (kind-of) implemented with their Adapter classes. They replace a controller with an "adapter." The description for the adapter states:

An Adapter object acts as a bridge between an AdapterView and the underlying data for that view.

I'm just looking into this for an Android application that reads from a database, so I don't know how well it works yet. However, it seems a little like Qt's Model-View-Delegate architecture, which they claim is a step up from a traditional MVC pattern. At least on the PC, Qt's pattern works fairly well.

In which conda environment is Jupyter executing?

Question 1: Find the current notebook's conda environment

Open the notebook in Jupyter Notebooks and look in the upper right corner of the screen.

It should say, for example, "Python [env_name]" if the language is Python and it's using an environment called env_name.

jupyter notebook with name of environment


Question 2: Start Jupyter Notebook from within a different conda environment

Activate a conda environment in your terminal using source activate <environment name> before you run jupyter notebook. This sets the default environment for Jupyter Notebooks. Otherwise, the [Root] environment is the default.

jupyter notebooks home screen, conda tab, create new environment

You can also create new environments from within Jupyter Notebook (home screen, Conda tab, and then click the plus sign).

And you can create a notebook in any environment you want. Select the "Files" tab on the home screen and click the "New" dropdown menu, and in that menu select a Python environment from the list.

jupyter notebooks home screen, files tab, create new notebook

Converting an int to std::string

Suppose I have integer = 0123456789101112. Now, this integer can be converted into a string by the stringstream class.

Here is the code in C++:

   #include <bits/stdc++.h>
   using namespace std;
   int main()
   {
      int n,i;
      string s;
      stringstream st;
      for(i=0;i<=12;i++)
      {
        st<<i;
      }
      s=st.str();
      cout<<s<<endl;
      return 0;

    }

How to register multiple servlets in web.xml in one Spring application

As explained in this thread on the cxf-user mailing list, rather than having the CXFServlet load its own spring context from user-webservice-servlet.xml, you can just load the whole lot into the root context. Rename your existing user-webservice-servlet.xml to some other name (e.g. user-webservice-beans.xml) then change your contextConfigLocation parameter to something like:

<servlet>
  <servlet-name>myservlet</servlet-name>
  <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>myservlet</servlet-name>
  <url-pattern>*.htm</url-pattern>
</servlet-mapping>

<context-param>
  <param-name>contextConfigLocation</param-name>
  <param-value>
    /WEB-INF/applicationContext.xml
    /WEB-INF/user-webservice-beans.xml
  </param-value>
</context-param>

<servlet>
  <servlet-name>user-webservice</servlet-name>
  <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
  <load-on-startup>2</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>user-webservice</servlet-name>
  <url-pattern>/UserService/*</url-pattern>
</servlet-mapping>

How do I get only directories using Get-ChildItem?

Use:

Get-ChildItem \\myserver\myshare\myshare\ -Directory | Select-Object -Property name |  convertto-csv -NoTypeInformation  | Out-File c:\temp\mydirectorylist.csv

Which does the following

  • Get a list of directories in the target location: Get-ChildItem \\myserver\myshare\myshare\ -Directory
  • Extract only the name of the directories: Select-Object -Property name
  • Convert the output to CSV format: convertto-csv -NoTypeInformation
  • Save the result to a file: Out-File c:\temp\mydirectorylist.csv

Access host database from a docker container

If you want access to a Docker container where there is a DB, you have to add a bash:

docker exec -it postgresql bash

postgresql is the container name.

Once inside, from the bash, access to DB e.g:

$psql -U postgres

Skip first entry in for loop in python?

If cars is a sequence you can just do

for car in cars[1:-1]:
    pass

Pythonic way to return list of every nth item in a larger list

  1. source_list[::10] is the most obvious, but this doesn't work for any iterable and is not memory efficient for large lists.
  2. itertools.islice(source_sequence, 0, None, 10) works for any iterable and is memory-efficient, but probably is not the fastest solution for large list and big step.
  3. (source_list[i] for i in xrange(0, len(source_list), 10))

How can I dynamically add a directive in AngularJS?

function addAttr(scope, el, attrName, attrValue) {
  el.replaceWith($compile(el.clone().attr(attrName, attrValue))(scope));
}

Webpack.config how to just copy the index.html to the dist folder

To copy an already existing index.html file into the dist directory you can simply use the HtmlWebpackPlugin by specifying the source index.html as a template.

const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  // ...
  plugins: [    
    new HtmlWebpackPlugin({
      template: './path/to/index.html',
    })
  ],
  // ...
};

The created dist/index.html file will be basically the same as your source file with the difference that bundled resources like .js files are injected with <script> tags by webpack. Minification and further options can be configured and are documented on github.

What are all the escape characters?

Yes, below is a link of docs.Oracle where you can find complete list of escape characters in Java.

Escape characters are always preceded with "\" and used to perform some specific task like go to next line etc.

For more Details on Escape Character Refer following link:

https://docs.oracle.com/javase/tutorial/java/data/characters.html

How to create a new variable in a data.frame based on a condition?

One obvious and straightforward possibility is to use "if-else conditions". In that example

x <- c(1, 2, 4)
y <- c(1, 4, 5)
w <- ifelse(x <= 1, "good", ifelse((x >= 3) & (x <= 5), "bad", "fair"))
data.frame(x, y, w)

** For the additional question in the edit** Is that what you expect ?

> d1 <- c("e", "c", "a")
> d2 <- c("e", "a", "b")
> 
> w <- ifelse((d1 == "e") & (d2 == "e"), 1, 
+    ifelse((d1=="a") & (d2 == "b"), 2,
+    ifelse((d1 == "e"), 3, 99)))
>     
> data.frame(d1, d2, w)
  d1 d2  w
1  e  e  1
2  c  a 99
3  a  b  2

If you do not feel comfortable with the ifelse function, you can also work with the if and else statements for such applications.

Initialise a list to a specific length in Python

In a talk about core containers internals in Python at PyCon 2012, Raymond Hettinger is suggesting to use [None] * n to pre-allocate the length you want.

Slides available as PPT or via Google

The whole slide deck is quite interesting. The presentation is available on YouTube, but it doesn't add much to the slides.

Java converting Image to BufferedImage

If you are getting back a sun.awt.image.ToolkitImage, you can cast the Image to that, and then use getBufferedImage() to get the BufferedImage.

So instead of your last line of code where you are casting you would just do:

BufferedImage buffered = ((ToolkitImage) image).getBufferedImage();

Android Crop Center of Bitmap

Have you considered doing this from the layout.xml ? You could set for your ImageView the ScaleType to android:scaleType="centerCrop" and set the dimensions of the image in the ImageView inside the layout.xml.

Undefined reference to vtable

  • Are you sure that CDasherComponent has a body for the destructor? It's definitely not here - the question is if it is in the .cc file.
  • From a style perspective, CDasherModule should explicitly define its destructor virtual.
  • It looks like CGameModule has an extra } at the end (after the }; // for the class).
  • Is CGameModule being linked against the libraries that define CDasherModule and CDasherComponent?

How do I lock the orientation to portrait mode in a iPhone Web Application?

While you cannot prevent orientation change from taking effect you can emulate no change as stated in other answers.

First detect device orientation or reorientation and, using JavaScript, add a class name to your wrapping element (in this example I use the body tag).

function deviceOrientation() {
  var body = document.body;
  switch(window.orientation) {
    case 90:
      body.classList = '';
      body.classList.add('rotation90');
      break;
    case -90:
      body.classList = '';
      body.classList.add('rotation-90');
      break;
    default:
      body.classList = '';
      body.classList.add('portrait');
      break;
  }
}
window.addEventListener('orientationchange', deviceOrientation);
deviceOrientation();

Then if the device is landscape, use CSS to set the body width to the viewport height and the body height to the viewport width. And let’s set the transform origin while we’re at it.

@media screen and (orientation: landscape) {
  body {
    width: 100vh;
    height: 100vw;
    transform-origin: 0 0;
  }
}

Now, reorient the body element and slide (translate) it into position.

body.rotation-90 {
  transform: rotate(90deg) translateY(-100%);
}
body.rotation90 {
  transform: rotate(-90deg) translateX(-100%);
}

Error: Segmentation fault (core dumped)

It's worth trying faulthandler to identify the line or the library that is causing the issue as mentioned here https://stackoverflow.com/a/58825725/2160809 and in the comments by Karuhanga

faulthandler.enable()
// bad code goes here

or

$ python3 -q -X faulthandler
>>> /// bad cod goes here

Calling dynamic function with dynamic number of parameters

Now I'm using this:

Dialoglar.Confirm = function (_title, _question, callback_OK) {
    var confirmArguments = arguments;
    bootbox.dialog({
        title: "<b>" + _title + "</b>",
        message: _question,
        buttons: {
            success: {
                label: "OK",
                className: "btn-success",
                callback: function () {
                    if (typeof(callback_OK) == "function") {                            callback_OK.apply(this,Array.prototype.slice.call(confirmArguments, 3));
                    }
                }
            },
            danger: {
                label: "Cancel",
                className: "btn-danger",
                callback: function () {
                    $(this).hide();
                }
            }
        }
    });
};

jQuery UI " $("#datepicker").datepicker is not a function"

I struggled with a similar problem for hours. It then turned out that jQuery was included twice, once by the program that I was adding a jQuery function to and once by our in-house debugger.

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

I'm using Android Studio Beta version 0.8.1 and I have the same problem. I now I sold my problem by changing the AVD (I'm using Genymotion) to API 19. and here is my build.gradle file

apply plugin: 'com.android.application'

android {
    compileSdkVersion 19
    buildToolsVersion "19.1.0"

    defaultConfig {
        applicationId "com.example.daroath.actionbar"
        minSdkVersion 14
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

enter image description here

Hope this help!

Clean up a fork and restart it from the upstream

How to do it 100% through the Sourcetree GUI

(Not everyone likes doing things through the git command line interface)

Once this has been set up, you only need to do steps 7-13 from then on.

Fetch > checkout master branch > reset to their master > Push changes to server

Steps

  1. In the menu toolbar at the top of the screen: "Repository" > "Repository settings"

"Repository" highlighted in the top menu bar

  1. "Add"

"Add" button at the bottom of the dialog

  1. Go back to GitHub and copy the clone URL.

"Clone or Download" button on the Github website followed by the git url

  1. Paste the url into the "URL / Path" field then give it a name that makes sense. I called it "master". Do not check the "Default remote" checkbox. You will not be able to push directly to this repository.

"Remote name" and "URL / Path" fields highlighted in the"Remote details" dialog

  1. Press "OK" and you should see it appear in your list of repositories now.

"master" repository added to the list of repositories in the "Repository settings" dialog

  1. Press "OK" again and you should see it appear in your list of "Remotes".

"master" repository highlighted in remotes list in side bar

  1. Click the "Fetch" button (top left of the Source tree header area)

"Fetch" button in the header area

  1. Make sure the "Fetch from all remotes" checkbox is checked and press "ok"

"Fetch from all remotes" checkbox highlighted in the "Fetch" dialog

  1. Double click on your "master" branch to check it out if it is not checked out already.

  2. Find the commit that you want to reset to, if you called the repo "master" you will most likely want to find the commit with the "master/master" tag on it.

Example of a commit with a "master/master" tag on it

  1. Right click on the commit > "Reset current branch to this commit".

  2. In the dialog, set the "Using mode:" field to "Hard - discard all working copy changes" then press "OK" (make sure to put any changes that you don't want to lose onto a separate branch first).

"Using mode" field highlighted in the "Reset to commit" dialog. It is set to "discard all working copy changes"

  1. Click the "Push" button (top left of the Source tree header area) to upload the changes to your copy of the repo.

"Push" button in the header area

Your Done!

Mean per group in a data.frame

A third great alternative is using the package data.table, which also has the class data.frame, but operations like you are looking for are computed much faster.

library(data.table)
mydt <- structure(list(Name = c("Aira", "Aira", "Aira", "Ben", "Ben", "Ben", "Cat", "Cat", "Cat"), Month = c(1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L), Rate1 = c(15.6396600443877, 2.15649279424609, 6.24692918928743, 2.37658797276116, 34.7500663272292, 3.28750138697048, 29.3265553981065, 17.9821839334431, 10.8639802575958), Rate2 = c(17.1680489538369, 5.84231656330206, 8.54330866437461, 5.88415184986176, 3.02064294862551, 17.2053351400752, 16.9552950199166, 2.56058000170089, 15.7496228048122)), .Names = c("Name", "Month", "Rate1", "Rate2"), row.names = c(NA, -9L), class = c("data.table", "data.frame"))

Now to take the mean of Rate1 and Rate2 for all 3 months, for each person (Name): First, decide which columns you want to take the mean of

colstoavg <- names(mydt)[3:4]

Now we use lapply to take the mean over the columns we want to avg (colstoavg)

mydt.mean <- mydt[,lapply(.SD,mean,na.rm=TRUE),by=Name,.SDcols=colstoavg]

 mydt.mean
   Name     Rate1     Rate2
1: Aira  8.014361 10.517891
2:  Ben 13.471385  8.703377
3:  Cat 19.390907 11.755166

Windows batch - concatenate multiple text files into one

In Win 7, navigate to the directory where your text files are. On the command prompt use:

copy *.txt combined.txt

Where combined.txt is the name of the newly created text file.

React PropTypes : Allow different types of PropTypes for one prop

Here is pro example of using multi proptypes and single proptype.

import React, { Component } from 'react';
import { string, shape, array, oneOfType } from 'prop-types';

class MyComponent extends Component {
  /**
   * Render
   */
  render() {
    const { title, data } = this.props;

    return (
      <>
        {title}
        <br />
        {data}
      </>
    );
  }
}

/**
 * Define component props
 */
MyComponent.propTypes = {
  data: oneOfType([array, string, shape({})]),
  title: string,
};

export default MyComponent;

How do I get video durations with YouTube API version 3?

Duration in seconds using Python 2.7 and the YouTube API v3:

    try:        
        dur = entry['contentDetails']['duration']
        try:
            minutes = int(dur[2:4]) * 60
        except:
            minutes = 0
        try:
            hours = int(dur[:2]) * 60 * 60
        except:
            hours = 0

        secs = int(dur[5:7])
        print hours, minutes, secs
        video.duration = hours + minutes + secs
        print video.duration
    except Exception as e:
        print "Couldnt extract time: %s" % e
        pass

Is it possible to create a File object from InputStream

Easy Java 9 solution with try with resources block

public static void copyInputStreamToFile(InputStream input, File file) {  

    try (OutputStream output = new FileOutputStream(file)) {
        input.transferTo(output);
    } catch (IOException ioException) {
        ioException.printStackTrace();
    }

}

java.io.InputStream#transferTo is available since Java 9.

Wait until an HTML5 video loads

call function on load:

<video onload="doWhatYouNeedTo()" src="demo.mp4" id="video">

get video duration

var video = document.getElementById("video");
var duration = video.duration;

How to convert string to float?

Use atof()

But this is deprecated, use this instead:

const char* flt = "4.0800";
float f;
sscanf(flt, "%f", &f);

http://www.cplusplus.com/reference/clibrary/cstdlib/atof/

atof() returns 0 for both failure and on conversion of 0.0, best to not use it.

git is not installed or not in the PATH

I did install git and tried again and got the same error. But running 'npm install' in a new command prompt window worked for me. Restarting the machine is not required.

How can I disable notices and warnings in PHP within the .htaccess file?

I used ini_set('display_errors','off'); and it worked great.

Check for column name in a SqlDataReader object

Neither did I get GetSchemaTable to work, until I found this way.

Basically I do this:

Dim myView As DataView = dr.GetSchemaTable().DefaultView
myView.RowFilter = "ColumnName = 'ColumnToBeChecked'"

If myView.Count > 0 AndAlso dr.GetOrdinal("ColumnToBeChecked") <> -1 Then
  obj.ColumnToBeChecked = ColumnFromDb(dr, "ColumnToBeChecked")
End If

How to get the size of a range in Excel

The overall dimensions of a range are in its Width and Height properties.

Dim r As Range
Set r = ActiveSheet.Range("A4:H12")

Debug.Print r.Width
Debug.Print r.Height

How can I store and retrieve images from a MySQL database using PHP?

Personally i wouldnt store the image in the database, Instead put it in a folder not accessable from outside, and use the database for keeping track of its location. keeps database size down and you can just include it by using PHP. There would be no way without PHP to access that image then

Combine two columns of text in pandas dataframe

my take....

listofcols = ['col1','col2','col3']
df['combined_cols'] = ''

for column in listofcols:
    df['combined_cols'] = df['combined_cols'] + ' ' + df[column]
'''

How do I select an element with its name attribute in jQuery?

jQuery("[name='test']") 

Although you should avoid it and if possible select by ID (e.g. #myId) as this has better performance because it invokes the native getElementById.

Android Intent Cannot resolve constructor

You Can not Use the Intent's Context for Creating Intent. So You need to use your Fragment's Parent Activity Context

Intent intent = new Intent(getActivity(),MyClass.class);

How do you get the process ID of a program in Unix or Linux using Python?

For Windows

A Way to get all the pids of programs on your computer without downloading any modules:

import os

pids = []
a = os.popen("tasklist").readlines()
for x in a:
      try:
         pids.append(int(x[29:34]))
      except:
           pass
for each in pids:
         print(each)

If you just wanted one program or all programs with the same name and you wanted to kill the process or something:

import os, sys, win32api

tasklistrl = os.popen("tasklist").readlines()
tasklistr = os.popen("tasklist").read()

print(tasklistr)

def kill(process):
     process_exists_forsure = False
     gotpid = False
     for examine in tasklistrl:
            if process == examine[0:len(process)]:
                process_exists_forsure = True
     if process_exists_forsure:
         print("That process exists.")
     else:
        print("That process does not exist.")
        raw_input()
        sys.exit()
     for getpid in tasklistrl:
         if process == getpid[0:len(process)]:
                pid = int(getpid[29:34])
                gotpid = True
                try:
                  handle = win32api.OpenProcess(1, False, pid)
                  win32api.TerminateProcess(handle, 0)
                  win32api.CloseHandle(handle)
                  print("Successfully killed process %s on pid %d." % (getpid[0:len(prompt)], pid))
                except win32api.error as err:
                  print(err)
                  raw_input()
                  sys.exit()
    if not gotpid:
       print("Could not get process pid.")
       raw_input()
       sys.exit()

   raw_input()
   sys.exit()

prompt = raw_input("Which process would you like to kill? ")
kill(prompt)

That was just a paste of my process kill program I could make it a whole lot better but it is okay.

Reset C int array to zero : the fastest way?

zero(myarray); is all you need in C++.

Just add this to a header:

template<typename T, size_t SIZE> inline void zero(T(&arr)[SIZE]){
    memset(arr, 0, SIZE*sizeof(T));
}

Trying to use Spring Boot REST to Read JSON String from POST

To add on to Andrea's solution, if you are passing an array of JSONs for instance

[
    {"name":"value"},
    {"name":"value2"}
]

Then you will need to set up the Spring Boot Controller like so:

@RequestMapping(
    value = "/process", 
    method = RequestMethod.POST)
public void process(@RequestBody Map<String, Object>[] payload) 
    throws Exception {

    System.out.println(payload);

}

Check if space is in a string

word = ' '
while True:
    if ' ' in word:
        word = raw_input("Please enter a single word: ")
    else:
        print "Thanks"
        break

This is more idiomatic python - comparison against True or False is not necessary - just use the value returned by the expression ' ' in word.

Also, you don't need to use pastebin for such a small snippet of code - just copy the code into your post and use the little 1s and 0s button to make your code look like code.

How to stop java process gracefully?

Ok, after all the possibilities I have chosen to work with "Java Monitoring and Management"
Overview is here
That allows you to control one application from another one in relatively easy way. You can call the controlling application from a script to stop controlled application gracefully before killing it.

Here is the simplified code:

Controlled application:
run it with the folowing VM parameters:
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=9999
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false

//ThreadMonitorMBean.java
public interface ThreadMonitorMBean
{
String getName();
void start();
void stop();
boolean isRunning();
}

// ThreadMonitor.java
public class ThreadMonitor implements ThreadMonitorMBean
{
private Thread m_thrd = null;

public ThreadMonitor(Thread thrd)
{
    m_thrd = thrd;
}

@Override
public String getName()
{
    return "JMX Controlled App";
}

@Override
public void start()
{
    // TODO: start application here
    System.out.println("remote start called");
}

@Override
public void stop()
{
    // TODO: stop application here
    System.out.println("remote stop called");

    m_thrd.interrupt();
}

public boolean isRunning()
{
    return Thread.currentThread().isAlive();
}

public static void main(String[] args)
{
    try
    {
        System.out.println("JMX started");

        ThreadMonitorMBean monitor = new ThreadMonitor(Thread.currentThread());

        MBeanServer server = ManagementFactory.getPlatformMBeanServer();

        ObjectName name = new ObjectName("com.example:type=ThreadMonitor");

        server.registerMBean(monitor, name);

        while(!Thread.interrupted())
        {
            // loop until interrupted
            System.out.println(".");
            try 
            {
                Thread.sleep(1000);
            } 
            catch(InterruptedException ex) 
            {
                Thread.currentThread().interrupt();
            }
        }
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        // TODO: some final clean up could be here also
        System.out.println("JMX stopped");
    }
}
}

Controlling application:
run it with the stop or start as the command line argument

public class ThreadMonitorConsole
{

public static void main(String[] args)
{
    try
    {   
        // connecting to JMX
        System.out.println("Connect to JMX service.");
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
        JMXConnector jmxc = JMXConnectorFactory.connect(url, null);
        MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();

        // Construct proxy for the the MBean object
        ObjectName mbeanName = new ObjectName("com.example:type=ThreadMonitor");
        ThreadMonitorMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, ThreadMonitorMBean.class, true);

        System.out.println("Connected to: "+mbeanProxy.getName()+", the app is "+(mbeanProxy.isRunning() ? "" : "not ")+"running");

        // parse command line arguments
        if(args[0].equalsIgnoreCase("start"))
        {
            System.out.println("Invoke \"start\" method");
            mbeanProxy.start();
        }
        else if(args[0].equalsIgnoreCase("stop"))
        {
            System.out.println("Invoke \"stop\" method");
            mbeanProxy.stop();
        }

        // clean up and exit
        jmxc.close();
        System.out.println("Done.");    
    }
    catch(Exception e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}


That's it. :-)

Rails.env vs RAILS_ENV

Strange behaviour while debugging my app: require "active_support/notifications" (rdb:1) p ENV['RAILS_ENV'] "test" (rdb:1) p Rails.env "development"

I would say that you should stick to one or another (and preferably Rails.env)

How to unzip a file in Powershell?

In PowerShell v5+, there is an Expand-Archive command (as well as Compress-Archive) built in:

Expand-Archive c:\a.zip -DestinationPath c:\a

How to encrypt String in Java

String s1="arshad"; 
char[] s2=s1.toCharArray(); 
int s3= s2.length; 

  System.out.println(s3);
 int i=0; 

// for(int j=0;j<s3;j++) 
// System.out.println(s2[j]); 

for(i=0;i<((s3)/2);i++) { 

char z,f=10; 
z=(char) (s2[i] * f); 
s2[i]=s2[(s3-1)-i]; 
s2[(s3-1)-i]=z; 

String b=new String(s2);

 print(b);  }

Boolean.parseBoolean("1") = false...?

As a note ,
for those who need to have null value for things other than "true" or "false" strings , you can use the function below

public Boolean tryParseBoolean(String inputBoolean)
{    
    if(!inputBoolean.equals("true")&&!inputBoolean.equals("false")) return null;
    return Boolean.valueOf(inputBoolean);
}

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

Execute and get the output of a shell command in node.js

Requirements

This will require Node.js 7 or later with a support for Promises and Async/Await.

Solution

Create a wrapper function that leverage promises to control the behavior of the child_process.exec command.

Explanation

Using promises and an asynchronous function, you can mimic the behavior of a shell returning the output, without falling into a callback hell and with a pretty neat API. Using the await keyword, you can create a script that reads easily, while still be able to get the work of child_process.exec done.

Code sample

const childProcess = require("child_process");

/**
 * @param {string} command A shell command to execute
 * @return {Promise<string>} A promise that resolve to the output of the shell command, or an error
 * @example const output = await execute("ls -alh");
 */
function execute(command) {
  /**
   * @param {Function} resolve A function that resolves the promise
   * @param {Function} reject A function that fails the promise
   * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
   */
  return new Promise(function(resolve, reject) {
    /**
     * @param {Error} error An error triggered during the execution of the childProcess.exec command
     * @param {string|Buffer} standardOutput The result of the shell command execution
     * @param {string|Buffer} standardError The error resulting of the shell command execution
     * @see https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback
     */
    childProcess.exec(command, function(error, standardOutput, standardError) {
      if (error) {
        reject();

        return;
      }

      if (standardError) {
        reject(standardError);

        return;
      }

      resolve(standardOutput);
    });
  });
}

Usage

async function main() {
  try {
    const passwdContent = await execute("cat /etc/passwd");

    console.log(passwdContent);
  } catch (error) {
    console.error(error.toString());
  }

  try {
    const shadowContent = await execute("cat /etc/shadow");

    console.log(shadowContent);
  } catch (error) {
    console.error(error.toString());
  }
}

main();

Sample Output

root:x:0:0::/root:/bin/bash
[output trimmed, bottom line it succeeded]

Error: Command failed: cat /etc/shadow
cat: /etc/shadow: Permission denied

Try it online.

Repl.it.

External resources

Promises.

child_process.exec.

Node.js support table.

remove double quotes from Json return data using Jquery

What you are doing is making a JSON string in your example. Either don't use the JSON.stringify() or if you ever do have JSON data coming back and you don't want quotations, Simply use JSON.parse() to remove quotations around JSON responses! Don't use regex, there's no need to.

Python Requests library redirect new url

I think requests.head instead of requests.get will be more safe to call when handling url redirect,check the github issue here:

r = requests.head(url, allow_redirects=True)
print(r.url)

How to select a dropdown value in Selenium WebDriver using Java

Just wrap your WebElement into Select Object as shown below

Select dropdown = new Select(driver.findElement(By.id("identifier")));

Once this is done you can select the required value in 3 ways. Consider an HTML file like this

<html>
<body>
<select id = "designation">
<option value = "MD">MD</option>
<option value = "prog"> Programmer </option>
<option value = "CEO"> CEO </option>
</option>
</select>
<body>
</html>

Now to identify dropdown do

Select dropdown = new Select(driver.findElement(By.id("designation")));

To select its option say 'Programmer' you can do

dropdown.selectByVisibleText("Programmer ");

or

dropdown.selectByIndex(1);

or

 dropdown.selectByValue("prog");

What is an instance variable in Java?

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

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

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

This test class illustrates the difference:

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

How to get selected path and name of the file opened with file dialog?

The below command is enough to get the path of the file from a dialog box -

my_FileName = Application.GetOpenFilename("Excel Files (*.tsv), *.txt")