Programs & Examples On #Uiapplication

The UIApplication class provides a centralized point of control and coordination for apps running on iOS. Every app must have exactly one instance of UIApplication (or a subclass of UIApplication). When an app is launched, the UIApplicationMain function is called; among its other tasks, this function creates a singleton UIApplication object. Thereafter you access this object by invoking the sharedApplication class method.

iOS Launching Settings -> Restrictions URL Scheme

If you add the prefs URL scheme to your iOS app, it will allow you to use all those schemes that we could in iOS 5. I've tested it on iOS 9, but I think it will work on older versions too.

How can I access global variable inside class in Python

class flag:
    ## Store pseudo-global variables here

    keys=False

    sword=True

    torch=False


## test the flag class

print('______________________')

print(flag.keys)
print(flag.sword)
print (flag.torch)


## now change the variables

flag.keys=True
flag.sword= not flag.sword
flag.torch=True

print('______________________')

print(flag.keys)
print(flag.sword)
print (flag.torch)

Passing multiple values for a single parameter in Reporting Services

The below solution worked for me.

  1. In the parameter tab of your dataset properties click on the expression icon (!http://chittagongit.com//images/fx-icon/fx-icon-16.jpg [fx symbol]) beside the parameter you need to allow comma delimited entry for.

  2. In the expression window that appears, use the Split function (Common Functions -> Text). Example shown below:

=Split(Parameters!ParameterName.Value,",")

Setting up a websocket on Apache?

I can't answer all questions, but I will do my best.

As you already know, WS is only a persistent full-duplex TCP connection with framed messages where the initial handshaking is HTTP-like. You need some server that's listening for incoming WS requests and that binds a handler to them.

Now it might be possible with Apache HTTP Server, and I've seen some examples, but there's no official support and it gets complicated. What would Apache do? Where would be your handler? There's a module that forwards incoming WS requests to an external shared library, but this is not necessary with the other great tools to work with WS.

WS server trends now include: Autobahn (Python) and Socket.IO (Node.js = JavaScript on the server). The latter also supports other hackish "persistent" connections like long polling and all the COMET stuff. There are other little known WS server frameworks like Ratchet (PHP, if you're only familiar with that).

In any case, you will need to listen on a port, and of course that port cannot be the same as the Apache HTTP Server already running on your machine (default = 80). You could use something like 8080, but even if this particular one is a popular choice, some firewalls might still block it since it's not supposed to be Web traffic. This is why many people choose 443, which is the HTTP Secure port that, for obvious reasons, firewalls do not block. If you're not using SSL, you can use 80 for HTTP and 443 for WS. The WS server doesn't need to be secure; we're just using the port.

Edit: According to Iharob Al Asimi, the previous paragraph is wrong. I have no time to investigate this, so please see his work for more details.

About the protocol, as Wikipedia shows, it looks like this:

Client sends:

GET /mychat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
Origin: http://example.com

Server replies:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

and keeps the connection alive. If you can implement this handshaking and the basic message framing (encapsulating each message with a small header describing it), then you can use any client-side language you want. JavaScript is only used in Web browsers because it's built-in.

As you can see, the default "request method" is an initial HTTP GET, although this is not really HTTP and looses everything in common with HTTP after this handshaking. I guess servers that do not support

Upgrade: websocket
Connection: Upgrade

will reply with an error or with a page content.

How do I stop/start a scheduled task on a remote computer programmatically?

What about /disable, and /enable switch for a /change command?

schtasks.exe /change /s <machine name> /tn <task name> /disable
schtasks.exe /change /s <machine name> /tn <task name> /enable

How to solve "Connection reset by peer: socket write error"?

It seems like your problem may be arising at

while(in.read(outputByte,0,4096)!=-1){

where it might go into an infinite loop for not advancing the offset (which is 0 always in the call). Try

while(in.read(outputByte)!=-1){

which will by default try to read upto outputByte.length into the byte[]. This way you dont have to worry about the offset. See FileInputStrem's read method

__FILE__ macro shows full path

GCC 8 now has the -fmacro-prefix-map and -ffile-prefix-map options:

-fmacro-prefix-map=old=new

When preprocessing files residing in directory old, expand the __FILE__ and __BASE_FILE__ macros as if the files resided in directory new instead. This can be used to change an absolute path to a relative path by using . for new which can result in more reproducible builds that are location independent. This option also affects __builtin_FILE() during compilation. See also -ffile-prefix-map.

-ffile-prefix-map=old=new

When compiling files residing in directory old, record any references to them in the result of the compilation as if the files resided in directory new instead. Specifying this option is equivalent to specifying all the individual -f*-prefix-map options. This can be used to make reproducible builds that are location independent. See also -fmacro-prefix-map and -fdebug-prefix-map.

Setting an invalid path for -ffile-prefix-map (-fdebug-prefix-map) will break debugging unless you tell your debugger how to map back. (gdb: set substitue-path, vscode: "sourceFileMap").

If your intent is to only clean up __FILE__ just use -fmacro-prefix-map.

Example: So for my Jenkins builds I will add -ffile-prefix-map=${WORKSPACE}/=/, and another to remove the local dev package install prefix.

NOTE Unfortunately the -ffile-prefix-map and -fmacro-prefix-map options are only available in GCC 8 onwards. For, say, GCC 5, we only have -fdebug-prefix-map which does not affect __FILE__.

MySQL combine two columns into one column

My guess is that you are using MySQL where the + operator does addition, along with silent conversion of the values to numbers. If a value does not start with a digit, then the converted value is 0.

So try this:

select concat(column1, column2)

Two ways to add a space:

select concat(column1, ' ', column2)
select concat_ws(' ', column1, column2)

How to handle configuration in Go

I usually use JSON for more complicated data structures. The downside is that you easily end up with a bunch of code to tell the user where the error was, various edge cases and what not.

For base configuration (api keys, port numbers, ...) I've had very good luck with the gcfg package. It is based on the git config format.

From the documentation:

Sample config:

; Comment line
[section]
name = value # Another comment
flag # implicit value for bool is true

Go struct:

type Config struct {
    Section struct {
            Name string
            Flag bool
    }
}

And the code needed to read it:

var cfg Config
err := gcfg.ReadFileInto(&cfg, "myconfig.gcfg")

It also supports slice values, so you can allow specifying a key multiple times and other nice features like that.

Dependent DLL is not getting copied to the build output folder in Visual Studio

In my case, it was the stupidest thing, caused by a default behavior of TFS/VS that I disagree with.

Since adding the dll as a reference to the main project did not work, I decided to add it as an "Existing Item", with Copy Local = Always. Even then the file was not there.

Turns out that, even though the file is present on the VS Solution and everything compiled both locally and on the server, VS/TFS did not add actually add the file to source control. It was not included on the "Pending Changes" at all. I had to manually go to the Source Control Explorer and explicitly click on the "Add items to folder" icon.

Stupid because I've been developing for 15 years in VS. I've run into this before, I just did not remember and somehow I missed it because everything still compiled because of the file being a regular reference, but the file that was added as Existing Item was not being copied because it did not exist on the source control server.

I hope this saves someone some time, since I lost 2 days of my life to this.

Send response to all clients except sender

From the @LearnRPG answer but with 1.0:

 // send to current request socket client
 socket.emit('message', "this is a test");

 // sending to all clients, include sender
 io.sockets.emit('message', "this is a test"); //still works
 //or
 io.emit('message', 'this is a test');

 // sending to all clients except sender
 socket.broadcast.emit('message', "this is a test");

 // sending to all clients in 'game' room(channel) except sender
 socket.broadcast.to('game').emit('message', 'nice game');

 // sending to all clients in 'game' room(channel), include sender
 // docs says "simply use to or in when broadcasting or emitting"
 io.in('game').emit('message', 'cool game');

 // sending to individual socketid, socketid is like a room
 socket.broadcast.to(socketid).emit('message', 'for your eyes only');

To answer @Crashalot comment, socketid comes from:

var io = require('socket.io')(server);
io.on('connection', function(socket) { console.log(socket.id); })

Link to add to Google calendar

I've also been successful with this URL structure:

Base URL:

https://calendar.google.com/calendar/r/eventedit?

And let's say this is my event details:

Title: Event Title
Description: Example of some description. See more at https://stackoverflow.com/questions/10488831/link-to-add-to-google-calendar
Location: 123 Some Place
Date: February 22, 2020
Start Time: 10:00am
End Time: 11:30am
Timezone: America/New York (GMT -5)

I'd convert my details into these parameters (URL encoded):

text=Event%20Title
details=Example%20of%20some%20description.%20See%20more%20at%20https%3A%2F%2Fstackoverflow.com%2Fquestions%2F10488831%2Flink-to-add-to-google-calendar
location=123%20Some%20Place%2C%20City
dates=20200222T100000/20200222T113000
ctz=America%2FNew_York

Example link:

https://calendar.google.com/calendar/r/eventedit?text=Event%20Title&details=Example%20of%20some%20description.%20See%20more%20at%20https%3A%2F%2Fstackoverflow.com%2Fquestions%2F10488831%2Flink-to-add-to-google-calendar&location=123%20Some%20Place%2C%20City&dates=20200222T100000/20200222T113000&ctz=America%2FNew_York

Please note that since I've specified a timezone with the "ctz" parameter, I used the local times for the start and end dates. Alternatively, you can use UTC dates and exclude the timezone parameter, like this:

dates=20200222T150000Z/20200222T163000Z

Example link:

https://calendar.google.com/calendar/r/eventedit?text=Event%20Title&details=Example%20of%20some%20description.%20See%20more%20at%20https%3A%2F%2Fstackoverflow.com%2Fquestions%2F10488831%2Flink-to-add-to-google-calendar&location=123%20Some%20Place%2C%20City&dates=20200222T150000Z/20200222T163000Z

python error: no module named pylab

The error means pylab is not part of the standard Python libraries. You will need to down-load it and install it. I think it's available Here They have installation instructions here

Total size of the contents of all the files in a directory

When a folder is created, many Linux filesystems allocate 4096 bytes to store some metadata about the directory itself. This space is increased by a multiple of 4096 bytes as the directory grows.

du command (with or without -b option) take in count this space, as you can see typing:

mkdir test && du -b test

you will have a result of 4096 bytes for an empty dir. So, if you put 2 files of 10000 bytes inside the dir, the total amount given by du -sb would be 24096 bytes.

If you read carefully the question, this is not what asked. The questioner asked:

the sum total of all the data in files and subdirectories I would get if I opened each file and counted the bytes

that in the example above should be 20000 bytes, not 24096.

So, the correct answer IMHO could be a blend of Nelson answer and hlovdal suggestion to handle filenames containing spaces:

find . -type f -print0 | xargs -0 stat --format=%s | awk '{s+=$1} END {print s}'

Rails: update_attribute vs update_attributes

update_attribute

This method update single attribute of object without invoking model based validation.

obj = Model.find_by_id(params[:id])
obj.update_attribute :language, “java”

update_attributes

This method update multiple attribute of single object and also pass model based validation.

attributes = {:name => “BalaChandar”, :age => 23}
obj = Model.find_by_id(params[:id])
obj.update_attributes(attributes)

Hope this answer will clear out when to use what method of active record.

make iframe height dynamic based on content inside- JQUERY/Javascript

All other answers are correct but what if the iframe has some dynamic content like a map that loads later and dynamically changes your iframe scroll height. This is how I achieved it.

var iFrameID = document.getElementById('idIframe');

intval =  setInterval(function(){
if(iFrameID.scrollHeight == iFrameID.contentWindow.document.body.scrollHeight){
     clearInterval(intval);
}else{
   iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
  }
},500)

I simply wrap the code inside setInterval which matches the iframe scroll height with iframe content scroll height then clear the interval.

JVM heap parameters

The JVM resizes the heap adaptively, meaning it will attempt to find the best heap size for your application. -Xms and -Xmx simply specifies the range in which the JVM can operate and resize the heap. If -Xms and -Xmx are the same value, then the JVM's heap size will stay constant at that value.

It's typically best to just set -Xmx and let the JVM find the best heap size, unless there's a specific reason why you need to give the JVM a big heap at JVM launch.

As far as when the JVM actually requests the memory from the OS, I believe it depends on the platform and implementation of the JVM. I imagine that it wouldn't request the memory until your app actually needs it. -Xmx and -Xms just reserves the memory.

Changing the current working directory in Java?

I have tried to invoke

String oldDir = System.setProperty("user.dir", currdir.getAbsolutePath());

It seems to work. But

File myFile = new File("localpath.ext"); InputStream openit = new FileInputStream(myFile);

throws a FileNotFoundException though

myFile.getAbsolutePath()

shows the correct path. I have read this. I think the problem is:

  • Java knows the current directory with the new setting.
  • But the file handling is done by the operation system. It does not know the new set current directory, unfortunately.

The solution may be:

File myFile = new File(System.getPropety("user.dir"), "localpath.ext");

It creates a file Object as absolute one with the current directory which is known by the JVM. But that code should be existing in a used class, it needs changing of reused codes.

~~~~JcHartmut

How to var_dump variables in twig templates?

Since Symfony >= 2.6, there is a nice VarDumper component, but it is not used by Twig's dump() function.

To overwrite it, we can create an extension:

In the following implementation, do not forget to replace namespaces.

Fuz/AppBundle/Resources/config/services.yml

parameters:
   # ...
   app.twig.debug_extension.class: Fuz\AppBundle\Twig\Extension\DebugExtension

services:
   # ...
   app.twig.debug_extension:
       class: %app.twig.debug_extension.class%
       arguments: []
       tags:
           - { name: twig.extension }

Fuz/AppBundle/Twig/Extension/DebugExtension.php

<?php

namespace Fuz\AppBundle\Twig\Extension;

class DebugExtension extends \Twig_Extension
{

    public function getFunctions()
    {
        return array (
              new \Twig_SimpleFunction('dump', array('Symfony\Component\VarDumper\VarDumper', 'dump')),
        );
    }

    public function getName()
    {
        return 'FuzAppBundle:Debug';
    }

}

How to run eclipse in clean mode? what happens if we do so?

  • click on short cut
  • right click -> properties
  • add -clean in target clause and then start.

it will take much time then normal start and it will fresh up all resources.

How to make promises work in IE11

If you want this type of code to run in IE11 (which does not support much of ES6 at all), then you need to get a 3rd party promise library (like Bluebird), include that library and change your coding to use ES5 coding structures (no arrow functions, no let, etc...) so you can live within the limits of what older browsers support.

Or, you can use a transpiler (like Babel) to convert your ES6 code to ES5 code that will work in older browsers.

Here's a version of your code written in ES5 syntax with the Bluebird promise library:

<script src="https://cdnjs.cloudflare.com/ajax/libs/bluebird/3.3.4/bluebird.min.js"></script>

<script>

'use strict';

var promise = new Promise(function(resolve) {
    setTimeout(function() {
        resolve("result");
    }, 1000);
});

promise.then(function(result) {
    alert("Fulfilled: " + result);
}, function(error) {
    alert("Rejected: " + error);
});

</script>

Resize UIImage and change the size of UIImageView

If you have the size of the image, why don't you set the frame.size of the image view to be of this size?

EDIT----

Ok, so seeing your comment I propose this:

UIImageView *imageView;
//so let's say you're image view size is set to the maximum size you want

CGFloat maxWidth = imageView.frame.size.width;
CGFloat maxHeight = imageView.frame.size.height;

CGFloat viewRatio = maxWidth / maxHeight;
CGFloat imageRatio = image.size.height / image.size.width;

if (imageRatio > viewRatio) {
    CGFloat imageViewHeight = round(maxWidth * imageRatio);
    imageView.frame = CGRectMake(0, ceil((self.bounds.size.height - imageViewHeight) / 2.f), maxWidth, imageViewHeight);
}
else if (imageRatio < viewRatio) {
    CGFloat imageViewWidth = roundf(maxHeight / imageRatio);
    imageView.frame = CGRectMake(ceil((maxWidth - imageViewWidth) / 2.f), 0, imageViewWidth, maxHeight);
} else {
    //your image view is already at the good size
}

This code will resize your image view to its image ratio, and also position the image view to the same centre as your "default" position.

PS: I hope you're setting imageView.layer.shouldRasterise = YES and imageView.layer.rasterizationScale = [UIScreen mainScreen].scale;

if you're using CALayer shadow effect ;) It will greatly improve the performance of your UI.

How to fetch data from local JSON file on react native?

maybe you could use AsyncStorage setItem and getItem...and store the data as string, then use the json parser for convert it again to json...

How to bind to a PasswordBox in MVVM

For anyone who is aware of the risks this implementation imposes, to have the password sync to your ViewModel simply add Mode=OneWayToSource.

XAML

<PasswordBox
    ff:PasswordHelper.Attach="True"
    ff:PasswordHelper.Password="{Binding Path=Password, Mode=OneWayToSource}" />

Add disabled attribute to input element using Javascript

Working code from my sources:

HTML WORLD

<select name="select_from" disabled>...</select>

JS WORLD

var from = jQuery('select[name=select_from]');

//add disabled
from.attr('disabled', 'disabled');



//remove it
from.removeAttr("disabled");

How to make clang compile to llvm IR

If you have multiple source files, you probably actually want to use link-time-optimization to output one bitcode file for the entire program. The other answers given will cause you to end up with a bitcode file for every source file.

Instead, you want to compile with link-time-optimization

clang -flto -c program1.c -o program1.o
clang -flto -c program2.c -o program2.o

and for the final linking step, add the argument -Wl,-plugin-opt=also-emit-llvm

clang -flto -Wl,-plugin-opt=also-emit-llvm program1.o program2.o -o program

This gives you both a compiled program and the bitcode corresponding to it (program.bc). You can then modify program.bc in any way you like, and recompile the modified program at any time by doing

clang program.bc -o program

although be aware that you need to include any necessary linker flags (for external libraries, etc) at this step again.

Note that you need to be using the gold linker for this to work. If you want to force clang to use a specific linker, create a symlink to that linker named "ld" in a special directory called "fakebin" somewhere on your computer, and add the option

-B/home/jeremy/fakebin

to any linking steps above.

How to stop an app on Heroku?

To DELETE your Heroku app

This is for those looking to DELETE an app on their Heroku account. Sometimes you end up here when trying to find out how to remove/delete an app.

WARNING: This is irreversible!

  • Go to your Heroku dashboard here
  • Select the app you want to delete.
  • Scroll down to the bottom of the settings page for that app.
  • Press the red Delete app... button.

Get Category name from Post ID

function wp_get_post_categories( $post_id = 0, $args = array() )
{
   $post_id = (int) $post_id;
   $defaults = array('fields' => 'ids');
   $args = wp_parse_args( $args, $defaults );
   $cats = wp_get_object_terms($post_id, 'category', $args);

   return $cats;
}

Here is the second argument of function wp_get_post_categories() which you can pass the attributes of receiving data.

$category_detail = get_the_category( '4',array( 'fields' => 'names' ) ); //$post->ID
foreach( $category_detail as $cd )
{
   echo $cd->name;
}

Vector of structs initialization

You cannot access elements of an empty vector by subscript.
Always check that the vector is not empty & the index is valid while using the [] operator on std::vector.
[] does not add elements if none exists, but it causes an Undefined Behavior if the index is invalid.

You should create a temporary object of your structure, fill it up and then add it to the vector, using vector::push_back()

subject subObj;
subObj.name = s1;
sub.push_back(subObj);

List all environment variables from the command line

Just do:

SET

You can also do SET prefix to see all variables with names starting with prefix.

For example, if you want to read only derbydb from the environment variables, do the following:

set derby 

...and you will get the following:

DERBY_HOME=c:\Users\amro-a\Desktop\db-derby-10.10.1.1-bin\db-derby-10.10.1.1-bin

Displaying the build date

A different, PCL-friendly approach would be to use an MSBuild inline task to substitute the build time into a string that is returned by a property on the app. We are using this approach successfully in an app that has Xamarin.Forms, Xamarin.Android, and Xamarin.iOS projects.

EDIT:

Simplified by moving all of the logic into the SetBuildDate.targets file, and using Regex instead of simple string replace so that the file can be modified by each build without a "reset".

The MSBuild inline task definition (saved in a SetBuildDate.targets file local to the Xamarin.Forms project for this example):

<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion="12.0">

  <UsingTask TaskName="SetBuildDate" TaskFactory="CodeTaskFactory" 
    AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v12.0.dll">
    <ParameterGroup>
      <FilePath ParameterType="System.String" Required="true" />
    </ParameterGroup>
    <Task>
      <Code Type="Fragment" Language="cs"><![CDATA[

        DateTime now = DateTime.UtcNow;
        string buildDate = now.ToString("F");
        string replacement = string.Format("BuildDate => \"{0}\"", buildDate);
        string pattern = @"BuildDate => ""([^""]*)""";
        string content = File.ReadAllText(FilePath);
        System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(pattern);
        content = rgx.Replace(content, replacement);
        File.WriteAllText(FilePath, content);
        File.SetLastWriteTimeUtc(FilePath, now);

   ]]></Code>
    </Task>
  </UsingTask>

</Project>

Invoking the above inline task in the Xamarin.Forms csproj file in target BeforeBuild:

  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
       Other similar extension points exist, see Microsoft.Common.targets.  -->
  <Import Project="SetBuildDate.targets" />
  <Target Name="BeforeBuild">
    <SetBuildDate FilePath="$(MSBuildProjectDirectory)\BuildMetadata.cs" />
  </Target>

The FilePath property is set to a BuildMetadata.cs file in the Xamarin.Forms project that contains a simple class with a string property BuildDate, into which the build time will be substituted:

public class BuildMetadata
{
    public static string BuildDate => "This can be any arbitrary string";
}

Add this file BuildMetadata.cs to project. It will be modified by every build, but in a manner that allows repeated builds (repeated replacements), so you may include or omit it in source control as desired.

How can I get the nth character of a string?

Array notation and pointer arithmetic can be used interchangeably in C/C++ (this is not true for ALL the cases but by the time you get there, you will find the cases yourself). So although str is a pointer, you can use it as if it were an array like so:

char char_E = str[1];
char char_L1 = str[2];
char char_O = str[4];

...and so on. What you could also do is "add" 1 to the value of the pointer to a character str which will then point to the second character in the string. Then you can simply do:

str = str + 1; // makes it point to 'E' now
char myChar =  *str;

I hope this helps.

How do you beta test an iphone app?

Creating ad-hoc distribution profiles

The instructions that Apple provides are here, but here is how I created a general provisioning profile that will work with multiple apps, and added a beta tester.

My setup:

  • Xcode 3.2.1
  • iPhone SDK 3.1.3

Before you get started, make sure that..

  • You can run the app on your own iPhone through Xcode.

Step A: Add devices to the Provisioning Portal

  1. Send an email to each beta tester with the following message:

    To get my app on onto your iPhone I need some information about your phone. Guess what, there is an app for that!

    Click on the below link and install and then run the app.

    http://itunes.apple.com/app/ad-hoc-helper/id285691333?mt=8

    This app will create an email. Please send it to me.

  2. Collect all the UDIDs from your testers.

  3. Go to the Provisioning Portal.

  4. Go to the section Devices.

  5. Click on the button Add Devices and add the devices previously collected.

Step B: Create a new provisioning profile

  1. Start the Mac OS utility program Keychain Access.

  2. In its main menu, select Keychain Access / Certificate Assistant / Request a Certificate From a Certificate Authority...

  3. The dialog that pops up should aready have your email and name it it.

  4. Select the radio button Saved to disk and Continue.

  5. Save the file to disk.

  6. Go back to the Provisioning Portal.

  7. Go to the section Certificates.

  8. Go to the tab Distribution.

  9. Click the button Request Certificate.

  10. Upload the file you created with Keychain Access: CertificateSigningRequest.certSigningRequest.

  11. Click the button Aprove.

  12. Refresh your browser until the status reads Issued.

  13. Click the Download button and save the file distribution_identify.cer.

  14. Doubleclick the file to add it to the Keychain.

  15. Backup the certificate by selecting its private key and the File / Export Items....

  16. Go back to the Provisioning Portal again.

  17. Go to the section Provisioning.

  18. Go to the tab Distribution.

  19. Click the button New Profile.

  20. Select the radio button Ad hoc.

  21. Enter a profile name, I named mine Evertsson Common Ad Hoc.

  22. Select the app id. I have a common app id to use for multiple apps: Evertsson Common.

  23. Select the devices, in my case my own and my tester's.

  24. Submit.

  25. Refresh the browser until the status field reads Active.

  26. Click the button Download and save the file to disk.

  27. Doubleclick the file to add it to Xcode.

Step C: Build the app for distribution

  1. Open your project in Xcode.

  2. Open the Project Info pane: In Groups & Files select the topmost item and press Cmd+I.

  3. Go to the tab Configuration.

  4. Select the configuration Release.

  5. Click the button Duplicate and name it Distribution.

  6. Close the Project Info pane.

  7. Open the Target Info pane: In Groups & Files expand Targets, select your target and press Cmd+I.

  8. Go to the tab Build.

  9. Select the Configuration named Distribution.

  10. Find the section Code Signing.

  11. Set the value of Code Signing Identity / Any iPhone OS Device to iPhone Distribution.

  12. Close the Target Info pane.

  13. In the main window select the Active Configuration to Distribution.

  14. Create a new file from the file template Code Signing / Entitlements.

  15. Name it Entitlements.plist.

  16. In this file, uncheck the checkbox get-task-allow.

  17. Bring up the Target Info pane, and find the section Code Signing again.

  18. After Code Signing Entitlements enter the file name Entitlements.plist.

  19. Save, clean, and build the project.

  20. In Groups & Files find the folder MyApp / Products and expand it.

  21. Right click the app and select Reveal in Finder.

  22. Zip the .app file and the .mobileprovision file and send the archive to your tester.

    Here is my app. To install it onto your phone:

    1. Unzip the archive file.

    2. Open iTunes.

    3. Drag both files into iTunes and drop them on the Library group.

    4. Sync your phone to install the app.

Done! Phew. This worked for me. So far I've only added one tester.

Remove file from SVN repository without deleting local copy

When you want to remove one xxx.java file from SVN:

  1. Go to workspace path where the file is located.
  2. Delete that file from the folder (xxx.java)
  3. Right click and commit, then a window will open.
  4. Select the file you deleted (xxx.java) from the folder, and again right click and delete.. it will remove the file from SVN.

View a file in a different Git branch without changing branches

This should work:

git show branch:file

Where branch can be any ref (branch, tag, HEAD, ...) and file is the full path of the file. To export it you could use

git show branch:file > exported_file

You should also look at VonC's answers to some related questions:

UPDATE 2015-01-19:

Nowadays you can use relative paths with git show a1b35:./file.txt.

Most simple code to populate JTable from ResultSet

Class Row will handle one row from your database.

Complete implementation of UpdateTask responsible for filling up UI.

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JTable;
import javax.swing.SwingWorker;

public class JTableUpdateTask extends SwingWorker<JTable, Row> {

    JTable      table       = null;

    ResultSet   resultSet   = null;

    public JTableUpdateTask(JTable table, ResultSet rs) {
        this.table = table;
        this.resultSet = rs;
    }

    @Override
    protected JTable doInBackground() throws Exception {
        List<Row> rows = new ArrayList<Row>();
        Object[] values = new Object[6];
        while (resultSet.next()) {
            values = new Object[6];
            values[0] = resultSet.getString("id");
            values[1] = resultSet.getString("student_name");
            values[2] = resultSet.getString("street");
            values[3] = resultSet.getString("city");
            values[4] = resultSet.getString("state");
            values[5] = resultSet.getString("zipcode");
            Row row = new Row(values);
            rows.add(row);
        }
        process(rows); 
        return this.table;
    }

    protected void process(List<Row> chunks) {
        ResultSetTableModel tableModel = (this.table.getModel() instanceof ResultSetTableModel ? (ResultSetTableModel) this.table.getModel() : null);
        if (tableModel == null) {
            try {
                tableModel = new ResultSetTableModel(this.resultSet.getMetaData(), chunks);
            } catch (SQLException e) {
                e.printStackTrace();
            }
            this.table.setModel(tableModel);
        } else {
            tableModel.getRows().addAll(chunks);
        }
        tableModel.fireTableDataChanged();
    }
}

Table Model:

import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.swing.table.AbstractTableModel;

/**
 * Simple wrapper around Object[] representing a row from the ResultSet.
 */
class Row {
    private final Object[]  values;

    public Row(Object[] values) {
        this.values = values;
    }

    public int getSize() {
        return values.length;
    }

    public Object getValue(int i) {
        return values[i];
    }
}

// TableModel implementation that will be populated by SwingWorker.
public class ResultSetTableModel extends AbstractTableModel {
    private final ResultSetMetaData rsmd;

    private List<Row>               rows;

    public ResultSetTableModel(ResultSetMetaData rsmd, List<Row> rows) {
        this.rsmd = rsmd;
        if (rows != null) {
            this.rows = rows;
        } else {
            this.rows = new ArrayList<Row>();
        }

    }

    public int getRowCount() {
        return rows.size();
    }

    public int getColumnCount() {
        try {
            return rsmd.getColumnCount();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public Object getValue(int row, int column) {
        return rows.get(row).getValue(column);
    }

    public String getColumnName(int col) {
        try {
            return rsmd.getColumnName(col + 1);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return "";
    }

    public Class<?> getColumnClass(int col) {
        String className = "";
        try {
            className = rsmd.getColumnClassName(col);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return className.getClass();
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        if(rowIndex > rows.size()){
            return null;
        }
        return rows.get(rowIndex).getValue(columnIndex);
    }

    public List<Row> getRows() {
        return this.rows;
    }

    public void setRows(List<Row> rows) {
        this.rows = rows;
    }
}

Main Application which builds UI and does the database connection

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTable;

public class MainApp {
    static Connection conn = null;
    static void init(final ResultSet rs) {
        JFrame frame = new JFrame();
        frame.setLayout(new BorderLayout());
        final JTable table = new JTable();
        table.setPreferredSize(new Dimension(300,300));
        table.setMinimumSize(new Dimension(300,300));
        table.setMaximumSize(new Dimension(300,300));
        frame.add(table, BorderLayout.CENTER);
        JButton button = new JButton("Start Loading");
        button.setPreferredSize(new Dimension(30,30));
        button.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JTableUpdateTask jTableUpdateTask = new JTableUpdateTask(table, rs);
                jTableUpdateTask.execute();

            }
        });
        frame.add(button, BorderLayout.SOUTH);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        String url = "jdbc:mysql://localhost:3306/test";
        String driver = "com.mysql.jdbc.Driver";
        String userName = "root";
        String password = "root";
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url, userName, password);
            PreparedStatement pstmt = conn.prepareStatement("Select id, student_name, street, city, state,zipcode from student");
            ResultSet rs = pstmt.executeQuery();
            init(rs);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How do I get the current date and current time only respectively in Django?

import datetime

datetime.date.today()  # Returns 2018-01-15

datetime.datetime.now() # Returns 2018-01-15 09:00

How to fix Error: listen EADDRINUSE while using nodejs?

EADDRINUSE means that the port(which we try to listen in node application) is already being used. In order to overcome, we need to identify which process is running with that port.

For example if we are trying to listen our node application in 3000 port. We need to check whether that port is already is being used by any other process.

step1:

$sudo netstat -plunt |grep :3000

That the above command gives below result.

tcp6       0      0 :::3000                 :::*                    LISTEN      25315/node

step2:

Now you got process ID(25315), Kill that process.

kill -9 25315

step3:

npm run start

Note: This solution for linux users.

Why use HttpClient for Synchronous Connection

public static class AsyncHelper  
{
    private static readonly TaskFactory _taskFactory = new
        TaskFactory(CancellationToken.None,
                    TaskCreationOptions.None,
                    TaskContinuationOptions.None,
                    TaskScheduler.Default);

    public static TResult RunSync<TResult>(Func<Task<TResult>> func)
        => _taskFactory
            .StartNew(func)
            .Unwrap()
            .GetAwaiter()
            .GetResult();

    public static void RunSync(Func<Task> func)
        => _taskFactory
            .StartNew(func)
            .Unwrap()
            .GetAwaiter()
            .GetResult();
}

Then

AsyncHelper.RunSync(() => DoAsyncStuff());

if you use that class pass your async method as parameter you can call the async methods from sync methods in a safe way.

it's explained here : https://cpratt.co/async-tips-tricks/

SQL Server format decimal places with commas

Thankfully(?), in SQL Server 2012+, you can now use FORMAT() to achieve this:

FORMAT(@s,'#,0.0000')


In prior versions, at the risk of looking real ugly

[Query]:

declare @s decimal(18,10);
set @s = 1234.1234567;
select replace(convert(varchar,cast(floor(@s) as money),1),'.00',
    '.'+right(cast(@s * 10000 +10000.5 as int),4))

In the first part, we use MONEY->VARCHAR to produce the commas, but FLOOR() is used to ensure the decimals go to .00. This is easily identifiable and replaced with the 4 digits after the decimal place using a mixture of shifting (*10000) and CAST as INT (truncation) to derive the digits.

[Results]:

|   COLUMN_0 |
--------------
| 1,234.1235 |

But unless you have to deliver business reports using SQL Server Management Studio or SQLCMD, this is NEVER the correct solution, even if it can be done. Any front-end or reporting environment has proper functions to handle display formatting.

JavaScript - Hide a Div at startup (load)

I've had the same problem.

Use CSS to hide is not the best solution, because sometimes you want users without JS can see the div.. The cleanest solution is to hide the div with JQuery. But the div is visible about 0.5 seconde, which is problematic if the div is on the top of the page.

In these cases, I use an intermediate solution, without JQuery. This one works and is immediate :

<script>document.write('<style>.js_hidden { display: none; }</style>');</script>

<div class="js_hidden">This div will be hidden for JS users, and visible for non JS users.</div>

Of course, you can still add all the effects you want on the div, JQuery toggle() for example. And you will get the best behaviour possible (imho) :

  • for non JS users, the div is visible directly
  • for JS users, the div is hidden and has toggle effect.

How to set width of a div in percent in JavaScript?

jQuery way -

$("#id").width('30%');

List of Python format characters

Here you go, Python documentation on old string formatting. tutorial -> 7.1.1. Old String Formatting -> "More information can be found in the [link] section".

Note that you should start using the new string formatting when possible.

How can I tell when a MySQL table was last updated?

OS level analysis:

Find where the DB is stored on disk:

grep datadir /etc/my.cnf
datadir=/var/lib/mysql

Check for most recent modifications

cd /var/lib/mysql/{db_name}
ls -lrt

Should work on all database types.

How to import cv2 in python3?

Your screenshot shows you doing a pip install from the python terminal which is wrong. Do that outside the python terminal. Also the package I believe you want is:

pip install opencv-python

Since you're running on Windows, I might look at the official install manual: https://breakthrough.github.io/Installing-OpenCV

opencv2 is ONLY compatible with Python3 if you do so by compiling the source code. See the section under opencv supported python versions: https://pypi.org/project/opencv-python

How to escape a JSON string containing newline characters using JavaScript?

It's better to use JSON.parse(yourUnescapedJson);

How to copy and paste worksheets between Excel workbooks?

Not tested, but something like:

Dim sourceSheet As Worksheet
Dim destSheet As Worksheet

'' copy from the source
Workbooks.Open Filename:="c:\source.xls"
Set sourceSheet = Worksheets("source")
sourceSheet.Activate
sourceSheet.Cells.Select
Selection.Copy

'' paste to the destination
Workbooks.Open Filename:="c:\destination.xls"
Set destSheet = Worksheets("dest")
destSheet.Activate
destSheet.Cells.Select
destSheet.Paste

'' save & close
ActiveWorkbook.Save
ActiveWorkbook.Close

Note that this assumes the destination sheet already exists. It's pretty easy to create one if it doesn't.

How to see JavaDoc in IntelliJ IDEA?

Alternatively you can position your cursor on the item and show JavaDoc using

CTRL+Q

which is the default shortcut.

Edit: As Methical mentioned on Mac the shortcut is

CTRL+j (^+j not ?+j)

Setting Custom ActionBar Title from Fragment

There are many ways as as outlined above. You can also do this in onNavigationDrawerSelected()in your DrawerActivity

public void setTitle(final String title){
    ((TextView)findViewById(R.id.toolbar_title)).setText(title);
}

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    fragment = null;
    String title = null;
    switch(position){

    case 0:
        fragment = new HomeFragment();
        title = "Home";
        break;
    case 1:
        fragment = new ProfileFragment();
        title = ("Find Work");
        break;
    ...
    }
    if (fragment != null){

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager
        .beginTransaction()
        .replace(R.id.container,
                fragment).commit();

        //The key is this line
        if (title != null && findViewById(R.id.toolbar_title)!= null ) setTitle(title);
    }
}

What killed my process and why?

We have had recurring problems under Linux at a customer site (Red Hat, I think), with OOMKiller (out-of-memory killer) killing both our principle application (i.e. the reason the server exists) and it's data base processes.

In each case OOMKiller simply decided that the processes were using to much resources... the machine wasn't even about to fail for lack of resources. Neither the application nor it's database has problems with memory leaks (or any other resource leak).

I am not a Linux expert, but I rather gathered it's algorithm for deciding when to kill something and what to kill is complex. Also, I was told (I can't speak as to the accuracy of this) that OOMKiller is baked into the Kernel and you can't simply not run it.

How to replace captured groups only?

A little improvement to Matthew's answer could be a lookahead instead of the last capturing group:

.replace(/(\w+)(\d+)(?=\w+)/, "$1!NEW_ID!");

Or you could split on the decimal and join with your new id like this:

.split(/\d+/).join("!NEW_ID!");

Example/Benchmark here: https://codepen.io/jogai/full/oyNXBX

load external URL into modal jquery ui dialog

I did it this way, where 'struts2ActionName' is the struts2 action in my case. You may use any url instead.

var urlAdditionCert =${pageContext.request.contextPath}/struts2ActionName";
$("#dialogId").load( urlAdditionCert).dialog({
    modal: true,
    height: $("#body").height(),
    width: $("#body").width()*.8
});

AngularJS Folder Structure

enter image description here

Sort By Type

On the left we have the app organized by type. Not too bad for smaller apps, but even here you can start to see it gets more difficult to find what you are looking for. When I want to find a specific view and its controller, they are in different folders. It can be good to start here if you are not sure how else to organize the code as it is quite easy to shift to the technique on the right: structure by feature.

Sort By Feature (preferred)

On the right the project is organized by feature. All of the layout views and controllers go in the layout folder, the admin content goes in the admin folder, and the services that are used by all of the areas go in the services folder. The idea here is that when you are looking for the code that makes a feature work, it is located in one place. Services are a bit different as they “service” many features. I like this once my app starts to take shape as it becomes a lot easier to manage for me.

A well written blog post: http://www.johnpapa.net/angular-growth-structure/

Example App: https://github.com/angular-app/angular-app

Set the maximum character length of a UITextField in Swift

Simply just check with the number of characters in the string

  1. Add a delegate to view controller ans asign delegate
    class YorsClassName : UITextFieldDelegate {

    }
  1. check the number of chars allowed for textfield
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
    if textField.text?.count == 1 {
        return false
    }
    return true
}

Note: Here I checked for only char allowed in textField

GROUP_CONCAT comma separator - MySQL

Or, if you are doing a split - join:

GROUP_CONCAT(split(thing, " "), '----') AS thing_name,

You may want to inclue WITHIN RECORD, like this:

GROUP_CONCAT(split(thing, " "), '----') WITHIN RECORD AS thing_name,

from BigQuery API page

How to disable a button when an input is empty?

Using constants allows to combine multiple fields for verification:

_x000D_
_x000D_
class LoginFrm extends React.Component {_x000D_
  constructor() {_x000D_
    super();_x000D_
    this.state = {_x000D_
      email: '',_x000D_
      password: '',_x000D_
    };_x000D_
  }_x000D_
  _x000D_
  handleEmailChange = (evt) => {_x000D_
    this.setState({ email: evt.target.value });_x000D_
  }_x000D_
  _x000D_
  handlePasswordChange = (evt) => {_x000D_
    this.setState({ password: evt.target.value });_x000D_
  }_x000D_
  _x000D_
  handleSubmit = () => {_x000D_
    const { email, password } = this.state;_x000D_
    alert(`Welcome ${email} password: ${password}`);_x000D_
  }_x000D_
  _x000D_
  render() {_x000D_
    const { email, password } = this.state;_x000D_
    const enabled =_x000D_
          email.length > 0 &&_x000D_
          password.length > 0;_x000D_
    return (_x000D_
      <form onSubmit={this.handleSubmit}>_x000D_
        <input_x000D_
          type="text"_x000D_
          placeholder="Email"_x000D_
          value={this.state.email}_x000D_
          onChange={this.handleEmailChange}_x000D_
        />_x000D_
        _x000D_
        <input_x000D_
          type="password"_x000D_
          placeholder="Password"_x000D_
          value={this.state.password}_x000D_
          onChange={this.handlePasswordChange}_x000D_
        />_x000D_
        <button disabled={!enabled}>Login</button>_x000D_
      </form>_x000D_
    )_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<LoginFrm />, document.body);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<body>_x000D_
_x000D_
_x000D_
</body>
_x000D_
_x000D_
_x000D_

What's the opposite of 'make install', i.e. how do you uninstall a library in Linux?

If you have a manifest file which lists all the files that were installed with make install you can run this command which I have from another answer:

cat install_manifest.txt | xargs echo rm | sh

If you have sudo make install you will need to add a sudo to your uninstall:

cat install_manifest.txt | xargs echo sudo rm | sh

[] and {} vs list() and dict(), which is better?

In my opinion [] and {} are the most pythonic and readable ways to create empty lists/dicts.

Be wary of set()'s though, for example:

this_set = {5}
some_other_set = {}

Can be confusing. The first creates a set with one element, the second creates an empty dict and not a set.

Disable double-tap "zoom" option in browser on touch devices

I just wanted to answer my question properly as some people do not read the comments below an answer. So here it is:

(function($) {
  $.fn.nodoubletapzoom = function() {
      $(this).bind('touchstart', function preventZoom(e) {
        var t2 = e.timeStamp
          , t1 = $(this).data('lastTouch') || t2
          , dt = t2 - t1
          , fingers = e.originalEvent.touches.length;
        $(this).data('lastTouch', t2);
        if (!dt || dt > 500 || fingers > 1) return; // not double-tap

        e.preventDefault(); // double tap - prevent the zoom
        // also synthesize click events we just swallowed up
        $(this).trigger('click').trigger('click');
      });
  };
})(jQuery);

I did not write this, i just modified it. I found the iOS-only version here: https://gist.github.com/2047491 (thanks Kablam)

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

  • Open the start menu
  • Type windows+R or open "Run
  • Execute the following command.

chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

In Python 3.6 the fastest way is still the WouterOvermeire one. Kikohs' proposal is slower than the other two options.

import timeit

setup = '''
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)
'''

timeit.Timer('dict(zip(df.A,df.B))', setup=setup).repeat(7,500)
timeit.Timer('pd.Series(df.A.values,index=df.B).to_dict()', setup=setup).repeat(7,500)
timeit.Timer('df.set_index("A").to_dict()["B"]', setup=setup).repeat(7,500)

Results:

1.1214002349999777 s  # WouterOvermeire
1.1922008498571748 s  # Jeff
1.7034366211428602 s  # Kikohs

Why is Android Studio reporting "URI is not registered"?

For me this was because I was using a debug and release build variant. I added the new folders src/debug/res/layout/some_layout.xml file manually, and it didn't recognize the URI. I switched the build variant to release, and then back to debug. This caused Android Studio to reload something, and the error went away.

EDIT: Also check that you have the correct filename. I had this issue again by adding a debug AndroidManifest.xml, but mistakenly named it AndroidManifest.xml.xml.

ValueError when checking if variable is None or numpy.array

To stick to == without consideration of the other type, the following is also possible.
type(a) == type(None)

Access denied for root user in MySQL command-line

Are you logging into MySQL as root? You have to explicitly grant privileges to your "regular" MySQL user account while logged in as MySQL root.

First set up a root account for your MySQL database.

In the terminal type:

mysqladmin -u root password 'password'

To log into MySQL, use this:

mysql -u root -p

To set the privileges manually start the server with the skip-grant-tables option, open mysql client and manually update the mysql.user table and/or the mysql.db tables. This can be a tedious task though so if what you need is an account with all privs I would do the following.

Start the server with the skip-grant-tables option

Start mysql client (without a username/password)

Issue the command

flush privileges;

which forces the grant tables to be loaded.

Create a new account with the GRANT command something like this (but replacing username and password with whatever you want to use.

GRANT ALL on *.* to 'username'@'localhost' identified by 'password';

Restart the server in normal mode (without skip-grant-tables) and log in with your newly created account.

Refer this MySQL docs.

select certain columns of a data table

DataView dv = new DataView(Your DataTable);

DataTable dt = dv.ToTable(true, "Your Specific Column Name");

The dt contains only selected column values.

How to deal with ModalDialog using selenium webdriver?

Assuming the expectation is just going to be two windows popping up (one of the parent and one for the popup) then just wait for two windows to come up, find the other window handle and switch to it.

WebElement link = // element that will showModalDialog()

// Click on the link, but don't wait for the document to finish
final JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript(
    "var el=arguments[0]; setTimeout(function() { el.click(); }, 100);",
  link);

// wait for there to be two windows and choose the one that is 
// not the original window
final String parentWindowHandle = driver.getWindowHandle();
new WebDriverWait(driver, 60, 1000)
    .until(new Function<WebDriver, Boolean>() {
    @Override
    public Boolean apply(final WebDriver driver) {
        final String[] windowHandles =
            driver.getWindowHandles().toArray(new String[0]);
        if (windowHandles.length != 2) {
            return false;
        }
        if (windowHandles[0].equals(parentWindowHandle)) {
            driver.switchTo().window(windowHandles[1]);
        } else {
            driver.switchTo().window(windowHandles[0]);
        }
        return true;
    }
});

Download File Using jQuery

Yes, you would have to change the window.location.href to the url of the file you would want to download.

window.location.href = 'http://www.com/path/to/file';

How to make a new line or tab in <string> XML (eclipse/android)?

Add '\t' for tab

<string name="tab">\u0009</string>

How can I use an ES6 import in Node.js?

You can also use npm package called esm which allows you to use ES6 modules in Node.js. It needs no configuration. With esm you will be able to use export/import in your JavaScript files.

Run the following command on your terminal

yarn add esm

or

npm install esm

After that, you need to require this package when starting your server with node. For example if your node server runs index.js file, you would use the command

node -r esm index.js

You can also add it in your package.json file like this

{
  "name": "My-app",
  "version": "1.0.0",
  "description": "Some Hack",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node -r esm index.js"
  },

}

Then run this command from the terminal to start your node server

npm start

Check this link for more details.

When do items in HTML5 local storage expire?

I would suggest to store timestamp in the object you store in the localStorage

var object = {value: "value", timestamp: new Date().getTime()}
localStorage.setItem("key", JSON.stringify(object));

You can parse the object, get the timestamp and compare with the current Date, and if necessary, update the value of the object.

var object = JSON.parse(localStorage.getItem("key")),
    dateString = object.timestamp,
    now = new Date().getTime().toString();

compareTime(dateString, now); //to implement

Define a global variable in a JavaScript function

If you read the comments there's a nice discussion around this particular naming convention.

It seems that since my answer has been posted the naming convention has gotten more formal. People who teach, write books, etc. speak about var declaration, and function declaration.

Here is the additional Wikipedia post that supports my point: Declarations and definitions ...and to answer the main question. Declare variable before your function. This will work and it will comply to the good practice of declaring your variables at the top of the scope :)

How to get the next auto-increment id in mysql

You have to connect to MySQL and select a database before you can do this

$table_name = "myTable"; 
$query = mysql_query("SHOW TABLE STATUS WHERE name='$table_name'"); 
$row = mysql_fetch_array($query); 
$next_inc_value = $row["AUTO_INCREMENT"];  

Best way to style a TextBox in CSS

You could target all text boxes with input[type=text] and then explicitly define the class for the textboxes who need it.

You can code like below :

_x000D_
_x000D_
input[type=text] {_x000D_
  padding: 0;_x000D_
  height: 30px;_x000D_
  position: relative;_x000D_
  left: 0;_x000D_
  outline: none;_x000D_
  border: 1px solid #cdcdcd;_x000D_
  border-color: rgba(0, 0, 0, .15);_x000D_
  background-color: white;_x000D_
  font-size: 16px;_x000D_
}_x000D_
_x000D_
.advancedSearchTextbox {_x000D_
  width: 526px;_x000D_
  margin-right: -4px;_x000D_
}
_x000D_
<input type="text" class="advancedSearchTextBox" />
_x000D_
_x000D_
_x000D_

PHP: Calling another class' method

File 1

class ClassA {

    public $name = 'A';

    public function getName(){
        return $this->name;
    }

}

File 2

include("file1.php");
class ClassB {

    public $name = 'B';

    public function getName(){
        return $this->name;
    }

    public function callA(){
        $a = new ClassA();
        return $a->getName();
    }

    public static function callAStatic(){
        $a = new ClassA();
        return $a->getName();
    }

}

$b = new ClassB();
echo $b->callA();
echo $b->getName();
echo ClassB::callAStatic();

How to upload a file in Django?

Demo

See the github repo, works with Django 3

A minimal Django file upload example

1. Create a django project

Run startproject::

$ django-admin.py startproject sample

now a folder(sample) is created.

2. create an app

Create an app::

$ cd sample
$ python manage.py startapp uploader

Now a folder(uploader) with these files are created::

uploader/
  __init__.py
  admin.py
  app.py
  models.py
  tests.py
  views.py
  migrations/
    __init__.py

3. Update settings.py

On sample/settings.py add 'uploader' to INSTALLED_APPS and add MEDIA_ROOT and MEDIA_URL, ie::

INSTALLED_APPS = [
    'uploader',
    ...<other apps>...      
]

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

4. Update urls.py

in sample/urls.py add::

...<other imports>...
from django.conf import settings
from django.conf.urls.static import static
from uploader import views as uploader_views

urlpatterns = [
    ...<other url patterns>...
    path('', uploader_views.UploadView.as_view(), name='fileupload'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

5. Update models.py

update uploader/models.py::

from django.db import models
class Upload(models.Model):
    upload_file = models.FileField()    
    upload_date = models.DateTimeField(auto_now_add =True)

6. Update views.py

update uploader/views.py::

from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .models import Upload
class UploadView(CreateView):
    model = Upload
    fields = ['upload_file', ]
    success_url = reverse_lazy('fileupload')
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['documents'] = Upload.objects.all()
        return context

7. create templates

Create a folder sample/uploader/templates/uploader

Create a file upload_form.html ie sample/uploader/templates/uploader/upload_form.html::

<div style="padding:40px;margin:40px;border:1px solid #ccc">
    <h1>Django File Upload</h1>
    <form method="post" enctype="multipart/form-data">
      {% csrf_token %}
      {{ form.as_p }}
      <button type="submit">Submit</button>
    </form><hr>
    <ul>
    {% for document in documents %}
        <li>
            <a href="{{ document.upload_file.url }}">{{ document.upload_file.name }}</a>
            <small>({{ document.upload_file.size|filesizeformat }}) - {{document.upload_date}}</small>
        </li>
    {% endfor %}
    </ul>
</div>

8. Syncronize database

Syncronize database and runserver::

$ python manage.py makemigrations
$ python manage.py migrate
$ python manage.py runserver

visit http://localhost:8000/

How to create a .gitignore file

You can go to https://www.toptal.com/developers/gitignore

Select the IDE, operating systems or programming language. It will automatically generate for you. enter image description here

Regex to match string containing two names in any order

Vim has a branch operator \& that is useful when searching for a line containing a set of words, in any order. Moreover, extending the set of required words is trivial.

For example,

/.*jack\&.*james

will match a line containing jack and james, in any order.

See this answer for more information on usage. I am not aware of any other regex flavor that implements branching; the operator is not even documented on the Regular Expression wikipedia entry.

Get JSON Data from URL Using Android?

Easy way to get JSON especially for Android SDK 23:

public class MainActivity extends AppCompatActivity {

Button btnHit;
TextView txtJson;
ProgressDialog pd;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnHit = (Button) findViewById(R.id.btnHit);
    txtJson = (TextView) findViewById(R.id.tvJsonItem);

    btnHit.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            new JsonTask().execute("Url address here");
        }
    });


}


private class JsonTask extends AsyncTask<String, String, String> {

    protected void onPreExecute() {
        super.onPreExecute();

        pd = new ProgressDialog(MainActivity.this);
        pd.setMessage("Please wait");
        pd.setCancelable(false);
        pd.show();
    }

    protected String doInBackground(String... params) {


        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            URL url = new URL(params[0]);
            connection = (HttpURLConnection) url.openConnection();
            connection.connect();


            InputStream stream = connection.getInputStream();

            reader = new BufferedReader(new InputStreamReader(stream));

            StringBuffer buffer = new StringBuffer();
            String line = "";

            while ((line = reader.readLine()) != null) {
                buffer.append(line+"\n");
                Log.d("Response: ", "> " + line);   //here u ll get whole response...... :-) 

            }

            return buffer.toString();


        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (pd.isShowing()){
            pd.dismiss();
        }
        txtJson.setText(result);
    }
}
}

How do I encrypt and decrypt a string in python?

I had troubles compiling all the most commonly mentioned cryptography libraries on my Windows 7 system and for Python 3.5.

This is the solution that finally worked for me.

from cryptography.fernet import Fernet
key = Fernet.generate_key() #this is your "password"
cipher_suite = Fernet(key)
encoded_text = cipher_suite.encrypt(b"Hello stackoverflow!")
decoded_text = cipher_suite.decrypt(encoded_text)

Difference between SelectedItem, SelectedValue and SelectedValuePath

inspired by this question I have written a blog along with the code snippet here. Below are some of the excerpts from the blog

SelectedItem – Selected Item helps to bind the actual value from the DataSource which will be displayed. This is of type object and we can bind any type derived from object type with this property. Since we will be using the MVVM binding for our combo boxes in that case this is the property which we can use to notify VM that item has been selected.

SelectedValue and SelectedValuePath – These are the two most confusing and misinterpreted properties for combobox. But these properties come to rescue when we want to bind our combobox with the value from already created object. Please check my last scenario in the following list to get a brief idea about the properties.

cor shows only NA or 1 for correlations - Why?

The NA can actually be due to 2 reasons. One is that there is a NA in your data. Another one is due to there being one of the values being constant. This results in standard deviation being equal to zero and hence the cor function returns NA.

Handling optional parameters in javascript

Can you override the function? Will this not work:

function doSomething(id){}
function doSomething(id,parameters){}
function doSomething(id,parameters,callback){}

Format a datetime into a string with milliseconds

Probably like this :

import datetime
now = datetime.datetime.now()
now.strftime('%Y/%m/%d %H:%M:%S.%f')[:-3]  
# [:-3] => Removing the 3 last characters as %f is for microsecs.

How to deal with the URISyntaxException

If you're using RestangularV2 to post to a spring controller in java you can get this exception if you use RestangularV2.one() instead of RestangularV2.all()

How can I tell if a Java integer is null?

ints are value types; they can never be null. Instead, if the parsing failed, parseInt will throw a NumberFormatException that you need to catch.

Clear variable in python

The del keyword would do.

>>> a=1
>>> a
1
>>> del a
>>> a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

But in this case I vote for self.left = None

ZIP file content type for HTTP request

.zip    application/zip, application/octet-stream

Vagrant error : Failed to mount folders in Linux guest

I arrived at this page whilst looking for the same error message. For me the cause was different: I had ran a yum update on the system that installed a new kernel. The guest additions where out of date so it couldn't load them.

I rebuilt them with

sudo /etc/init.d/vboxadd setup 

And a vagrant reload later my guest was up and running again.

I'm just adding it here in case someone else gets here the same way I did.

Edit (Per KCD's comment):
It is possible that you get an error saying:

The headers for the current running kernel were not found

This can be resolved by installing kernel-devel (yum install kernel-devel)

How to map and remove nil values in Ruby

One more way to accomplish it will be as shown below. Here, we use Enumerable#each_with_object to collect values, and make use of Object#tap to get rid of temporary variable that is otherwise needed for nil check on result of process_x method.

items.each_with_object([]) {|x, obj| (process x).tap {|r| obj << r unless r.nil?}}

Complete example for illustration:

items = [1,2,3,4,5]
def process x
    rand(10) > 5 ? nil : x
end

items.each_with_object([]) {|x, obj| (process x).tap {|r| obj << r unless r.nil?}}

Alternate approach:

By looking at the method you are calling process_x url, it is not clear what is the purpose of input x in that method. If I assume that you are going to process the value of x by passing it some url and determine which of the xs really get processed into valid non-nil results - then, may be Enumerabble.group_by is a better option than Enumerable#map.

h = items.group_by {|x| (process x).nil? ? "Bad" : "Good"}
#=> {"Bad"=>[1, 2], "Good"=>[3, 4, 5]}

h["Good"]
#=> [3,4,5]

Echo a blank (empty) line to the console from a Windows batch file

Note: Though my original answer attracted several upvotes, I decided that I could do much better. You can find my original (simplistic and misguided) answer in the edit history.

If Microsoft had the intent of providing a means of outputting a blank line from cmd.exe, Microsoft surely would have documented such a simple operation. It is this omission that motivated me to ask this question.

So, because a means for outputting a blank line from cmd.exe is not documented, arguably one should consider any suggestion for how to accomplish this to be a hack. That means that there is no known method for outputting a blank line from cmd.exe that is guaranteed to work (or work efficiently) in all situations.

With that in mind, here is a discussion of methods that have been recommended for outputting a blank line from cmd.exe. All recommendations are based on variations of the echo command.


echo.

While this will work in many if not most situations, it should be avoided because it is slower than its alternatives and actually can fail (see here, here, and here). Specifically, cmd.exe first searches for a file named echo and tries to start it. If a file named echo happens to exist in the current working directory, echo. will fail with:

'echo.' is not recognized as an internal or external command,
operable program or batch file.

echo:
echo\

At the end of this answer, the author argues that these commands can be slow, for instance if they are executed from a network drive location. A specific reason for the potential slowness is not given. But one can infer that it may have something to do with accessing the file system. (Perhaps because : and \ have special meaning in a Windows file system path?)

However, some may consider these to be safe options since : and \ cannot appear in a file name. For that or another reason, echo: is recommended by SS64.com here.


echo(
echo+
echo,
echo/
echo;
echo=
echo[
echo]

This lengthy discussion includes what I believe to be all of these. Several of these options are recommended in this SO answer as well. Within the cited discussion, this post ends with what appears to be a recommendation for echo( and echo:.

My question at the top of this page does not specify a version of Windows. My experimentation on Windows 10 indicates that all of these produce a blank line, regardless of whether files named echo, echo+, echo,, ..., echo] exist in the current working directory. (Note that my question predates the release of Windows 10. So I concede the possibility that older versions of Windows may behave differently.)

In this answer, @jeb asserts that echo( always works. To me, @jeb's answer implies that other options are less reliable but does not provide any detail as to why that might be. Note that @jeb contributed much valuable content to other references I have cited in this answer.


Conclusion: Do not use echo.. Of the many other options I encountered in the sources I have cited, the support for these two appears most authoritative:

echo(
echo:

But I have not found any strong evidence that the use of either of these will always be trouble-free.


Example Usage:

@echo off
echo Here is the first line.
echo(
echo There is a blank line above this line.

Expected output:

Here is the first line.

There is a blank line above this line.

Parse String to Date with Different Format in Java

Use the SimpleDateFormat class:

private Date parseDate(String date, String format) throws ParseException
{
    SimpleDateFormat formatter = new SimpleDateFormat(format);
    return formatter.parse(date);
}

Usage:

Date date = parseDate("19/05/2009", "dd/MM/yyyy");

For efficiency, you would want to store your formatters in a hashmap. The hashmap is a static member of your util class.

private static Map<String, SimpleDateFormat> hashFormatters = new HashMap<String, SimpleDateFormat>();

public static Date parseDate(String date, String format) throws ParseException
{
    SimpleDateFormat formatter = hashFormatters.get(format);

    if (formatter == null)
    {
        formatter = new SimpleDateFormat(format);
        hashFormatters.put(format, formatter);
    }

    return formatter.parse(date);
}

In a unix shell, how to get yesterday's date into a variable?

If your HP-UX installation has Tcl installed, you might find it's date arithmetic very readable (unfortunately the Tcl shell does not have a nice "-e" option like perl):

dt=$(echo 'puts [clock format [clock scan yesterday] -format "%a %d/%m/%Y"]' | tclsh)
echo "yesterday was $dt"

This will handle all the daylight savings bother.

How to edit the legend entry of a chart in Excel?

There are 3 ways to do this:

1. Define the Series names directly

Right-click on the Chart and click Select Data then edit the series names directly as shown below.

enter image description here

You can either specify the values directly e.g. Series 1 or specify a range e.g. =A2

enter image description here

2. Create a chart defining upfront the series and axis labels

Simply select your data range (in similar format as I specified) and create a simple bar chart. The labels should be defined automatically. enter image description here

3. Define the legend (series names) using VBA

Similarly you can define the series names dynamically using VBA. A simple example below:

ActiveChart.ChartArea.Select
ActiveChart.FullSeriesCollection(1).Name = "=""Hello"""

This will redefine the first series name. Just change the index from (1) to e.g. (2) and so on to change the following series names. What does the VBA above do? It sets the series name to Hello as "=""Hello""" translates to ="Hello" (" have to be escaped by a preceding ").

Maven Out of Memory Build Failure

While building the project on Unix/Linux platform, set Maven options syntax as below. Notice that single qoutation signs, not double qoutation.

export MAVEN_OPTS='-Xmx512m -XX:MaxPermSize=128m'

How to use protractor to check if an element is visible?

This answer will be robust enough to work for elements that aren't on the page, therefore failing gracefully (not throwing an exception) if the selector failed to find the element.

const nameSelector = '[data-automation="name-input"]';
const nameInputIsDisplayed = () => {
    return $$(nameSelector).count()
        .then(count => count !== 0)
}
it('should be displayed', () => {
    nameInputIsDisplayed().then(isDisplayed => {
        expect(isDisplayed).toBeTruthy()
    })
})

What does 'x packages are looking for funding' mean when running `npm install`?

npm fund [<pkg>]

This command retrieves information on how to fund the dependencies of a given project. If no package name is provided, it will list all dependencies that are looking for funding in a tree-structure in which are listed the type of funding and the url to visit.
The message can be disabled using: npm install --no-fund

Can I simultaneously declare and assign a variable in VBA?

In some cases the whole need for declaring a variable can be avoided by using With statement.

For example,

    Dim fd As Office.FileDialog
    Set fd = Application.FileDialog(msoFileDialogSaveAs)
    If fd.Show Then
        'use fd.SelectedItems(1)
    End If

this can be rewritten as

    With Application.FileDialog(msoFileDialogSaveAs)
      If .Show Then
        'use .SelectedItems(1)
      End If
    End With

Effective method to hide email from spam bots

I like ofaurax's answer best but I would modify to this for a little more hidden email:

onclick="p1='admin'; p2='domain.com'; this.href='mailto:' + p1 + '& #x40;' + p2"

ObservableCollection Doesn't support AddRange method, so I get notified for each item added, besides what about INotifyCollectionChanging?

Yes, adding your own Custom Observable Collection would be fair enough. Don't forget to raise appropriate events regardless whether it is used by UI for the moment or not ;) You will have to raise property change notification for "Item[]" property (required by WPF side and bound controls) as well as NotifyCollectionChangedEventArgs with a set of items added (your range). I've did such things (as well as sorting support and some other stuff) and had no problems with both Presentation and Code Behind layers.

PyCharm shows unresolved references error for valid code

I have a project where one file in src/ imports another file in the same directory. To get PyCharm to recognize I had to to go to File > Settings > Project > Project Structure > select src folder and click "Mark as: Sources"

From https://www.jetbrains.com/help/pycharm/configuring-folders-within-a-content-root.html

Source roots contain the actual source files and resources. PyCharm uses the source roots as the starting point for resolving imports

Is there a way to disable initial sorting for jquery DataTables?

Well I found the answer set "aaSorting" to an empty array:

$(document).ready( function() {
    $('#example').dataTable({
        /* Disable initial sort */
        "aaSorting": []
    });
})

For newer versions of Datatables (>= 1.10) use order option:

$(document).ready( function() {
    $('#example').dataTable({
        /* No ordering applied by DataTables during initialisation */
        "order": []
    });
})

Amazon S3 exception: "The specified key does not exist"

In my case the error was appearing because I had uploaded the whole folder, containing the website files, into the container.

I solved it by moving all the files outside the folder, right into the container.

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

This error may be caused by several reasons.

Here is the list of requirements for the Google IAB testing.

Prerequisites:

  1. AndroidManifest must include "com.android.vending.BILLING" permission.
  2. APK is built in release mode.
  3. APK is signed with the release certificate(s). (Important: with "App Signing by Google Play" it only works if you download directly from GooglePlayStore!)
  4. APK is uploaded to alpha/beta distribution channel (previously - as a draft) to the developer console at least once. (takes some time ~2h-24h).
  5. IAB products are published and their status set to active.
  6. Test account(s) is added in developer console.

Testing requirements:

  1. Test APK has the same versionCode as the one uploaded to developer console.
  2. Test APK is signed with the same certificate(s) as the one uploaded to dev.console.
  3. Test account (not developer) - is the main account on the device. (Main account might be not necessary - according to @MinosL comment)
  4. Test account is opted-in as a tester and it's linked to a valid payment method. (@Kyone)

P.S: Debugging with release certificate: https://stackoverflow.com/a/15754187/1321401 (Thnx @dipp for the link)

P.P.S: Wanted to make this list for a long time already.

Thnx @zlgdev, @Kyone, @MinosL for updates

Split String into an array of String

String[] result = "hi i'm paul".split("\\s+"); to split across one or more cases.

Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str) method that splits string using white space as delimiter. It also has other useful utility methods

How to change the date format of a DateTimePicker in vb.net

You need to set the Format of the DateTimePicker to Custom and then assign the CustomFormat.

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    DateTimePicker1.Format = DateTimePickerFormat.Custom
    DateTimePicker1.CustomFormat = "dd/MM/yyyy"
End Sub

How to quit android application programmatically

It's not a good decision, cause it's against the Android's application processing principles. Android doesn't kill any process unless it's absolutely inevitable. This helps apps start faster, cause they're always kept in memory. So you need a very special reason to kill your application's process.

javascript regex - look behind alternative?

If you can look ahead but back, you could reverse the string first and then do a lookahead. Some more work will need to be done, of course.

Is there a C++ decompiler?

You can use IDA Pro by Hex-Rays. You will usually not get good C++ out of a binary unless you compiled in debugging information. Prepare to spend a lot of manual labor reversing the code.

If you didn't strip the binaries there is some hope as IDA Pro can produce C-alike code for you to work with. Usually it is very rough though, at least when I used it a couple of years ago.

How do I set proxy for chrome in python webdriver?

from selenium import webdriver
from selenium.webdriver.common.proxy import *

myProxy = "86.111.144.194:3128"
proxy = Proxy({
    'proxyType': ProxyType.MANUAL,
    'httpProxy': myProxy,
    'ftpProxy': myProxy,
    'sslProxy': myProxy,
    'noProxy':''})

driver = webdriver.Firefox(proxy=proxy)
driver.set_page_load_timeout(30)
driver.get('http://whatismyip.com')

Removing the first 3 characters from a string

Just use substring: "apple".substring(3); will return le

Converting int to string in C

You can make your own itoa, with this function:

void my_utoa(int dataIn, char* bffr, int radix){
int temp_dataIn;
temp_dataIn = dataIn;
int stringLen=1;

while ((int)temp_dataIn/radix != 0){
    temp_dataIn = (int)temp_dataIn/radix;
    stringLen++;
}
//printf("stringLen = %d\n", stringLen);
temp_dataIn = dataIn;
do{
    *(bffr+stringLen-1) = (temp_dataIn%radix)+'0';
    temp_dataIn = (int) temp_dataIn / radix;
}while(stringLen--);}

and this is example:

char buffer[33];
int main(){
  my_utoa(54321, buffer, 10);
  printf(buffer);
  printf("\n");

  my_utoa(13579, buffer, 10);
  printf(buffer);
  printf("\n");
}

Truncate (not round) decimal places in SQL Server

I know this is pretty late but I don't see it as an answer and have been using this trick for years.

Simply subtract .005 from your value and use Round(@num,2).

Your example:

declare @num decimal(9,5) = 123.456

select round(@num-.005,2)

returns 123.45

It will automatically adjust the rounding to the correct value you are looking for.

By the way, are you recreating the program from the movie Office Space?

How do I execute code AFTER a form has loaded?

I sometimes use (in Load)

this.BeginInvoke((MethodInvoker) delegate {
  // some code
});

or

this.BeginInvoke((MethodInvoker) this.SomeMethod);

(change "this" to your form variable if you are handling the event on an instance other than "this").

This pushes the invoke onto the windows-forms loop, so it gets processed when the form is processing the message queue.

[updated on request]

The Control.Invoke/Control.BeginInvoke methods are intended for use with threading, and are a mechanism to push work onto the UI thread. Normally this is used by worker threads etc. Control.Invoke does a synchronous call, where-as Control.BeginInvoke does an asynchronous call.

Normally, these would be used as:

SomeCodeOrEventHandlerOnAWorkerThread()
{
  // this code running on a worker thread...
  string newText = ExpensiveMethod(); // perhaps a DB/web call

  // now ask the UI thread to update itself
  this.Invoke((MethodInvoker) delegate {
      // this code runs on the UI thread!
      this.Text = newText;
  });
}

It does this by pushing a message onto the windows message queue; the UI thread (at some point) de-queues the message, processes the delegate, and signals the worker that it completed... so far so good ;-p

OK; so what happens if we use Control.Invoke / Control.BeginInvoke on the UI thread? It copes... if you call Control.Invoke, it is sensible enough to know that blocking on the message queue would cause an immediate deadlock - so if you are already on the UI thread it simply runs the code immediately... so that doesn't help us...

But Control.BeginInvoke works differently: it always pushes work onto the queue, even it we are already on the UI thread. This makes a really simply way of saying "in a moment", but without the inconvenience of timers etc (which would still have to do the same thing anyway!).

How to initialize HashSet values by construction?

(ugly) Double Brace Initialization without side effects:

Set<String> a = new HashSet<>(new HashSet<String>() {{
    add("1");
    add("2");
}})

But in some cases, if we mentioned that is a good smell to make final collections unmutable, it could be really useful:

final Set<String> a = Collections.unmodifiableSet(new HashSet<String>(){{
    add("1");
    add("2");
}})

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

Android getting value from selected radiobutton

mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
        RadioButton radioButton = (RadioButton)group.findViewById(checkedId);
    }
});

Finding the index of an item in a list

One thing that is really helpful in learning Python is to use the interactive help function:

>>> help(["foo", "bar", "baz"])
Help on list object:

class list(object)
 ...

 |
 |  index(...)
 |      L.index(value, [start, [stop]]) -> integer -- return first index of value
 |

which will often lead you to the method you are looking for.

How to undo a SQL Server UPDATE query?

If you already have a full backup from your database, fortunately, you have an option in SQL Management Studio. In this case, you can use the following steps:

  1. Right click on database -> Tasks -> Restore -> Database.

  2. In General tab, click on Timeline -> select Specific date and time option.

  3. Move the timeline slider to before update command time -> click OK.

  4. In the destination database name, type a new name.

  5. In the Files tab, check in Reallocate all files to folder and then select a new path to save your recovered database.

  6. In the options tab, check in Overwrite ... and remove Take tail-log... check option.

  7. Finally, click on OK and wait until the recovery process is over.

I have used this method myself in an operational database and it was very useful.

How to use this boolean in an if statement?

additionally you can just write

if(stop)
{
        sb.append("y");
        getWhoozitYs();
}

What does `set -x` do?

set -x enables a mode of the shell where all executed commands are printed to the terminal. In your case it's clearly used for debugging, which is a typical use case for set -x: printing every command as it is executed may help you to visualize the control flow of the script if it is not functioning as expected.

set +x disables it.

Java error: Only a type can be imported. XYZ resolves to a package

This typically happens when mixing (in the same jsp page) static jsp import:

<%@include file="...

with dynamic jsp import:

<jsp:include page="...

and your type has been already imported by the "static imported" jsp. When the same type needs to be used (and then imported) by the "dynamically imported" jsp -> this generate the Exception: "Only a type can be imported..."

How can I see all the "special" characters permissible in a varchar or char field in SQL Server?

i think that special characters are # and @ only... query will list both.

DECLARE  @str VARCHAR(50) 
SET @str = '[azAB09ram#reddy@wer45' + CHAR(5) + 'a~b$' 
SELECT DISTINCT poschar 
FROM   MASTER..spt_values S 
       CROSS APPLY (SELECT SUBSTRING(@str,NUMBER,1) AS poschar) t 
WHERE  NUMBER > 0 
       AND NUMBER <= LEN(@str) 
       AND NOT (ASCII(t.poschar) BETWEEN 65 AND 90 
                 OR ASCII(t.poschar) BETWEEN 97 AND 122 
                 OR ASCII(t.poschar) BETWEEN 48 AND 57) 

In SQL, is UPDATE always faster than DELETE+INSERT?

In your case, I believe the update will be faster.

Remember indexes!

You have defined a primary key, it will likely automatically become a clustered index (at least SQL Server does so). A cluster index means the records are physically laid on the disk according to the index. DELETE operation itself won't cause much trouble, even after one record goes away, the index stays correct. But when you INSERT a new record, the DB engine will have to put this record in the correct location which under circumstances will cause some "reshuffling" of the old records to "make place" for a new one. There where it will slow down the operation.

An index (especially clustered) works best if the values are ever increasing, so the new records just get appended to the tail. Maybe you can add an extra INT IDENTITY column to become a clustered index, this will simplify insert operations.

Override and reset CSS style: auto or none don't work

I ended up using Javascript to perfect everything.

My JS fiddle: https://jsfiddle.net/QEpJH/612/

HTML:

<div class="container">
    <img src="http://placekitten.com/240/300">
</div>

<h3 style="clear: both;">Full Size Image - For Reference</h3>
<img src="http://placekitten.com/240/300">

CSS:

.container {
    background-color:#000;
    width:100px;
    height:200px;

    display:flex;
    justify-content:center;
    align-items:center;
    overflow:hidden;

}

JS:

$(".container").each(function(){
    var divH = $(this).height()
    var divW = $(this).width()
    var imgH = $(this).children("img").height();
    var imgW = $(this).children("img").width();

    if ( (imgW/imgH) < (divW/divH)) { 
        $(this).addClass("1");
        var newW = $(this).width();
        var newH = (newW/imgW) * imgH;
        $(this).children("img").width(newW); 
        $(this).children("img").height(newH); 
    } else {
        $(this).addClass("2");
        var newH = $(this).height();
        var newW = (newH/imgH) * imgW;
        $(this).children("img").width(newW); 
        $(this).children("img").height(newH); 
    }
})

jQuery returning "parsererror" for ajax request

Make sure that you remove any debug code or anything else that might be outputting unintended information. Somewhat obvious, but easy to forgot in the moment.

What is RSS and VSZ in Linux memory management

RSS is Resident Set Size (physically resident memory - this is currently occupying space in the machine's physical memory), and VSZ is Virtual Memory Size (address space allocated - this has addresses allocated in the process's memory map, but there isn't necessarily any actual memory behind it all right now).

Note that in these days of commonplace virtual machines, physical memory from the machine's view point may not really be actual physical memory.

how to add values to an array of objects dynamically in javascript?

You have to instantiate the object first. The simplest way is:

var lab =["1","2","3"];
var val = [42,55,51,22];
var data = [];
for(var i=0; i<4; i++)  {
    data.push({label: lab[i], value: val[i]});
}

Or an other, less concise way, but closer to your original code:

for(var i=0; i<4; i++)  {
   data[i] = {};              // creates a new object
   data[i].label = lab[i];
   data[i].value = val[i];    
}

array() will not create a new array (unless you defined that function). Either Array() or new Array() or just [].

I recommend to read the MDN JavaScript Guide.

Using getline() with file input in C++

ifstream inFile;
string name, temp;
int age;

inFile.open("file.txt");

getline(inFile, name, ' '); // use ' ' as separator, default is '\n' (newline). Now name is "John".
getline(inFile, temp, ' '); // Now temp is "Smith"
name.append(1,' ');
name += temp;
inFile >> age; 

cout << name << endl;
cout << age << endl;  

inFile.close();    

How to change the font color of a disabled TextBox?

If you want to display text that cannot be edited or selected you can simply use a label

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

How to group pandas DataFrame entries by date in a non-unique column

This should work:

data.groupby(lambda x: data['date'][x].year)

Find file in directory from command line

find /root/directory/to/search -name 'filename.*'
# Directory is optional (defaults to cwd)

Standard UNIX globbing is supported. See man find for more information.

If you're using Vim, you can use:

:e **/filename.cpp

Or :tabn or any Vim command which accepts a filename.

MongoDB - Update objects in a document's array (nested updating)

We can use $set operator to update the nested array inside object filed update the value

db.getCollection('geolocations').update( 
   {
       "_id" : ObjectId("5bd3013ac714ea4959f80115"), 
       "geolocation.country" : "United States of America"
   }, 
   { $set: 
       {
           "geolocation.$.country" : "USA"
       } 
    }, 
   false,
   true
);

Include in SELECT a column that isn't actually in the database

You may want to use:

SELECT Name, 'Unpaid' AS Status FROM table;

The SELECT clause syntax, as defined in MSDN: SELECT Clause (Transact-SQL), is as follows:

SELECT [ ALL | DISTINCT ]
[ TOP ( expression ) [ PERCENT ] [ WITH TIES ] ] 
<select_list> 

Where the expression can be a constant, function, any combination of column names, constants, and functions connected by an operator or operators, or a subquery.

What is the use of ObservableCollection in .net?

One of the biggest uses is that you can bind UI components to one, and they'll respond appropriately if the collection's contents change. For example, if you bind a ListView's ItemsSource to one, the ListView's contents will automatically update if you modify the collection.

EDIT: Here's some sample code from MSDN: http://msdn.microsoft.com/en-us/library/ms748365.aspx

In C#, hooking the ListBox to the collection could be as easy as

listBox.ItemsSource = NameListData;

though if you haven't hooked the list up as a static resource and defined NameItemTemplate you may want to override PersonName's ToString(). For example:

public override ToString()
{
    return string.Format("{0} {1}", this.FirstName, this.LastName);
}

Catching exceptions from Guzzle

Old question, but Guzzle adds the response within the exception object. So a simple try-catch on GuzzleHttp\Exception\ClientException and then using getResponse on that exception to see what 400-level error and continuing from there.

Min/Max-value validators in asp.net mvc

I don't think min/max validations attribute exist. I would use something like

[Range(1, Int32.MaxValue)]

for minimum value 1 and

[Range(Int32.MinValue, 10)]

for maximum value 10

"detached entity passed to persist error" with JPA/EJB code

If you set id in your database to be primary key and autoincrement, then this line of code is wrong:

user.setId(1);

Try with this:

public static void main(String[] args){
         UserBean user = new UserBean();
         user.setUserName("name1");
         user.setPassword("passwd1");
         em.persist(user);
  }

How to unpack and pack pkg file?

In addition to what @abarnert said, I today had to find out that the default cpio utility on Mountain Lion uses a different archive format per default (not sure which), even with the man page stating it would use the old cpio/odc format. So, if anyone stumbles upon the cpio read error: bad file format message while trying to install his/her manipulated packages, be sure to include the format in the re-pack step:

find ./Foo.app | cpio -o --format odc | gzip -c > Payload

Direct method from SQL command text to DataSet

public static string textDataSource = "Data Source=localhost;Initial Catalog=TEST_C;User ID=sa;Password=P@ssw0rd";

public static DataSet LoaderDataSet(string StrSql)      
{
    SqlConnection cnn;            
    SqlDataAdapter dad;
    DataSet dts = new DataSet();
    cnn = new SqlConnection(textDataSource);
    dad = new SqlDataAdapter(StrSql, cnn);
    try
    {
        cnn.Open();
        dad.Fill(dts);
        cnn.Close();

        return dts;
    }
    catch (Exception)
    {

        return dts;
    }
    finally
    {
        dad.Dispose();
        dts = null;
        cnn = null;
    }
}

Must issue a STARTTLS command first

smtp port and socketFactory has to be change

    String to = "[email protected]";
    String subject = "subject"
    String msg ="email text...."
    final String from ="[email protected]"
    final  String password ="senderPassword"


    Properties props = new Properties();  
    props.setProperty("mail.transport.protocol", "smtp");     
    props.setProperty("mail.host", "smtp.gmail.com");  
    props.put("mail.smtp.auth", "true");  
    props.put("mail.smtp.port", "465");  
    props.put("mail.debug", "true");  
    props.put("mail.smtp.socketFactory.port", "465");  
    props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");  
    props.put("mail.smtp.socketFactory.fallback", "false");  
    Session session = Session.getDefaultInstance(props,  
    new javax.mail.Authenticator() {
       protected PasswordAuthentication getPasswordAuthentication() {  
       return new PasswordAuthentication(from,password);  
   }  
   });  

   //session.setDebug(true);  
   Transport transport = session.getTransport();  
   InternetAddress addressFrom = new InternetAddress(from);  

   MimeMessage message = new MimeMessage(session);  
   message.setSender(addressFrom);  
   message.setSubject(subject);  
   message.setContent(msg, "text/plain");  
   message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));  

   transport.connect();  
   Transport.send(message);  
   transport.close();
   }  

hope it will work for you..

How to reset index in a pandas dataframe?

Another solutions are assign RangeIndex or range:

df.index = pd.RangeIndex(len(df.index))

df.index = range(len(df.index))

It is faster:

df = pd.DataFrame({'a':[8,7], 'c':[2,4]}, index=[7,8])
df = pd.concat([df]*10000)
print (df.head())

In [298]: %timeit df1 = df.reset_index(drop=True)
The slowest run took 7.26 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 3: 105 µs per loop

In [299]: %timeit df.index = pd.RangeIndex(len(df.index))
The slowest run took 15.05 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 7.84 µs per loop

In [300]: %timeit df.index = range(len(df.index))
The slowest run took 7.10 times longer than the fastest. This could mean that an intermediate result is being cached.
100000 loops, best of 3: 14.2 µs per loop

How to replace specific values in a oracle database column?

In Oracle, there is the concept of schema name, so try using this

update schemname.tablename t
set t.columnname = replace(t.columnname, t.oldvalue, t.newvalue);

Remove tracking branches no longer on remote

Drawing heavily from a number of other answers here, I've ended up with the following (git 2.13 and above only, I believe), which should work on any UNIX-like shell:

git for-each-ref --shell --format='ref=%(if:equals=[gone])%(upstream:track)%(then)%(refname)%(end)' refs/heads | while read entry; do eval "$entry"; [ ! -z "$ref" ] && git update-ref -d "$ref" && echo "deleted $ref"; done

This notably uses for-each-ref instead of branch (as branch is a "porcelain" command designed for human-readable output, not machine-processing) and uses its --shell argument to get properly escaped output (this allows us to not worry about any character in the ref name).

LINQ order by null column where order is ascending and nulls should be last

Below is extension method to check for null if you want to sort on child property of a keySelector.

public static IOrderedEnumerable<T> NullableOrderBy<T>(this IEnumerable<T> list, Func<T, object> parentKeySelector, Func<T, object> childKeySelector)
{
    return list.OrderBy(v => parentKeySelector(v) != null ? 0 : 1).ThenBy(childKeySelector);
}

And simple use it like:

var sortedList = list.NullableOrderBy(x => x.someObject, y => y.someObject?.someProperty);

Android 8: Cleartext HTTP traffic not permitted

 cleartext support is disabled by default.Android in 9 and above

 Try This one I hope It will work fine

1 Step:->  add inside android build gradle (Module:App)
            useLibrary 'org.apache.http.legacy'

  android {
               compileSdkVersion 28
              useLibrary 'org.apache.http.legacy'

          }

Then 2 Step:-> manifest add inside manifest application tag

<application
    android:networkSecurityConfig="@xml/network_security_config">//add drawable goto Step 4

   // Step --->3  add to top this line  
     <uses-library
        android:name="org.apache.http.legacy"
        android:required="false" />

</application>

//Step 4-->> Create Drawable>>Xml file>>name as>> network_security_config.xml

   <?xml version="1.0" encoding="utf-8"?>
   <network-security-config>
      <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
           <certificates src="system" />
        </trust-anchors>
      </base-config>
    </network-security-config>

Understanding Fragment's setRetainInstance(boolean)

setRetainInstance() - Deprecated

As Fragments Version 1.3.0-alpha01

The setRetainInstance() method on Fragments has been deprecated. With the introduction of ViewModels, developers have a specific API for retaining state that can be associated with Activities, Fragments, and Navigation graphs. This allows developers to use a normal, not retained Fragment and keep the specific state they want retained separate, avoiding a common source of leaks while maintaining the useful properties of a single creation and destruction of the retained state (namely, the constructor of the ViewModel and the onCleared() callback it receives).

CSS transition between left -> right and top -> bottom positions

In more modern browsers (including IE 10+) you can now use calc():

.moveto {
  top: 0px;
  left: calc(100% - 50px);
}

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

Check out this infographic: http://www.paintcodeapp.com/news/iphone-6-screens-demystified

It explains the differences between old iPhones, iPhone 6 and iPhone 6 Plus. You can see comparison of screen sizes in points, rendered pixels and physical pixels. You will also find answer to your question there:

iPhone 6 Plus - with Retina display HD. Scaling factor is 3 and the image is afterwards downscaled from rendered 2208 × 1242 pixels to 1920 × 1080 pixels.

The downscaling ratio is 1920 / 2208 = 1080 / 1242 = 20 / 23. That means every 23 pixels from the original render have to be mapped to 20 physical pixels. In other words the image is scaled down to approximately 87% of its original size.

Update:

There is an updated version of infographic mentioned above. It contains more detailed info about screen resolution differences and it covers all iPhone models so far, including 4 inch devices.

http://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions

How to check type of object in Python?

What type() means:

I think your question is a bit more general than I originally thought. type() with one argument returns the type or class of the object. So if you have a = 'abc' and use type(a) this returns str because the variable a is a string. If b = 10, type(b) returns int.

See also python documentation on type().


For comparisons:

If you want a comparison you could use: if type(v) == h5py.h5r.Reference (to check if it is a h5py.h5r.Reference instance).

But it is recommended that one uses if isinstance(v, h5py.h5r.Reference) but then also subclasses will evaluate to True.

If you want to print the class use print v.__class__.__name__.

More generally: You can compare if two instances have the same class by using type(v) is type(other_v) or isinstance(v, other_v.__class__).

Navigation drawer: How do I set the selected item at startup?

When using BottomNavigationView the other answers such as navigationView.getMenu().getItem(0).setChecked(true); and navigationView.setCheckedItem(id); won't work calling setSelectedItemId works:

    BottomNavigationView bottomNavigationView = findViewById(R.id.bottom_navigation_view);

    bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
        @Override
        public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
            // TODO: 10-Aug-19 your code here 
        }
    });

    bottomNavigationView.setSelectedItemId(R.id.myitem);

How to update-alternatives to Python 3 without breaking apt?

replace

[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python2.7 2

[bash:~] $ sudo update-alternatives --install /usr/bin/python python \
/usr/bin/python3.5 3

with

[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python2.7 2

[bash:~] $ sudo update-alternatives --install /usr/local/bin/python python \
/usr/bin/python3.5 3

e.g. installing into /usr/local/bin instead of /usr/bin.

and ensure the /usr/local/bin is before /usr/bin in PATH.

i.e.

[bash:~] $ echo $PATH
/usr/local/bin:/usr/bin:/bin

Ensure this always is the case by adding

export PATH=/usr/local/bin:$PATH

to the end of your ~/.bashrc file. Prefixing the PATH environment variable with custom bin folder such as /usr/local/bin or /opt/<some install>/bin is generally recommended to ensure that customizations are found before the default system ones.

How to connect to a remote MySQL database with Java?

Just supply the IP / hostname of the remote machine in your database connection string, instead of localhost. For example:

jdbc:mysql://192.168.15.25:3306/yourdatabase

Make sure there is no firewall blocking the access to port 3306

Also, make sure the user you are connecting with is allowed to connect from this particular hostname. For development environments it is safe to do this by 'username'@'%'. Check the user creation manual and the GRANT manual.

Specifying Style and Weight for Google Fonts

font-family:'Open Sans' , sans-serif;

For light: font-weight : 100; Or font-weight : lighter;

For normal: font-weight : 500; Or font-weight : normal;

For bold: font-weight : 700; Or font-weight : bold;

For more bolder: font-weight : 900; Or font-weight : bolder;

Associative arrays in Shell scripts

Bash4 supports this natively. Do not use grep or eval, they are the ugliest of hacks.

For a verbose, detailed answer with example code see: https://stackoverflow.com/questions/3467959

What Java ORM do you prefer, and why?

I had a really good experience with Avaje Ebean when I was writing a medium sized JavaSE application.

It uses standard JPA annotations to define entities, but exposes a much simpler API (No EntityManager or any of that attached/detached entities crap). It also lets you easily use SQL queries or event plain JDBC calls when necessary.

It also has a very nice fluid and type-safe API for queries. You can write things like:

List<Person> boys = Ebean.find(Person.class)
                                  .where()
                                       .eq("gender", "M")
                                       .le("age", 18)
                                  .orderBy("firstName")
                                  .findList();

How can I open a Shell inside a Vim Window?

Not absolutely what you are asking for, but you may be interested by my plugin vim-notebook which allows the user to keep a background process alive and to make it evaluate part of the current document (and to write the output in the document). It is intended to be used on notebook-style documents containing pieces of code to be evaluated.

how to log in to mysql and query the database from linux terminal

1.- How do I get mysql prompt in linux terminal?

mysql -u root -p

At the Enter password: prompt, well, enter root's password :)

You can find further reference by typing mysql --help or at the online manual.

2. How I stop the mysql server from linux terminal?

It depends. Red Hat based distros have the service command:

service mysqld stop

Other distros require to call the init script directly:

/etc/init.d/mysqld stop

3. How I start the mysql server from linux terminal?

Same as #2, but with start.

4. How do I get mysql prompt in linux terminal?

Same as #1.

5. How do I login to mysql server from linux terminal?

Same as #1.

6. How do I solve following error?

Same as #1.

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

I knew the file name but wanted the directory as well.

find $PWD | fgrep filename

worked perfectly in Mac OS 10.12.1

Javascript replace all "%20" with a space

If you need to remove white spaces at the end then here is a solution: https://www.geeksforgeeks.org/urlify-given-string-replace-spaces/

_x000D_
_x000D_
const stringQ1 = (string)=>{_x000D_
  //remove white space at the end _x000D_
  const arrString = string.split("")_x000D_
  for(let i = arrString.length -1 ; i>=0 ; i--){_x000D_
    let char = arrString[i];_x000D_
    _x000D_
    if(char.indexOf(" ") >=0){_x000D_
     arrString.splice(i,1)_x000D_
    }else{_x000D_
      break;_x000D_
    }_x000D_
  }_x000D_
_x000D_
  let start =0;_x000D_
  let end = arrString.length -1;_x000D_
  _x000D_
_x000D_
  //add %20_x000D_
  while(start < end){_x000D_
    if(arrString[start].indexOf(' ') >=0){_x000D_
      arrString[start] ="%20"_x000D_
      _x000D_
    }_x000D_
    _x000D_
    start++;_x000D_
  }_x000D_
  _x000D_
  return arrString.join('');_x000D_
}_x000D_
_x000D_
console.log(stringQ1("Mr John Smith   "))
_x000D_
_x000D_
_x000D_

HRESULT: 0x80131040: The located assembly's manifest definition does not match the assembly reference

I got this error when working in the Designer. I had been developing in VS 2012, but "upgraded" to 2017 over the past couple days. Solution was to close and reopen VS.

It may be related to a bug which I've seen reported elsewhere, where the Reference Manager does not work? In that situation, the following error message is encountered when trying to add a reference in the Solution Explorer:

"Error HRESULT E_FAIL has been returned from a call to a COM component."

My workaround was to close the solution, reopen in VS2012, add the reference, close 2012 and reopen 2017. Ridiculous that 2017 should have been released with such an obvious bug.

Internal Error 500 Apache, but nothing in the logs?

If your Internal Server Error information doesn't show up in log files, you probably need to restart the Apache service.

I've found that Apache 2.4 (at least on Windows platform) tends to stubbornly refuse to flush log files—instead, logged data remains in memory for quite a while. It's a good idea from the performance point of view but it can be confusing when developing.

Google drive limit number of download

Sure Google has a limit of downloads so that you don't abuse the system. These are the limits if you are using Gmail:

The following limits apply for Google Apps for Business or Education editions. Limits for domains during trial are lower. These limits may change without notice in order to protect Google’s infrastructure.

Bandwidth limits

Limit                          Per hour            Per day
Download via web client        750 MB              1250 MB
Upload via web client          300 MB              500 MB
POP and IMAP bandwidth limits

Limit                Per day
Download via IMAP    2500 MB
Download via POP     1250 MB
Upload via IMAP      500 MB

check out this link

Cannot GET / Nodejs Error

Have you checked your folder structure? It seems to me like Express can't find your root directory, which should be a a folder named "site" right under your default directory. Here is how it should look like, according to the tutorial:

node_modules/
  .bin/
  express/
  mongoose/
  path/
site/
  css/
  img/
  js/
  index.html
package.json

For example on my machine, I started getting the same error as you when I renamed my "site" folder as something else. So I would suggest you check that you have the index.html page inside a "site" folder that sits on the same path as your server.js file.

Hope that helps!

"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"

As mentioned above, if you use INSERT..IGNORE, errors that occur while executing the INSERT statement are treated as warnings instead.

One thing which is not explicitly mentioned is that INSERT..IGNORE will cause invalid values will be adjusted to the closest values when inserted (whereas invalid values would cause the query to abort if the IGNORE keyword was not used).

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

To get around sandboxing of SCM stored Groovy scripts, I recommend to run the script as Groovy Command (instead of Groovy Script file):

import hudson.FilePath
final GROOVY_SCRIPT = "workspace/relative/path/to/the/checked/out/groovy/script.groovy"

evaluate(new FilePath(build.workspace, GROOVY_SCRIPT).read().text)

in such case, the groovy script is transferred from the workspace to the Jenkins Master where it can be executed as a system Groovy Script. The sandboxing is suppressed as long as the Use Groovy Sandbox is not checked.

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

I had the same problem. I tried 'yyyy-mm-dd' format i.e. '2013-26-11' and got rid of this problem...

Laravel eloquent update record without loading from database

Use property exists:

$post = new Post();
$post->exists = true;
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();

Here is the API documentation: http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Model.html

Printing Python version in output

import platform
print(platform.python_version())

This prints something like

3.7.2

Getting the absolute path of the executable, using C#?

Suppose i have .config file in console app and now am getting like below.

Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "\\YourFolderName\\log4net.config";

Filter object properties by key in ES6

The cleanest way you can find is with Lodash#pick

const _ = require('lodash');

const allowed = ['item1', 'item3'];

const obj = {
  item1: { key: 'sdfd', value:'sdfd' },
  item2: { key: 'sdfd', value:'sdfd' },
  item3: { key: 'sdfd', value:'sdfd' }
}

const filteredObj = _.pick(obj, allowed)

Print a list of space-separated elements in Python 3

You can apply the list as separate arguments:

print(*L)

and let print() take care of converting each element to a string. You can, as always, control the separator by setting the sep keyword argument:

>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5

Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join():

joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string

Note that this requires manual conversion to strings for any non-string values in L!

How do I get the title of the current active window using c#?

Use the Windows API. Call GetForegroundWindow().

GetForegroundWindow() will give you a handle (named hWnd) to the active window.

Documentation: GetForegroundWindow function | Microsoft Docs

Update date + one year in mysql

For multiple interval types use a nested construction as in:

 UPDATE table SET date = DATE_ADD(DATE_ADD(date, INTERVAL 1 YEAR), INTERVAL 1 DAY)

For updating a given date in the column date to 1 year + 1 day

Reset select2 value and show placeholder

Select2 uses a specific CSS class, so an easy way to reset it is:

$('.select2-container').select2('val', '');

And you have the advantage of if you have multiple Select2 at the same form, all them will be reseted with this single command.

Disable eslint rules for folder

To ignore some folder from eslint rules we could create the file .eslintignore in root directory and add there the path to the folder we want omit (the same way as for .gitignore).

Here is the example from the ESLint docs on Ignoring Files and Directories:

# path/to/project/root/.eslintignore
# /node_modules/* and /bower_components/* in the project root are ignored by default

# Ignore built files except build/index.js
build/*
!build/index.js

Call JavaScript function from C#

This may be helpful to you:

<script type="text/javascript">
    function Showalert() {
        alert('Profile not parsed!!');
        window.parent.parent.parent.location.reload();
    }
    function ImportingDone() {
        alert('Importing done successfull.!');
        window.parent.parent.parent.location.reload();
    }
</script>

if (SelectedRowCount == 0)
{
    ScriptManager.RegisterStartupScript(this, GetType(), "displayalertmessage", "Showalert();", true);
}
else
{
    ScriptManager.RegisterStartupScript(this, GetType(), "importingdone", "ImportingDone();", true);
}

How to get the width and height of an android.widget.ImageView?

my friend by this u are not getting height of image stored in db.but you are getting view height.for getting height of image u have to create bitmap from db,s image.and than u can fetch height and width of imageview

how to list all sub directories in a directory

FolderBrowserDialog fbd = new FolderBrowserDialog();

        DialogResult result = fbd.ShowDialog();

        string[] files = Directory.GetFiles(fbd.SelectedPath);
        string[] dirs = Directory.GetDirectories(fbd.SelectedPath);

        foreach (string item2 in dirs)
        {
            FileInfo f = new FileInfo(item2);

            listBox1.Items.Add(f.Name);

        }

        foreach (string item in files)
        {
            FileInfo f = new FileInfo(item);

            listBox1.Items.Add(f.Name);

        }

How can I simulate an anchor click via jquery?

Although this is very old question i found something easier to handle this task. It is jquery plugin developed by jquery UI team called simulate. you can include it after jquery and then you can do something like

<a href="http://stackoverflow.com/"></a>
$('a').simulate('click');

works fine in chrome, firefox, opera and IE10.you can download it from https://github.com/eduardolundgren/jquery-simulate/blob/master/jquery.simulate.js

How to upload and parse a CSV file in php

function doParseCSVFile($filesArray)
    {
        if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) { 

            $strFilePath = $filesArray['frmUpload']['tmp_name']; 

            $strFileHandle = fopen($strFilePath,"r");
            $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 
            $line_of_text = fgetcsv($strFileHandle,1024,",","'"); 

            do { 
                if ($line_of_text[0]) { 
                    $strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
                    ExecuteQry($strInsertSql);
                }               
            } while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);

        } else {
            return FALSE;
        }
    }

How to change owner of PostgreSql database?

Frank Heikens answer will only update database ownership. Often, you also want to update ownership of contained objects (including tables). Starting with Postgres 8.2, REASSIGN OWNED is available to simplify this task.

IMPORTANT EDIT!

Never use REASSIGN OWNED when the original role is postgres, this could damage your entire DB instance. The command will update all objects with a new owner, including system resources (postgres0, postgres1, etc.)


First, connect to admin database and update DB ownership:

psql
postgres=# REASSIGN OWNED BY old_name TO new_name;

This is a global equivalent of ALTER DATABASE command provided in Frank's answer, but instead of updating a particular DB, it change ownership of all DBs owned by 'old_name'.

The next step is to update tables ownership for each database:

psql old_name_db
old_name_db=# REASSIGN OWNED BY old_name TO new_name;

This must be performed on each DB owned by 'old_name'. The command will update ownership of all tables in the DB.

Find non-ASCII characters in varchar columns using SQL Server

Here is a solution for the single column search using PATINDEX.
It also displays the StartPosition, InvalidCharacter and ASCII code.

select line,
  patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,Line) as [Position],
  substring(line,patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,Line),1) as [InvalidCharacter],
  ascii(substring(line,patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,Line),1)) as [ASCIICode]
from  staging.APARMRE1
where patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,Line) >0

Cleanest way to reset forms

Add a reference to the ngForm directive in your html code and this gives you access to the form.

<form #myForm="ngForm" (ngSubmit)="addPost(); myForm.reset()"> ... </form>

Or pass the form to the function:

<form #myForm="ngForm" (ngSubmit)="addPost(myForm)"> ... </form>
addPost(form: NgForm){
    this.newPost = {
        title: this.title,
        body: this.body
    }
    this._postService.addPost(this.newPost);
    form.resetForm(); // or form.reset();
}

The difference between resetForm and reset is that the former will clear the form fields as well as any validation, while the later will only clear the fields. Use resetForm after the form is validated and submitted, otherwise use reset.


Adding another example for people who can't get the above to work.

With button press:

<form #heroForm="ngForm">
    ...
    <button type="button" class="btn btn-default" (click)="newHero(); heroForm.reset()">New Hero</button>
</form>

Same thing applies above, you can also choose to pass the form to the newHero function.

Does reading an entire file leave the file handle open?

Well, if you have to read file line by line to work with each line, you can use

with open('Path/to/file', 'r') as f:
    s = f.readline()
    while s:
        # do whatever you want to
        s = f.readline()

Or even better way:

with open('Path/to/file') as f:
    for line in f:
        # do whatever you want to

Setting the MySQL root user password on OS X

If you can't remember your password, @radtek's answer worked for me except in my case I had set up MySQL using brew which meant that steps 1 and 2 of his answer had to be changed to:

  1. /usr/local/bin/mysql.server stop

  2. /usr/local/bin/mysqld_safe --skip-grant-tables

Note: the lack of sudo.

Why isn't my Pandas 'apply' function referencing multiple columns working?

Seems you forgot the '' of your string.

In [43]: df['Value'] = df.apply(lambda row: my_test(row['a'], row['c']), axis=1)

In [44]: df
Out[44]:
                    a    b         c     Value
          0 -1.674308  foo  0.343801  0.044698
          1 -2.163236  bar -2.046438 -0.116798
          2 -0.199115  foo -0.458050 -0.199115
          3  0.918646  bar -0.007185 -0.001006
          4  1.336830  foo  0.534292  0.268245
          5  0.976844  bar -0.773630 -0.570417

BTW, in my opinion, following way is more elegant:

In [53]: def my_test2(row):
....:     return row['a'] % row['c']
....:     

In [54]: df['Value'] = df.apply(my_test2, axis=1)

Javascript loading CSV file into an array

The original code works fine for reading and separating the csv file data but you need to change the data type from csv to text.

How do I create variable variables?

Any set of variables can also be wrapped up in a class. "Variable" variables may be added to the class instance during runtime by directly accessing the built-in dictionary through __dict__ attribute.

The following code defines Variables class, which adds variables (in this case attributes) to its instance during the construction. Variable names are taken from a specified list (which, for example, could have been generated by program code):

# some list of variable names
L = ['a', 'b', 'c']

class Variables:
    def __init__(self, L):
        for item in L:
            self.__dict__[item] = 100

v = Variables(L)
print(v.a, v.b, v.c)
#will produce 100 100 100

LEFT OUTER JOIN in LINQ

If you need to join and filter on something, that can be done outside of the join. Filter can be done after creating the collection.

In this case if I do this in the join condition I reduce the rows that are returned.

Ternary condition is used (= n == null ? "__" : n.MonDayNote,)

  • If the object is null (so no match), then return what is after the ?. __, in this case.

  • Else, return what is after the :, n.MonDayNote.

Thanks to the other contributors that is where I started with my own issue.


        var schedLocations = (from f in db.RAMS_REVENUE_LOCATIONS
              join n in db.RAMS_LOCATION_PLANNED_MANNING on f.revenueCenterID equals

                  n.revenueCenterID into lm

              from n in lm.DefaultIfEmpty()

              join r in db.RAMS_LOCATION_SCHED_NOTE on f.revenueCenterID equals r.revenueCenterID
              into locnotes

              from r in locnotes.DefaultIfEmpty()
              where f.LocID == nLocID && f.In_Use == true && f.revenueCenterID > 1000

              orderby f.Areano ascending, f.Locname ascending
              select new
              {
                  Facname = f.Locname,
                  f.Areano,
                  f.revenueCenterID,
                  f.Locabbrev,

                  //  MonNote = n == null ? "__" : n.MonDayNote,
                  MonNote = n == null ? "__" : n.MonDayNote,
                  TueNote = n == null ? "__" : n.TueDayNote,
                  WedNote = n == null ? "__" : n.WedDayNote,
                  ThuNote = n == null ? "__" : n.ThuDayNote,

                  FriNote = n == null ? "__" : n.FriDayNote,
                  SatNote = n == null ? "__" : n.SatDayNote,
                  SunNote = n == null ? "__" : n.SunDayNote,
                  MonEmpNbr = n == null ? 0 : n.MonEmpNbr,
                  TueEmpNbr = n == null ? 0 : n.TueEmpNbr,
                  WedEmpNbr = n == null ? 0 : n.WedEmpNbr,
                  ThuEmpNbr = n == null ? 0 : n.ThuEmpNbr,
                  FriEmpNbr = n == null ? 0 : n.FriEmpNbr,
                  SatEmpNbr = n == null ? 0 : n.SatEmpNbr,
                  SunEmpNbr = n == null ? 0 : n.SunEmpNbr,
                  SchedMondayDate = n == null ? dMon : n.MondaySchedDate,
                  LocNotes = r == null ? "Notes: N/A" : r.LocationNote

              }).ToList();
                Func<int, string> LambdaManning = (x) => { return x == 0 ? "" : "Manning:" + x.ToString(); };
        DataTable dt_ScheduleMaster = PsuedoSchedule.Tables["ScheduleMasterWithNotes"];
        var schedLocations2 = schedLocations.Where(x => x.SchedMondayDate == dMon);

How to confirm RedHat Enterprise Linux version?

Avoid /etc/*release* files and run this command instead, it is far more reliable and gives more details:

rpm -qia '*release*'

How do you rebase the current branch's changes on top of changes being merged in?

Another way to look at it is to consider git rebase master as:

Rebase the current branch on top of master

Here , 'master' is the upstream branch, and that explain why, during a rebase, ours and theirs are reversed.

Running javascript in Selenium using Python

Try browser.execute_script instead of selenium.GetEval.

See this answer for example.

How do I make a LinearLayout scrollable?

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center|left"
        android:orientation="vertical">

        Your views go here...

    </LinearLayout>

</ScrollView>

How do I make an http request using cookies on Android?

Since Apache library is deprecated, for those who want to use HttpURLConncetion , I wrote this class to send Get and Post Request with the help of this answer:

public class WebService {

static final String COOKIES_HEADER = "Set-Cookie";
static final String COOKIE = "Cookie";

static CookieManager msCookieManager = new CookieManager();

private static int responseCode;

public static String sendPost(String requestURL, String urlParameters) {

    URL url;
    String response = "";
    try {
        url = new URL(requestURL);

        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");

        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");

        if (msCookieManager.getCookieStore().getCookies().size() > 0) {
            //While joining the Cookies, use ',' or ';' as needed. Most of the server are using ';'
            conn.setRequestProperty(COOKIE ,
                    TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
        }

        conn.setDoInput(true);
        conn.setDoOutput(true);

        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));

        if (urlParameters != null) {
            writer.write(urlParameters);
        }
        writer.flush();
        writer.close();
        os.close();

        Map<String, List<String>> headerFields = conn.getHeaderFields();
        List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);

        if (cookiesHeader != null) {
            for (String cookie : cookiesHeader) {
                msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
            }
        }

        setResponseCode(conn.getResponseCode());

        if (getResponseCode() == HttpsURLConnection.HTTP_OK) {

            String line;
            BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            while ((line = br.readLine()) != null) {
                response += line;
            }
        } else {
            response = "";
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    return response;
}


// HTTP GET request
public static String sendGet(String url) throws Exception {

    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    //add request header 
    con.setRequestProperty("User-Agent", "Mozilla");
    /*
    * https://stackoverflow.com/questions/16150089/how-to-handle-cookies-in-httpurlconnection-using-cookiemanager
    * Get Cookies form cookieManager and load them to connection:
     */
    if (msCookieManager.getCookieStore().getCookies().size() > 0) {
        //While joining the Cookies, use ',' or ';' as needed. Most of the server are using ';'
        con.setRequestProperty(COOKIE ,
                TextUtils.join(";", msCookieManager.getCookieStore().getCookies()));
    }

    /*
    * https://stackoverflow.com/questions/16150089/how-to-handle-cookies-in-httpurlconnection-using-cookiemanager
    * Get Cookies form response header and load them to cookieManager:
     */
    Map<String, List<String>> headerFields = con.getHeaderFields();
    List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
    if (cookiesHeader != null) {
        for (String cookie : cookiesHeader) {
            msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));
        }
    }


    int responseCode = con.getResponseCode();

    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();

    return response.toString();
}

public static void setResponseCode(int responseCode) {
    WebService.responseCode = responseCode;
    Log.i("Milad", "responseCode" + responseCode);
}


public static int getResponseCode() {
    return responseCode;
}
}

Vim and Ctags tips and tricks

I put the following in my .gvimrc file, which searches up the tree from any point for a tags file when gvim starts:

function SetTags()
    let curdir = getcwd()

    while !filereadable("tags") && getcwd() != "/"
        cd ..
    endwhile

    if filereadable("tags")
        execute "set tags=" . getcwd() . "/tags"
    endif

    execute "cd " . curdir
endfunction

call SetTags()

I then periodically regenerate a tags file at the top of my source tree with a script that looks like:

#!/bin/bash

find . -regex ".*\.\(c\|h\|hpp\|cc\|cpp\)" -print | ctags --totals --recurse --extra="+qf" --fields="+i" -L -

CSV API for Java

If you intend to read csv from excel, then there are some interesting corner cases. I can't remember them all, but the apache commons csv was not capable of handling it correctly (with, for example, urls).

Be sure to test excel output with quotes and commas and slashes all over the place.

Is there a good Valgrind substitute for Windows?

You might want to read what Mozilla is doing regarding memory leaks. One tool in their toolbox is the Hans Boehm garbage collector used as memory leak detector.

Convert a char to upper case using regular expressions (EditPad Pro)

TextPad will allow you to perform this operation.

example:

test this sentence

Find what: \([^ ]*\) \(.*\) Replace with: \U\1\E \2

the \U will cause all following chars to be upper

the \E will turn off the \U

the result will be:

TEST this sentence