Programs & Examples On #Launching

Dart SDK is not configured

Downloading and Configuring the Dart SDK

If you don’t already have the Dart SDK, install it. You can get it either by itself or by downloading the Flutter SDK, which (as of Flutter 1.21) includes the full Dart SDK.

Choose one:

Here’s one way to configure Dart support:

  1. Start the IDE, and install the Dart plugin. To find the Dart plugin, from the Welcome screen choose Configure > Plugins, then click Install JetBrains plugin, and then search or scroll down until you find Dart. Once you've installed the Dart plugin, restart the IDE.

  2. Create a new Dart project:

    • From the Welcome screen, click Create New Project.
    • In the next dialog, click Dart.
  3. If you don't see a value for the Dart SDK path, enter it.

    • For example, the SDK path might be <dart installation directory>/dart/dart-sdk.

Unable to merge dex

add commands below:

android {
...

    dexOptions {

        jumboMode true
        javaMaxHeapSize "4g"

    }
}

Xcode 9 error: "iPhone has denied the launch request"

After seeing all the solutions given across web, i finally found one and here are those:

  • Error occurs because of it makes Runner confused about what profile to use.
  • You will most often get this error, when you have added new account in profile in Xcode > Targets > Signing.
  • You can remove this error by just using before one Profile.
  • There is no need to create New Users.
  • or you can sign in with account you are using in Profile in your iPhone (i did this!)

Happy Days :)

Can't bind to 'ngModel' since it isn't a known property of 'input'

If you are still getting the error after importing FormsModule correctly then check in your terminal or (windows console) because your project is not compiling (because of another error that could be anything) and your solution has not been reflected in your browser!

In my case, my console had the following unrelated error:

Property 'retrieveGithubUser' does not exist on type 'ApiService'.

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

The issue is that you are not able to get a connection to MYSQL database and hence it is throwing an error saying that cannot build a session factory.

Please see the error below:

 Caused by: java.sql.SQLException: Access denied for user ''@'localhost' (using password: NO) 

which points to username not getting populated.

Please recheck system properties

dataSource.setUsername(System.getProperty("root"));

some packages seems to be missing as well pointing to a dependency issue:

package org.gjt.mm.mysql does not exist

Please run a mvn dependency:tree command to check for dependencies

React Native Change Default iOS Simulator Device

As answered by Ian L, I also use NPM to manage my scripts.

Example:

_x000D_
_x000D_
{_x000D_
  "scripts": {_x000D_
    "ios": "react-native run-ios --simulator=\"iPad Air 2\"",_x000D_
    "devices": "xcrun simctl list devices"_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

This way, I can quickly get what I need:

  1. List all devices: npm run devices
  2. Run the default simulator: npm run ios

Error while waiting for device: Time out after 300seconds waiting for emulator to come online

Sadly none of the solutions worked for me! I solved my problem by uninstalling existing APK from my phone and it all started working perfectly!

This started happening after I've updated android studio to latest version.

Session 'app': Error Launching activity

I tried, clean & rebuild project and Invalidate Cache & Restart also manually removed .gradle and .idea folders, but that didn't solved the issue.

I have 3 user acounts in my phone. So, I didn't select Uninstall for all users, and it only uninstall my app from first user account, but it was still there in guest and second user account.

So, I removed it from rest of the accounts and it solved my issue!!

How to solve ERR_CONNECTION_REFUSED when trying to connect to localhost running IISExpress - Error 502 (Cannot debug from Visual Studio)?

In my case it was caused by starting IIS with no administrative rights. When I launched IIS as admin and started the site it worked fine

How can I keep a container running on Kubernetes?

You could use this CMD in your Dockerfile:

CMD exec /bin/bash -c "trap : TERM INT; sleep infinity & wait"

This will keep your container alive until it is told to stop. Using trap and wait will make your container react immediately to a stop request. Without trap/wait stopping will take a few seconds.

For busybox based images (used in alpine based images) sleep does not know about the infinity argument. This workaround gives you the same immediate response to a docker stop like in the above example:

CMD exec /bin/sh -c "trap : TERM INT; sleep 9999999999d & wait"

Docker error response from daemon: "Conflict ... already in use by container"

I got this error quite a lot, so now I do a batch removal of all unused containers at once:

docker container prune 

add -f to force removal without prompt.

To list all unused containers (without removal):

docker container ls -a --filter status=exited --filter status=created 

See here more examples how to prune other objects (networks, volumes, etc.).

How to open Visual Studio Code from the command line on OSX?

After opening VSC and pressing (Command + Up + P) I tried typing in "shell command" and nothing came up. In order to get "Shell Command: Install 'code' command in PATH command" to come up, you must do the following:

  1. Press (Command, Up, P)

  2. Type > (this will show and run commands)

  3. Then type Shell Command: Install 'code' command in PATH command. It should then come up.

    Once you click it, it will update and you should be good to go!

MacOS X Launch from Command Line docs

Running PowerShell as another user, and launching a script

Here's also nice way to achieve this via UI.

0) Right click on PowerShell icon when on task bar

1) Shift + right click on Windows PowerShell

2) "Run as different user"

Pic

Debugging with Android Studio stuck at "Waiting For Debugger" forever

On some machines/projects the debugger do not attach automatically so you need to attach it manually (studio menu -> Run -> Attach debugger to Android process)

Android Studio doesn't start, fails saying components not installed

For OSX (Mac)

I tried install as Administrator (sudo) but it's did not work


After that I solve the problem by this,

when setup, select custom setup instead of standard setup

then, it will solve this problem

Android studio takes too much memory

You can speed up your Eclipse or Android Studio work, you just follow these:

  • Use/open single project at a time
  • clean your project after running your app in emulator every time
  • use mobile/external device instead of emulator
  • don't close emulator after using once, use same emulator for running app each time
  • Disable VCS by using File->Settings->Plugins and disable the following things :
    1.CVS Integration
    2.Git Integration
    3.GitHub
    4.Google Cloud Tools for Android Studio
    5.Subversion Integration

I am also using Android Studio with 4-GB installed main memory but following these statements really boost my Android Studio performance.

set initial viewcontroller in appdelegate - swift

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
    let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    var exampleViewController: ExampleViewController = mainStoryboard.instantiateViewControllerWithIdentifier("ExampleController") as! ExampleViewController

    self.window?.rootViewController = exampleViewController

    self.window?.makeKeyAndVisible()

    return true
}

Error in launching AVD with AMD processor

This resolves it for me:

Go to (C:\users\%USERNAME%\AppData\Local\Android\sdk, generally).

Then go to Extras -> Intel -> Hardware_Accelerated_Execution_Manager and run the file named "intelhaxm-android.exe".

In case you get an error like "Intel virtualization technology (vt,vt-x) is not enabled", go to your BIOS settings and enable Hardware Virtualization.

Restart your studio

How to actually search all files in Visual Studio

So the answer seems to be to NOT use the Solution Explorer search box.

Rather, open any file in the solution, then use the control-f search pop-up to search all files by:

  1. selecting "Find All" from the "--> Find Next / <-- Find Previous" selector
  2. selecting "Current Project" or "Entire Solution" from the selector that normally says just "Current Document".

How to turn off INFO logging in Spark?

You can use setLogLevel

val spark = SparkSession
      .builder()
      .config("spark.master", "local[1]")
      .appName("TestLog")
      .getOrCreate()

spark.sparkContext.setLogLevel("WARN")

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Your -vm argument seems ok BUT it's position is wrong. According to this Eclipse Wiki entry :

The -vm option must occur before the -vmargs option, since everything after -vmargs is passed directly to the JVM.

So your -vm argument is not taken into account and it fails over to your default java installation, which is probably 1.6.0_65.

iOS app with framework crashed on device, dyld: Library not loaded, Xcode 6 Beta

Firstly Try to build after Command+Option+Shift+K .If still fails then do below steps.

If anybody is facing this error in Xcode 8 then change your framework status to Optional instead of Required under the General Tab of your target.

enter image description here

How do I hide the status bar in a Swift iOS app?

If you want to hide and bring back the status bar on button tap, while at the time of presenting and dismissing slide-in menu, popups etc, then you can use this method:-

To hide the status bar:-

UIApplication.shared.keyWindow?.windowLevel = UIWindowLevelStatusBar

To bring back the status bar:-

UIApplication.shared.keyWindow?.windowLevel = UIWindowLevelNormal 

How to debug Spring Boot application with Eclipse?

  • right click on your project and choose "Debug As => Java application or Spring boot App" -capture1 - enter image description here
  • If you want that your application pause in somewhere in your app double click on the left you will have like this capture 2. enter image description here
  • then when you start your app use those arrows to go next.(capture 3) enter image description here

How can I resolve the error: "The command [...] exited with code 1"?

For me, in VS 2013, I had to get rid of missing references under References in the UI project (MVC). Turns out, the ones missing were not referenced.

Android Studio suddenly cannot resolve symbols

In my multi-module project, the problem was that version of "com.android.support:appcompat-v7" in module A was "22.0.0", but in B - "22.2.0".

Solution: make sure
1. version of common libraries is same among modules.
2. each of modules compiles without any errors (try to build each of them from CLI).

intelliJ IDEA 13 error: please select Android SDK

If you can't compile a proyect and you have this message:

enter image description here

Go to File -> Project Structure, then go to Modules section and select your module app and then select a Compile Sdk Version and a Build Tools Version after that click in OK.

enter image description here

Wait until gradle synchronize and ready!

Error type 3 Error: Activity class {} does not exist

Just in case anyone runs into my issue and has no luck with the other solutions... I was trying to start an activity through adb for FireTV while debugging Amazon launcher integration. However, my project had 60 different build variants (multi-platform, multi-app project) and the ApplicationId didn't match any classpath since the runtime package (and classpaths) were different from the applicationId.

I was trying to run adb shell am start -n com.myappid.example.packageone.packagetwo/com.myappid.example.packageone.packagetwo.MySplashActivity

(Of course I had tried many combinations with com.runtimepath.example since I had the added challenge of a different applicationId in my build.gradle and another at runtime)

What finally helped was this post https://stackoverflow.com/a/36255727/5970652

Which revealed a different format! com.myappid.example/com.runtimepath.example.packageone.packagetwo.MySplashActivity

So if you have a different runtime classpath try specifying with the build.gradle applicationId before the slash and the runtime classpath afterwards.

You can also get these values from BuildConfig.APPLICATION_ID and this.getLocalClassName() respectively if you want to log them in logcat.

Launching Spring application Address already in use

you can configure another port number in your IDE /src/main/resources/application.properties

server.port=8081

otherwise right click on the IDE console tab and select Terminate/Disconnect All

How can I start InternetExplorerDriver using Selenium WebDriver

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.ie.*;

public class IEclass {



public static void main(String[] args) {

System.setProperty("webdriver.ie.driver","S:\\IE and Chrome ServerDriver\\IEDriverServer.exe");

WebDriver driver = new InternetExplorerDriver();

driver.get("https://www.google.com");
  }
    }

SSL Connection / Connection Reset with IISExpress

I was having this problem, I had configured my site for global require https in FilterConfig.cs.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new HandleErrorAttribute());
        filters.Add(new RequireHttpsAttribute());
    }

I had forgotten to change the project url to https: from this tutorial http://azure.microsoft.com/en-us/documentation/articles/web-sites-dotnet-deploy-aspnet-mvc-app-membership-oauth-sql-database/ under ENABLE SSL part 4. This caused the errors you were getting.

Will iOS launch my app into the background if it was force-quit by the user?

The answer is YES, but shouldn't use 'Background Fetch' or 'Remote notification'. PushKit is the answer you desire.

In summary, PushKit, the new framework in ios 8, is the new push notification mechanism which can silently launch your app into the background with no visual alert prompt even your app was killed by swiping out from app switcher, amazingly you even cannot see it from app switcher.

PushKit reference from Apple:

The PushKit framework provides the classes for your iOS apps to receive pushes from remote servers. Pushes can be of one of two types: standard and VoIP. Standard pushes can deliver notifications just as in previous versions of iOS. VoIP pushes provide additional functionality on top of the standard push that is needed to VoIP apps to perform on-demand processing of the push before displaying a notification to the user.

To deploy this new feature, please refer to this tutorial: https://zeropush.com/guide/guide-to-pushkit-and-voip - I've tested it on my device and it works as expected.

Class JavaLaunchHelper is implemented in both ... libinstrument.dylib. One of the two will be used. Which one is undefined

If you're using IntelliJ & Mac just go to Project structure -> SDK and make sure that there is Java listed but it points to sth like

/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home

Rather than user home...

iOS 7 status bar back to iOS 6 default style in iPhone app?

This is cross-posted from a blog post I wrote, but here is the full rundown on status bars, navigation bars, and container view controllers on iOS 7:

  1. There is no way to preserve the iOS 6 style status bar layout. The status bar will always overlap your application on iOS 7

  2. Do not confuse status bar appearance with status bar layout. The appearance (light or default) does not affect how the status bar is laid out (frame/height/overlap). It is important to note as well that the system status bar no longer has any background color. When the API refers to UIStatusBarStyleLightContent, they mean white text on a clear background. UIStatusBarStyleDefault is black text on a clear background.

  3. Status bar appearance is controlled along one of two mutually-exclusive basis paths: you can either set them programmatically in the traditional manner, or UIKit will update the appearance for you based on some new properties of UIViewController. The latter option is on by default. Check your app’s plist value for “ViewController-Based Status Bar Appearance” to see which one you’re using. If you set this value to YES, every top-level view controller in your app (other than a standard UIKit container view controller) needs to override preferredStatusBarStyle, returning either the default or the light style. If you edit the plist value to NO, then you can manage the status bar appearance using the familiar UIApplication methods.

  4. UINavigationController will alter the height of its UINavigationBar to either 44 points or 64 points, depending on a rather strange and undocumented set of constraints. If the UINavigationController detects that the top of its view’s frame is visually contiguous with its UIWindow’s top, then it draws its navigation bar with a height of 64 points. If its view’s top is not contiguous with the UIWindow’s top (even if off by only one point), then it draws its navigation bar in the “traditional” way with a height of 44 points. This logic is performed by UINavigationController even if it is several children down inside the view controller hierarchy of your application. There is no way to prevent this behavior.

  5. If you supply a custom navigation bar background image that is only 44 points (88 pixels) tall, and the UINavigationController’s view’s bounds matches the UIWindow’s bounds (as discussed in #4), the UINavigationController will draw your image in the frame (0,20,320,44), leaving 20 points of opaque black space above your custom image. This may confuse you into thinking you are a clever developer who bypassed rule #1, but you are mistaken. The navigation bar is still 64 points tall. Embedding a UINavigationController in a slide-to-reveal style view hierarchy makes this abundantly clear.

  6. Beware of the confusingly-named edgesForExtendedLayout property of UIViewController. Adjusting edgesForExtendedLayout does nothing in most cases. The only way UIKit uses this property is if you add a view controller to a UINavigationController, then the UINavigationController uses edgesForExtendedLayout to determine whether or not its child view controller should be visible underneath the navigation bar / status bar area. Setting edgesForExtendedLayout on the UINavigationController itself does nothing to alter whether or not the UINavigationController has a 44 or 64 point high navigation bar area. See #4 for that logic. Similar layout logic applies to the bottom of your view when using a toolbar or UITabBarController.

  7. If all you are trying to do is prevent your custom child view controller from underlapping the navigation bar when inside a UINavigationController, then set edgesForExtendedLayout to UIRectEdgeNone (or at least a mask that excludes UIRectEdgeTop). Set this value as early as possible in the life cycle of your view controller.

  8. UINavigationController and UITabBarController will also try to pad the contentInsets of table views and collection views in its subview hierarchy. It does this in a manner similar to the status bar logic from #4. There is a programmatic way of preventing this, by setting automaticallyAdjustsScrollViewInsets to NO for your table views and collection views (it defaults to YES). This posed some serious problems for Whisper and Riposte, since we use contentInset adjustments to control the layout of table views in response to toolbar and keyboard movements.

  9. To reiterate: there is no way to return to iOS 6 style status bar layout logic. In order to approximate this, you have to move all the view controllers of your app into a container view that is offset by 20 points from the top of the screen, leaving an intentionally black view behind the status bar to simulate the old appearance. This is the method we ended up using in Riposte and Whisper.

  10. Apple is pushing very hard to ensure that you don’t try to do #9. They want us to redesign all our apps to underlap the status bar. There are many cogent arguments, however, for both user experience and technical reasons, why this is not always a good idea. You should do what is best for your users and not simply follow the whimsy of the platform.

RuntimeError on windows trying python multiprocessing

Though the earlier answers are correct, there's a small complication it would help to remark on.

In case your main module imports another module in which global variables or class member variables are defined and initialized to (or using) some new objects, you may have to condition that import in the same way:

if __name__ ==  '__main__':
  import my_module

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

I think JAVA_HOME is the best you can do. The command-line tools like java and javac will respect that environment variable, you can use /usr/libexec/java_home -v '1.7*' to give you a suitable value to put into JAVA_HOME in order to make command line tools use Java 7.

export JAVA_HOME="`/usr/libexec/java_home -v '1.7*'`"

But standard double-clickable application bundles don't use JDKs installed under /Library/Java at all. Old-style .app bundles using Apple's JavaApplicationStub will use Apple Java 6 from /System/Library/Frameworks, and new-style ones built with AppBundler without a bundled JRE will use the "public" JRE in /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home - that's hard-coded in the stub code and can't be changed, and you can't have two different public JREs installed at the same time.


Edit: I've had a look at VisualVM specifically, assuming you're using the "application bundle" version from the download page, and this particular app is not an AppBundler application, instead its main executable is a shell script that calls a number of other shell scripts and reads various configuration files. It defaults to picking the newest JDK from /Library/Java as long as that is 7u10 or later, or uses Java 6 if your Java 7 installation is update 9 or earlier. But unravelling the logic in the shell scripts it looks to me like you can specify a particular JDK using a configuration file.

Create a text file ~/Library/Application Support/VisualVM/1.3.6/etc/visualvm.conf (replace 1.3.6 with whatever version of VisualVM you're using) containing the line

visualvm_jdkhome="`/usr/libexec/java_home -v '1.7*'`"

and this will force it to choose Java 7 instead of 8.

How to change Vagrant 'default' machine name?

You can change vagrant default machine name by changing value of config.vm.define.

Here is the simple Vagrantfile which uses getopts and allows you to change the name dynamically:

# -*- mode: ruby -*-
require 'getoptlong'

opts = GetoptLong.new(
  [ '--vm-name',        GetoptLong::OPTIONAL_ARGUMENT ],
)
vm_name        = ENV['VM_NAME'] || 'default'

begin
  opts.each do |opt, arg|
    case opt
      when '--vm-name'
        vm_name = arg
    end
  end
  rescue
end

Vagrant.configure(2) do |config|
  config.vm.define vm_name
  config.vm.provider "virtualbox" do |vbox, override|
    override.vm.box = "ubuntu/wily64"
    # ...
  end
  # ...
end

So to use different name, you can run for example:

vagrant --vm-name=my_name up --no-provision

Note: The --vm-name parameter needs to be specified before up command.

or:

VM_NAME=my_name vagrant up --no-provision

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

In my case, this error occurred because of windows 7 shortcuts. In windows we create shortcuts on desktop by using right click > send to > desktop. In my pc, there is no option for desktop, but there is one for "documents". I created the shortcuts there and then moved them to the desktop. Executing these shortcuts causes the error. Eclipse works fine when I run it directly from the folder where it is installed. I fixed it by using right click > create shortcut and then moving this shortcut to the desktop.

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

In my case, I needed to deploy two Qt apps on an Ubuntu virtualbox guest. One was command-line ("app"), the other GUI_based ("app_GUI").

I used "ldd app" to find out what the required libs are, and copied them to the Ubuntu guest. While the command-line executable "app" worked ok, the GUI-based executable crashed, giving the "Failed to load platform plugin "xcb" error. I checked ldd for libxcb.so, but this too had no missing dependencies.

The problem seemed to be that while I did copy all the right libraries I accidentally had copied also libraries that were already present at the guest system.. meaning that (a) they were unnecessary to copy them in the first place and (b) worse, copying them produced incompatibilities between the install libraries. Worse still, they were undetectable by ldd like I said..

The solution? Make sure that you copy libraries shown as missing by ldd and absolutely no extra libraries.

Detect if the app was launched/opened from a push notification

For swift:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    PFPush.handlePush(userInfo)

    if application.applicationState == UIApplicationState.Inactive || application.applicationState == UIApplicationState.Background {
        //opened from a push notification when the app was in the background

    }

}

CS0234: Mvc does not exist in the System.Web namespace

You need to include the reference to the assembly System.Web.Mvc in you project.

you may not have the System.Web.Mvc in your C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0

So you need to add it and then to include it as reference to your projrect

Launch iOS simulator from Xcode and getting a black screen, followed by Xcode hanging and unable to stop tasks

Solution 1 : You can Quit simulator and try again.

Solution 2 (Recommended) : Go to iOS Simulator -> Reset Content and Settings...

Step 1

This will pop-up an alert stating 'Are you sure you want to reset the iOS Simulator content and settings?'

Step 2

Select Reset if you wish to or else Don't Reset button.

Note that once you reset simulator content all app installed on simulator will be deleted and it will reset to initial settings.

Increase JVM max heap size for Eclipse

--launcher.XXMaxPermSize

256m

Try to bump that value up!

NSInternalInconsistencyException', reason: 'Could not load NIB in bundle: 'NSBundle

I spend a hour finding out what was wrong.. But Clean Project did the trick.

Build -> Clean All

The accepted solution is probably also working.. but this was enough for me.

Is there a command to restart computer into safe mode?

In the command prompt, type the command below and press Enter.

bcdedit /enum

Under the Windows Boot Loader sections, make note of the identifier value.

To start in safe mode from command prompt :

bcdedit /set {identifier} safeboot minimal 

Then enter the command line to reboot your computer.

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

Solution -

1) Upgrade your Selenium Server i.e. selenium jar "selenium-server-standalone-2.xx.x.JAR" TO "selenium-server-standalone-2.45.0.JAR"

2) Upgrade your Selenium Client Driver i.e. selenium libs folder "selenium-java-2.xx.x" TO "selenium-java-2.45.0"

3) Check and Install compatible Firefox version

Refer - Download updated selenium libs & jar i.e. Version 2.45.0

This will RESOLVE your problem.. Cheers !!

How to fix 'Microsoft Excel cannot open or save any more documents'

Go to this key on Registry Editor (Run | Regedit) HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders

change key Cache to something like C:\Windows\Temp

My similar problem was solved like this.

Regards,

Ripley

How do I start an activity from within a Fragment?

Use the Base Context of the Activity in which your fragment resides to start an Intent.

Intent j = new Intent(fBaseCtx, NewactivityName.class);         
startActivity(j);

where fBaseCtx is BaseContext of your current activity. You can get it as fBaseCtx = getBaseContext();

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

I believe that npm install should not run in a production environment. There are several things that can go wrong - npm outage, download of newer dependencies (shrinkwrap seems to have solved this) are two of them.

On the other hand, folder node_modules should not be committed to Git. Apart from their big size, commits including them can become distracting.

The best solutions would be this: npm install should run in a CI environment that is similar to the production environment. All tests will run and a zipped release file will be created that will include all dependencies.

What is Hive: Return Code 2 from org.apache.hadoop.hive.ql.exec.MapRedTask

I faced the same issue because I didn't have permission to query the database I was trying to.

In the case you don't have permission to query the table/database, besides the Return Code 2 from org.apache.hadoop.hive.ql.exec.MapRedTask error, you will see that in Cloudera Manager is not even registering your query.

How to fix "no valid 'aps-environment' entitlement string found for application" in Xcode 4.3?

Easiest way is to do this from your accounts with Xcode:

Head over Xcode -> Preferences -> Choose Accounts Tab -> View Details -> Hit refresh button on the bottom left -> Done.

Build again and it should work.

Launch Android application without main Activity and start Service on launching application

The reason to make an App with no activity or service could be making a Homescreen Widget app that doesn't need to be started.
Once you start a project don't create any activities. After you created the project just hit run. Android studio will say No default activity found.

Click Edit Configuration (From the Run menu) and in the Launch option part set the Launch value to Nothing. Then click ok and run the App.

(Since there is no launcher activity, No app will be show in the Apps menu.).

Issue with Task Scheduler launching a task

Thanks all, I had the same issue. I have a task that runs via a generic user account not linked to a particular person. This user as somehow logged off the VM, when I was trying to fix it I was logged in as me and not that user.

Logging back in with that user fixed the issue!

Positioning <div> element at center of screen

Use flex. Much simpler and will work regardless of your div size:

_x000D_
_x000D_
.center-screen {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  text-align: center;_x000D_
  min-height: 100vh;_x000D_
}
_x000D_
 <html>_x000D_
 <head>_x000D_
 </head>_x000D_
 <body>_x000D_
 <div class="center-screen">_x000D_
 I'm in the center_x000D_
 </div>_x000D_
 </body>_x000D_
 </html>
_x000D_
_x000D_
_x000D_

Xcode error - Thread 1: signal SIGABRT

SIGABRT means in general that there is an uncaught exception. There should be more information on the console.

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.

I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.

# Enable TCP/IP

Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable

# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433

# Modify TCP/IP properties to enable an IP address

$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }

# Restart SQL Server

Restart-Service 'MSSQL$SQLEXPRESS'

Detect home button press in android

Following code works for me :)

HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
    @Override
    public void onHomePressed() {
        // do something here...
    }
    @Override
    public void onHomeLongPressed() {
    }
});
mHomeWatcher.startWatch();
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

public class HomeWatcher {

    static final String TAG = "hg";
    private Context mContext;
    private IntentFilter mFilter;
    private OnHomePressedListener mListener;
    private InnerReceiver mReceiver;

    public HomeWatcher(Context context) {
        mContext = context;
        mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
    }

    public void setOnHomePressedListener(OnHomePressedListener listener) {
        mListener = listener;
        mReceiver = new InnerReceiver();
    }

    public void startWatch() {
        if (mReceiver != null) {
            mContext.registerReceiver(mReceiver, mFilter);
        }
    }

    public void stopWatch() {
        if (mReceiver != null) {
            mContext.unregisterReceiver(mReceiver);
        }
    }

    class InnerReceiver extends BroadcastReceiver {
        final String SYSTEM_DIALOG_REASON_KEY = "reason";
        final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
        final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
        final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
                if (reason != null) {
                    Log.e(TAG, "action:" + action + ",reason:" + reason);
                    if (mListener != null) {
                        if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                            mListener.onHomePressed();
                        } else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
                            mListener.onHomeLongPressed();
                        }
                    }
                }
            }
        }
    }
}
public interface OnHomePressedListener {
    void onHomePressed();
    void onHomeLongPressed();
}

Get device token for push notification

Get device token in Swift 3

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})

    print("Device token: \(deviceTokenString)")

}

how to pass command line arguments to main method dynamically

go to Run Configuration and in argument tab you can write your argument

iOS application: how to clear notifications?

When you logout from your app, at that time you have to use a below line of code on your logout button click method.

[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];

[[UIApplication sharedApplication] cancelAllLocalNotifications];

and this works perfectly in my app.

Programmatically extract contents of InstallShield setup.exe

The free and open-source program called cabextract will list and extract the contents of not just .cab-files, but Macrovision's archives too:

% cabextract /tmp/QLWREL.EXE
Extracting cabinet: /tmp/QLWREL.EXE
  extracting ikernel.dll
  extracting IsProBENT.tlb
  ....
  extracting IScript.dll
  extracting iKernel.rgs

All done, no errors.

Can Selenium interact with an existing browser session?

Inspired by Eric's answer, here is my solution to this problem for selenium 3.7.0. Compared with the solution at http://tarunlalwani.com/post/reusing-existing-browser-session-selenium/, the advantage is that there won't be a blank browser window each time I connect to the existing session.

import warnings

from selenium.common.exceptions import WebDriverException
from selenium.webdriver.remote.errorhandler import ErrorHandler
from selenium.webdriver.remote.file_detector import LocalFileDetector
from selenium.webdriver.remote.mobile import Mobile
from selenium.webdriver.remote.remote_connection import RemoteConnection
from selenium.webdriver.remote.switch_to import SwitchTo
from selenium.webdriver.remote.webdriver import WebDriver


# This webdriver can directly attach to an existing session.
class AttachableWebDriver(WebDriver):
    def __init__(self, command_executor='http://127.0.0.1:4444/wd/hub',
                 desired_capabilities=None, browser_profile=None, proxy=None,
                 keep_alive=False, file_detector=None, session_id=None):
        """
        Create a new driver that will issue commands using the wire protocol.

        :Args:
         - command_executor - Either a string representing URL of the remote server or a custom
             remote_connection.RemoteConnection object. Defaults to 'http://127.0.0.1:4444/wd/hub'.
         - desired_capabilities - A dictionary of capabilities to request when
             starting the browser session. Required parameter.
         - browser_profile - A selenium.webdriver.firefox.firefox_profile.FirefoxProfile object.
             Only used if Firefox is requested. Optional.
         - proxy - A selenium.webdriver.common.proxy.Proxy object. The browser session will
             be started with given proxy settings, if possible. Optional.
         - keep_alive - Whether to configure remote_connection.RemoteConnection to use
             HTTP keep-alive. Defaults to False.
         - file_detector - Pass custom file detector object during instantiation. If None,
             then default LocalFileDetector() will be used.
        """
        if desired_capabilities is None:
            raise WebDriverException("Desired Capabilities can't be None")
        if not isinstance(desired_capabilities, dict):
            raise WebDriverException("Desired Capabilities must be a dictionary")
        if proxy is not None:
            warnings.warn("Please use FirefoxOptions to set proxy",
                          DeprecationWarning)
            proxy.add_to_capabilities(desired_capabilities)
        self.command_executor = command_executor
        if type(self.command_executor) is bytes or isinstance(self.command_executor, str):
            self.command_executor = RemoteConnection(command_executor, keep_alive=keep_alive)

        self.command_executor._commands['GET_SESSION'] = ('GET', '/session/$sessionId')  # added

        self._is_remote = True
        self.session_id = session_id  # added
        self.capabilities = {}
        self.error_handler = ErrorHandler()
        self.start_client()
        if browser_profile is not None:
            warnings.warn("Please use FirefoxOptions to set browser profile",
                          DeprecationWarning)

        if session_id:
            self.connect_to_session(desired_capabilities)  # added
        else:
            self.start_session(desired_capabilities, browser_profile)

        self._switch_to = SwitchTo(self)
        self._mobile = Mobile(self)
        self.file_detector = file_detector or LocalFileDetector()

        self.w3c = True  # added hardcoded

    def connect_to_session(self, desired_capabilities):
        response = self.execute('GET_SESSION', {
            'desiredCapabilities': desired_capabilities,
            'sessionId': self.session_id,
        })
        # self.session_id = response['sessionId']
        self.capabilities = response['value']

To use it:

if use_existing_session:
    browser = AttachableWebDriver(command_executor=('http://%s:4444/wd/hub' % ip),
                                  desired_capabilities=(DesiredCapabilities.INTERNETEXPLORER),
                                  session_id=session_id)
    self.logger.info("Using existing browser with session id {}".format(session_id))
else:
    browser = AttachableWebDriver(command_executor=('http://%s:4444/wd/hub' % ip),
                                  desired_capabilities=(DesiredCapabilities.INTERNETEXPLORER))
    self.logger.info('New session_id  : {}'.format(browser.session_id))

Running Selenium WebDriver python bindings in chrome

Mac OSX only

An easier way to get going (assuming you already have homebrew installed, which you should, if not, go do that first and let homebrew make your life better) is to just run the following command:

brew install chromedriver

That should put the chromedriver in your path and you should be all set.

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.

prevent iphone default keyboard when focusing an <input>

By adding the attribute readonly (or readonly="readonly") to the input field you should prevent anyone typing anything in it, but still be able to launch a click event on it.

This is also usefull in non-mobile devices as you use a date/time picker

spring PropertyPlaceholderConfigurer and context:property-placeholder

First, you don't need to define both of those locations. Just use classpath:config/properties/database.properties. In a WAR, WEB-INF/classes is a classpath entry, so it will work just fine.

After that, I think what you mean is you want to use Spring's schema-based configuration to create a configurer. That would go like this:

<context:property-placeholder location="classpath:config/properties/database.properties"/>

Note that you don't need to "ignoreResourceNotFound" anymore. If you need to define the properties separately using util:properties:

<context:property-placeholder properties-ref="jdbcProperties" ignore-resource-not-found="true"/>

There's usually not any reason to define them separately, though.

Applications are expected to have a root view controller at the end of application launch

None of the above suggestions solved my problem. Mine was this:

Add:

window.rootViewController = navigationController;

after:

[window addSubview:navigationController.view];

in my appdelegate's

- (void)applicationDidFinishLaunching:(UIApplication *)application {

"getaddrinfo failed", what does that mean?

The problem, in my case, was that some install at some point defined an environment variable http_proxy on my machine when I had no proxy.

Removing the http_proxy environment variable fixed the problem.

How to set an environment variable only for the duration of the script?

Just put

export HOME=/blah/whatever

at the point in the script where you want the change to happen. Since each process has its own set of environment variables, this definition will automatically cease to have any significance when the script terminates (and with it the instance of bash that has a changed environment).

How can I auto-elevate my batch file, so that it requests from UAC administrator rights if required?

There is an easy way without the need to use an external tool - it runs fine with Windows 7, 8, 8.1 and 10 and is backwards-compatible too (Windows XP doesn't have any UAC, thus elevation is not needed - in that case the script just proceeds).

Check out this code (I was inspired by the code by NIronwolf posted in the thread Batch File - "Access Denied" On Windows 7?), but I've improved it - in my version there isn't any directory created and removed to check for administrator privileges):

::::::::::::::::::::::::::::::::::::::::::::
:: Elevate.cmd - Version 4
:: Automatically check & get admin rights
:: see "https://stackoverflow.com/a/12264592/1016343" for description
::::::::::::::::::::::::::::::::::::::::::::
 @echo off
 CLS
 ECHO.
 ECHO =============================
 ECHO Running Admin shell
 ECHO =============================

:init
 setlocal DisableDelayedExpansion
 set cmdInvoke=1
 set winSysFolder=System32
 set "batchPath=%~0"
 for %%k in (%0) do set batchName=%%~nk
 set "vbsGetPrivileges=%temp%\OEgetPriv_%batchName%.vbs"
 setlocal EnableDelayedExpansion

:checkPrivileges
  NET FILE 1>NUL 2>NUL
  if '%errorlevel%' == '0' ( goto gotPrivileges ) else ( goto getPrivileges )

:getPrivileges
  if '%1'=='ELEV' (echo ELEV & shift /1 & goto gotPrivileges)
  ECHO.
  ECHO **************************************
  ECHO Invoking UAC for Privilege Escalation
  ECHO **************************************

  ECHO Set UAC = CreateObject^("Shell.Application"^) > "%vbsGetPrivileges%"
  ECHO args = "ELEV " >> "%vbsGetPrivileges%"
  ECHO For Each strArg in WScript.Arguments >> "%vbsGetPrivileges%"
  ECHO args = args ^& strArg ^& " "  >> "%vbsGetPrivileges%"
  ECHO Next >> "%vbsGetPrivileges%"

  if '%cmdInvoke%'=='1' goto InvokeCmd 

  ECHO UAC.ShellExecute "!batchPath!", args, "", "runas", 1 >> "%vbsGetPrivileges%"
  goto ExecElevation

:InvokeCmd
  ECHO args = "/c """ + "!batchPath!" + """ " + args >> "%vbsGetPrivileges%"
  ECHO UAC.ShellExecute "%SystemRoot%\%winSysFolder%\cmd.exe", args, "", "runas", 1 >> "%vbsGetPrivileges%"

:ExecElevation
 "%SystemRoot%\%winSysFolder%\WScript.exe" "%vbsGetPrivileges%" %*
 exit /B

:gotPrivileges
 setlocal & cd /d %~dp0
 if '%1'=='ELEV' (del "%vbsGetPrivileges%" 1>nul 2>nul  &  shift /1)

 ::::::::::::::::::::::::::::
 ::START
 ::::::::::::::::::::::::::::
 REM Run shell as admin (example) - put here code as you like
 ECHO %batchName% Arguments: P1=%1 P2=%2 P3=%3 P4=%4 P5=%5 P6=%6 P7=%7 P8=%8 P9=%9
 cmd /k

The script takes advantage of the fact that NET FILE requires administrator privilege and returns errorlevel 1 if you don't have it. The elevation is achieved by creating a script which re-launches the batch file to obtain privileges. This causes Windows to present the UAC dialog and asks you for the administrator account and password.

I have tested it with Windows 7, 8, 8.1, 10 and with Windows XP - it works fine for all. The advantage is, after the start point you can place anything that requires system administrator privileges, for example, if you intend to re-install and re-run a Windows service for debugging purposes (assumed that mypackage.msi is a service installer package):

msiexec /passive /x mypackage.msi
msiexec /passive /i mypackage.msi
net start myservice

Without this privilege elevating script, UAC would ask you three times for your administrator user and password - now you're asked only once at the beginning, and only if required.


If your script just needs to show an error message and exit if there aren't any administrator privileges instead of auto-elevating, this is even simpler: You can achieve this by adding the following at the beginning of your script:

@ECHO OFF & CLS & ECHO.
NET FILE 1>NUL 2>NUL & IF ERRORLEVEL 1 (ECHO You must right-click and select &
  ECHO "RUN AS ADMINISTRATOR"  to run this batch. Exiting... & ECHO. &
  PAUSE & EXIT /D)
REM ... proceed here with admin rights ...

This way, the user has to right-click and select "Run as administrator". The script will proceed after the REM statement if it detects administrator rights, otherwise exit with an error. If you don't require the PAUSE, just remove it. Important: NET FILE [...] EXIT /D) must be on the same line. It is displayed here in multiple lines for better readability!


On some machines, I've encountered issues, which are solved in the new version above already. One was due to different double quote handling, and the other issue was due to the fact that UAC was disabled (set to lowest level) on a Windows 7 machine, hence the script calls itself again and again.

I have fixed this now by stripping the quotes in the path and re-adding them later, and I've added an extra parameter which is added when the script re-launches with elevated rights.

The double quotes are removed by the following (details are here):

setlocal DisableDelayedExpansion
set "batchPath=%~0"
setlocal EnableDelayedExpansion

You can then access the path by using !batchPath!. It doesn't contain any double quotes, so it is safe to say "!batchPath!" later in the script.

The line

if '%1'=='ELEV' (shift & goto gotPrivileges)

checks if the script has already been called by the VBScript script to elevate rights, hence avoiding endless recursions. It removes the parameter using shift.


Update:

  • To avoid having to register the .vbs extension in Windows 10, I have replaced the line
    "%temp%\OEgetPrivileges.vbs"
    by
    "%SystemRoot%\System32\WScript.exe" "%temp%\OEgetPrivileges.vbs"
    in the script above; also added cd /d %~dp0 as suggested by Stephen (separate answer) and by Tomáš Zato (comment) to set script directory as default.

  • Now the script honors command line parameters being passed to it. Thanks to jxmallet, TanisDLJ and Peter Mortensen for observations and inspirations.

  • According to Artjom B.'s hint, I analyzed it and have replaced SHIFT by SHIFT /1, which preserves the file name for the %0 parameter

  • Added del "%temp%\OEgetPrivileges_%batchName%.vbs" to the :gotPrivileges section to clean up (as mlt suggested). Added %batchName% to avoid impact if you run different batches in parallel. Note that you need to use for to be able to take advantage of the advanced string functions, such as %%~nk, which extracts just the filename.

  • Optimized script structure, improvements (added variable vbsGetPrivileges which is now referenced everywhere allowing to change the path or name of the file easily, only delete .vbs file if batch needed to be elevated)

  • In some cases, a different calling syntax was required for elevation. If the script does not work, check the following parameters:
    set cmdInvoke=0
    set winSysFolder=System32
    Either change the 1st parameter to set cmdInvoke=1 and check if that already fixes the issue. It will add cmd.exe to the script performing the elevation.
    Or try to change the 2nd parameter to winSysFolder=Sysnative, this might help (but is in most cases not required) on 64 bit systems. (ADBailey has reported this). "Sysnative" is only required for launching 64-bit applications from a 32-bit script host (e.g. a Visual Studio build process, or script invocation from another 32-bit application).

  • To make it more clear how the parameters are interpreted, I am displaying it now like P1=value1 P2=value2 ... P9=value9. This is especially useful if you need to enclose parameters like paths in double quotes, e.g. "C:\Program Files".

  • If you want to debug the VBS script, you can add the //X parameter to WScript.exe as first parameter, as suggested here (it is described for CScript.exe, but works for WScript.exe too).

Useful links:

The Android emulator is not starting, showing "invalid command-line parameter"

There is currently a problem with R12 where the SDK location cannot contain any spaces.

The default installation location is: C:\Programme Files(x86)\Android\android-sdk. They are currently fixing the problem but you can currently work around it by changing the SDK location path in eclipse to C:\PROGRA~2\Android\android-sdk.

If you are running 32-bit Windows, change the path to C:\PROGRA~1\Android\android-sdk.

Execute specified function every X seconds

Threaded:

    /// <summary>
    /// Usage: var timer = SetIntervalThread(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetIntervalThread(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be disposed.</returns>
    public static System.Threading.Timer SetIntervalThread(Action Act, int Interval)
    {
        TimerStateManager state = new TimerStateManager();
        System.Threading.Timer tmr = new System.Threading.Timer(new TimerCallback(_ => Act()), state, Interval, Interval);
        state.TimerObject = tmr;
        return tmr;
    }

Regular

    /// <summary>
    /// Usage: var timer = SetInterval(DoThis, 1000);
    /// UI Usage: BeginInvoke((Action)(() =>{ SetInterval(DoThis, 1000); }));
    /// </summary>
    /// <returns>Returns a timer object which can be stopped and disposed.</returns>
    public static System.Timers.Timer SetInterval(Action Act, int Interval)
    {
        System.Timers.Timer tmr = new System.Timers.Timer();
        tmr.Elapsed += (sender, args) => Act();
        tmr.AutoReset = true;
        tmr.Interval = Interval;
        tmr.Start();

        return tmr;
    }

jQuery attr() change img src

  1. Function imageMorph will create a new img element therefore the id is removed. Changed to

    $("#wrapper > img")

  2. You should use live() function for click event if you want you rocket lanch again.

Updated demo: http://jsfiddle.net/ynhat/QQRsW/4/

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

Android Failed to install HelloWorld.apk on device (null) Error

If unplugging the device and plugging it back in doesn't work, try increasing the upload timeout to something really huge like 20000 ms. It's at Window ? Preferences ? Android ? DDMS ? "ADB connection time out (ms)".

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

Simplest one to print along with last commit date:

git branch --all  --format='%(committerdate:short) %(refname:short)'|sort

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

I faced same problem and tried above solutions but none of them worked for me. Then I tried following steps and the problem was solved:

  • Go to the project properties.
  • Go to Java Build Path option.
  • Then add *.jar file as external jar.
  • Then go to the order and export option and select the libraries and jars of the project.
  • save the current changes and clean the project and run the project again.

How to terminate a python subprocess launched with shell=True

If you can use psutil, then this works perfectly:

import subprocess

import psutil


def kill(proc_pid):
    process = psutil.Process(proc_pid)
    for proc in process.children(recursive=True):
        proc.kill()
    process.kill()


proc = subprocess.Popen(["infinite_app", "param"], shell=True)
try:
    proc.wait(timeout=3)
except subprocess.TimeoutExpired:
    kill(proc.pid)

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

Image

It also happens because of this issue. I unchecked the jars that needed be exported to the apk and this same thing happened. Please tick the jars that your app Needs to run.

Disabling same-origin policy in Safari

There is an option to disable cross-origin restrictions in Safari 9, different from local file restrictions as mentioned above.

XMLHttpRequest Origin null is not allowed Access-Control-Allow-Origin for file:/// to file:/// (Serverless)

use the 'web server for chrome app'. (you actually have it on your pc, wether you know or not. just search it in cortana!). open it and click 'choose file' choose the folder with your file in it. do not actually select your file. select your files folder then click on the link(s) under the 'choose folder' button.

if it doesnt take you to the file, then add the name of the file to the urs. like this:

   https://127.0.0.1:8887/fileName.txt

link to web server for chrome: click me

Launching a website via windows commandline

To open a URL with the default browser, you can execute:

rundll32 url.dll,FileProtocolHandler https://www.google.com

I had issues with URL parameters with the other solutions. However, this one seemed to work correctly.

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

my case seems to be invalid JRE version.

1.7+ required while I launched with 1.6

plus: I filtered some plugin jars which might be required. so changed to select all

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

Disable antivirus and try. I was also facing that problem... but in my case antivirus was blocking my application when I disabled antivirus it resolved.

How to debug on a real device (using Eclipse/ADT)

Sometimes you need to reset ADB. To do that, in Eclipse, go:

Window>> Show View >> Android (Might be found in the "Other" option)>>Devices

in the device Tab, click the down arrow, and choose reset adb.

Launching Google Maps Directions via an intent on Android

You can Launch Google Maps Directions via an intent on Android through this way

btn_search_route.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String source = et_source.getText().toString();
            String destination = et_destination.getText().toString();

            if (TextUtils.isEmpty(source)) {
                et_source.setError("Enter Soruce point");
            } else if (TextUtils.isEmpty(destination)) {
                et_destination.setError("Enter Destination Point");
            } else {
                String sendstring="http://maps.google.com/maps?saddr=" +
                        source +
                        "&daddr=" +
                        destination;
                Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
                        Uri.parse(sendstring));
                startActivity(intent);
            }
        }

    });

REST API Best practice: How to accept list of parameter values as input

First case:

A normal product lookup would look like this

http://our.api.com/product/1

So Im thinking that best practice would be for you to do this

http://our.api.com/Product/101404,7267261

Second Case

Search with querystring parameters - fine like this. I would be tempted to combine terms with AND and OR instead of using [].

PS This can be subjective, so do what you feel comfortable with.

The reason for putting the data in the url is so the link can pasted on a site/ shared between users. If this isnt an issue, by all means use a JSON/ POST instead.

EDIT: On reflection I think this approach suits an entity with a compound key, but not a query for multiple entities.

"Unable to acquire application service" error while launching Eclipse

delete processcenter.ini at location similar to: C:\IBM\IntegrationDesigner\v8.5\iid and then once IDE comes up, go to windows preference and put in the correct URL.

How to store custom objects in NSUserDefaults

On your Player class, implement the following two methods (substituting calls to encodeObject with something relevant to your own object):

- (void)encodeWithCoder:(NSCoder *)encoder {
    //Encode properties, other class variables, etc
    [encoder encodeObject:self.question forKey:@"question"];
    [encoder encodeObject:self.categoryName forKey:@"category"];
    [encoder encodeObject:self.subCategoryName forKey:@"subcategory"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    if((self = [super init])) {
        //decode properties, other class vars
        self.question = [decoder decodeObjectForKey:@"question"];
        self.categoryName = [decoder decodeObjectForKey:@"category"];
        self.subCategoryName = [decoder decodeObjectForKey:@"subcategory"];
    }
    return self;
}

Reading and writing from NSUserDefaults:

- (void)saveCustomObject:(MyObject *)object key:(NSString *)key {
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:encodedObject forKey:key];
    [defaults synchronize];

}

- (MyObject *)loadCustomObjectWithKey:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *encodedObject = [defaults objectForKey:key];
    MyObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    return object;
}

Code shamelessly borrowed from: saving class in nsuserdefaults

Disable activity slide-in animation when launching new activity?

In my opinion the best answer is to use "overridePendingTransition(0, 0);"

to avoid seeing animation when you want to Intent to an Activity use:

this.startActivity(new Intent(v.getContext(), newactivity.class));
this.overridePendingTransition(0, 0);

and to not see the animation when you press back button Override onPause method in your newactivity

@Override
protected void onPause() {
    super.onPause();
    overridePendingTransition(0, 0);
}

I am not able launch JNLP applications using "Java Web Start"?

In my case, Netbeans automatically creates a .jnlp file that doesn't work and my problem was due to an accidental overwriting of the launch.jnlp file on the server (by the inadequate and incorrect version from Netbeans). This caused a mismatch between the local .jnlp file and the remote .jnlp file, resulting in Java Web Start just quitting after "Verifying application."

So no one else has to waste an hour finding a bug that should be communicated adequately (but isn't) by Java WS.

Android intent for playing video?

I have come across this with the Hero, using what I thought was a published API. In the end, I used a test to see if the intent could be received:

private boolean isCallable(Intent intent) {
    List<ResolveInfo> list = getPackageManager().queryIntentActivities(intent, 
        PackageManager.MATCH_DEFAULT_ONLY);
    return list.size() > 0;
}

In use when I would usually just start the activity:

final Intent intent = new Intent("com.android.camera.action.CROP");
intent.setClassName("com.android.camera", "com.android.camera.CropImage");
if (isCallable(intent)) {
    // call the intent as you intended.
} else {
    // make alternative arrangements.
}

obvious: If you go down this route - using non-public APIs - you must absolutely provide a fallback which you know definitely works. It doesn't have to be perfect, it can be a Toast saying that this is unsupported for this handset/device, but you should avoid an uncaught exception. end obvious.


I find the Open Intents Registry of Intents Protocols quite useful, but I haven't found the equivalent of a TCK type list of intents which absolutely must be supported, and examples of what apps do different handsets.

How to make a phone call in android and come back to my activity when the call is done?

Inside PhoneStateListener after seeing the call is finished better use:

Intent intent = new Intent(CallDispatcherActivity.this, CallDispatcherActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

Where CallDispatcherActivity is the activity where the user has launched a call (to a taxi service dispatcher, in my case). This just removes Android telephony app from the top, the user gets back instead of ugly code I saw here.

Present and dismiss modal view controller

First of all, when you put that code in applicationDidFinishLaunching, it might be the case that controllers instantiated from Interface Builder are not yet linked to your application (so "red" and "blue" are still nil).

But to answer your initial question, what you're doing wrong is that you're calling dismissModalViewControllerAnimated: on the wrong controller! It should be like this:

[blue presentModalViewController:red animated:YES];
[red dismissModalViewControllerAnimated:YES];

Usually the "red" controller should decide to dismiss himself at some point (maybe when a "cancel" button is clicked). Then the "red" controller could call the method on self:

[self dismissModalViewControllerAnimated:YES];

If it still doesn't work, it might have something to do with the fact that the controller is presented in an animation fashion, so you might not be allowed to dismiss the controller so soon after presenting it.

iPhone Debugging: How to resolve 'failed to get the task for process'?

I Had the same issue, but resolved it by following simple following steps :

  1. Make sure you have selected debug rather than release.
  2. In Debug configurations, in project settings, you should have selected developer's profile & no need of specifying the entitlements plist.
  3. Also same setting are there under: Targets: , if not manuall change them to the above for the debug config. It will work.

All the best.

How to resolve 'unrecognized selector sent to instance'?

In the code you posted, you're sending the setDownloadURL: setter to ClassA — that is, the class itself. You want to set the property of an instance.

Stop Visual Studio from launching a new browser window when starting debug?

You can use the Attach To Process function, rather than pressing F5.

This can also allow you to navigate through known working sections without the slowdown of VS debugger loaded underneath.

How to make sure you don't get WCF Faulted state exception?

If the transfer mode is Buffered then make sure that the values of MaxReceivedMessageSize and MaxBufferSize is same. I just resolved the faulted state issue this way after grappling with it for hours and thought i'll post it here if it helps someone.

Can a shell script set environment variables of the calling shell?

Add the -l flag in top of your bash script i.e.

#!/usr/bin/env bash -l

...

export NAME1="VALUE1"
export NAME2="VALUE2"

The values with NAME1 and NAME2 will now have been exported to your current environment, however these changes are not permanent. If you want them to be permanent you need to add them to your .bashrc file or other init file.

From the man pages:

-l Make bash act as if it had been invoked as a login shell (see INVOCATION below).

How do I set Java's min and max heap size through environment variables?

You can't do it using environment variables. It's done via "non standard" options. Run: java -X for details. The options you're looking for are -Xmx and -Xms (this is "initial" heap size, so probably what you're looking for.)

How do I get a Cron like scheduler in Python?

There isn't a "pure python" way to do this because some other process would have to launch python in order to run your solution. Every platform will have one or twenty different ways to launch processes and monitor their progress. On unix platforms, cron is the old standard. On Mac OS X there is also launchd, which combines cron-like launching with watchdog functionality that can keep your process alive if that's what you want. Once python is running, then you can use the sched module to schedule tasks.

Launching an application (.EXE) from C#?

Additionally you will want to use the Environment Variables for your paths if at all possible: http://en.wikipedia.org/wiki/Environment_variable#Default_Values_on_Microsoft_Windows

E.G.

  • %WINDIR% = Windows Directory
  • %APPDATA% = Application Data - Varies alot between Vista and XP.

There are many more check out the link for a longer list.

How to launch multiple Internet Explorer windows/tabs from batch file?

The top answer is almost correct, but you also need to add an ampersand at the end of each line. For example write the batch file:

start /d "~\iexplore.exe" "www.google.com" & 
start /d "~\iexplore.exe" "www.yahoo.com" &
start /d "~\iexplore.exe" "www.blackholesurfer.com" &

The ampersand allows the prompt to return to the shell and launch another tab. This is a windows solution only, but the ampersand has the same effect in linux shell.

How do I start a process from C#?

As suggested by Matt Hamilton, the quick approach where you have limited control over the process, is to use the static Start method on the System.Diagnostics.Process class...

using System.Diagnostics;
...
Process.Start("process.exe");

The alternative is to use an instance of the Process class. This allows much more control over the process including scheduling, the type of the window it will run in and, most usefully for me, the ability to wait for the process to finish.

using System.Diagnostics;
...
Process process = new Process();
// Configure the process using the StartInfo properties.
process.StartInfo.FileName = "process.exe";
process.StartInfo.Arguments = "-n";
process.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
process.Start();
process.WaitForExit();// Waits here for the process to exit.

This method allows far more control than I've mentioned.

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

Note that if you need this in a deployment situation, consider using Java WebStart (with an "ondisk" version, not the network one - possible in Java 6u10 and later) as it allows you to specify the various arguments to the JVM in a cross platform way.

Otherwise you will need an operating system specific launcher which sets the arguments you need.

What Does 'zoom' do in CSS?

Zoom is not included in the CSS specification, but it is supported in IE, Safari 4, Chrome (and you can get a somewhat similar effect in Firefox with -moz-transform: scale(x) since 3.5). See here.

So, all browsers

 zoom: 2;
 zoom: 200%;

will zoom your object in by 2, so it's like doubling the size. Which means if you have

a:hover {
   zoom: 2;
}

On hover, the <a> tag will zoom by 200%.

Like I say, in FireFox 3.5+ use -moz-transform: scale(x), it does much the same thing.

Edit: In response to the comment from thirtydot, I will say that scale() is not a complete replacement. It does not expand in line like zoom does, rather it will expand out of the box and over content, not forcing other content out of the way. See this in action here. Furthermore, it seems that zoom is not supported in Opera.

This post gives a useful insight into ways to work around incompatibilities with scale and workarounds for it using jQuery.

How to get the Power of some Integer in Swift language?

In Swift 5:

extension Int{
    func expo(_ power: Int) -> Int {
        var result = 1
        var powerNum = power
        var tempExpo = self
        while (powerNum != 0){
        if (powerNum%2 == 1){
            result *= tempExpo
        }
        powerNum /= 2
        tempExpo *= tempExpo
        }
        return result
    }
}

Use like this

2.expo(5) // pow(2, 5)

Thanks to @Paul Buis's answer.

How to read a Parquet file into Pandas DataFrame?

Aside from pandas, Apache pyarrow also provides way to transform parquet to dataframe

The code is simple, just type:

import pyarrow.parquet as pq

df = pq.read_table(source=your_file_path).to_pandas()

For more information, see the document from Apache pyarrow Reading and Writing Single Files

Change Title of Javascript Alert

You can't, this is determined by the browser, for the user's safety and security. For example you can't make it say "Virus detected" with a message of "Would you like to quarantine it now?"...at least not as an alert().

There are plenty of JavaScript Modal Dialogs out there though, that are far more customizable than alert().

Spring 3 MVC accessing HttpRequest from controller

@RequestMapping(value="/") public String home(HttpServletRequest request){
    System.out.println("My Attribute :: "+request.getAttribute("YourAttributeName"));
    return "home"; 
}

HTTP get with headers using RestTemplate

Take a look at the JavaDoc for RestTemplate.

There is the corresponding getForObject methods that are the HTTP GET equivalents of postForObject, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.

Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange methods allow you to provide an HttpEntity object representing the details of the request (including headers). The execute methods allow you to specify a RequestCallback from which you can add the headers upon its invocation.

Changing the JFrame title

If your class extends JFrame then use this.setTitle(newTitle.getText());

If not and it contains a JFrame let's say named myFrame, then use myFrame.setTitle(newTitle.getText());

Now that you have posted your program, it is obvious that you need only one JTextField to get the new title. These changes will do the trick:

JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
        hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
        newTitle;

and:

    public void createOptions()
    {
        options = new JPanel();
        options.setLayout(null);
        JLabel labelOptions = new JLabel("Change Company Name:");
        labelOptions.setBounds(120, 10, 150, 20);
        options.add(labelOptions);
        newTitle = new JTextField("Some Title");
        newTitle.setBounds(80, 40, 225, 20);
        options.add(newTitle);
//        myTitle = new JTextField("My Title...");
//        myTitle.setBounds(80, 40, 225, 20);
//        myTitle.add(labelOptions);
        JButton newName = new JButton("Set New Name");
        newName.setBounds(60, 80, 150, 20);
        newName.addActionListener(this);
        options.add(newName);
        JButton Exit = new JButton("Exit");
        Exit.setBounds(250, 80, 80, 20);
        Exit.addActionListener(this);
        options.add(Exit);
    }

and:

private void New_Name()
{
    this.setTitle(newTitle.getText());
}

What's the difference between "app.render" and "res.render" in express.js?

along with these two variants, there is also jade.renderFile which generates html that need not be passed to the client.

usage-

var jade = require('jade');

exports.getJson = getJson;

function getJson(req, res) {
    var html = jade.renderFile('views/test.jade', {some:'json'});
    res.send({message: 'i sent json'});
}

getJson() is available as a route in app.js.

How do I put double quotes in a string in vba?

I find the easiest way is to double up on the quotes to handle a quote.

Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0,"""",Sheet1!A1)" 

Some people like to use CHR(34)*:

Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)" 

*Note: CHAR() is used as an Excel cell formula, e.g. writing "=CHAR(34)" in a cell, but for VBA code you use the CHR() function.

How to make canvas responsive

You can have a responsive canvas in 3 short and simple steps:

  1. Remove the width and height attributes from your <canvas>.

    <canvas id="responsive-canvas"></canvas>
    
  2. Using CSS, set the width of your canvas to 100%.

    #responsive-canvas {
      width: 100%;
    }
    
  3. Using JavaScript, set the height to some ratio of the width.

    var canvas = document.getElementById('responsive-canvas');
    var heightRatio = 1.5;
    canvas.height = canvas.width * heightRatio;
    

Property 'value' does not exist on type 'Readonly<{}>'

The problem is you haven't declared your interface state replace any with your suitable variable type of the 'value'

Here is a good reference

interface AppProps {
   //code related to your props goes here
}

interface AppState {
   value: any
}

class App extends React.Component<AppProps, AppState> {
  // ...
}

Create timestamp variable in bash script

ISO 8601 format (2018-12-23T12:34:56) is more readable than UNIX timestamp. However on some OSs you cannot have : in the filenames. Therefore I recommend using something like this instead:

2018-12-23_12-34-56

You can use the following command to get the timestamp in this format:

TIMESTAMP=`date +%Y-%m-%d_%H-%M-%S`

This is the format I have seen many applications use. Another nice thing about this is that if your file names start with this, you can sort them alphabetically and they would be sorted by date.

Display PDF within web browser

The simple solution is to put it in an iframe and hope that the user has a plug-in that supports it.

(I don't, the Acrobat plugin has been such a resource hog and source of instability that I make a point to remove it from any browser that it touches).

The complicated, but relative popular solution is to display it in a flash applet.

including parameters in OPENQUERY

declare @p_Id varchar(10)
SET @p_Id = '40381'

EXECUTE ('BEGIN update TableName
                set     ColumnName1 = null,
                        ColumnName2 = null,
                        ColumnName3 = null,
                        ColumnName4 = null
                 where   PERSONID = '+ @p_Id +'; END;') AT [linked_Server_Name]

Does mobile Google Chrome support browser extensions?

You can use bookmarklets (javascript code in a bookmark) - this also means they sync across devices.

I have loads - I prefix the name with zzz, so they are eazy to type in to the address bar and show in drop down predictions.

To get them to operate on a page you need to go to the page and then in the address bar type the bookmarklet name - this will cause the bookmarklet to execute in the context of the page.

edit

Just to highlight - for this to work, the bookmarklet name must be typed into the address bar while the page you want to operate in is being displayed - if you go off to select the bookmarklet in some other way the page context gets lost, and the bookmarklet operates on a new empty page.

I use zzzpocket - send to pocket. zzztwitter tweet this page zzzmail email this page zzzpressthis send this page to wordpress zzztrello send this page to trello and more...

and it works in chrome whatever platform I am currently logged on to.

How to encrypt and decrypt String with my passphrase in Java (Pc not mobile platform)?

package com.example;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class StrongAES 
{
    public void run() 
    {
        try 
        {
            String text = "Hello World";
            String key = "Bar12345Bar12345"; // 128 bit key
            // Create key and cipher
            Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            // encrypt the text
            cipher.init(Cipher.ENCRYPT_MODE, aesKey);
            byte[] encrypted = cipher.doFinal(text.getBytes());
            System.err.println(new String(encrypted));
            // decrypt the text
            cipher.init(Cipher.DECRYPT_MODE, aesKey);
            String decrypted = new String(cipher.doFinal(encrypted));
            System.err.println(decrypted);
        }
        catch(Exception e) 
        {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) 
    {
        StrongAES app = new StrongAES();
        app.run();
    }
}

DLL Load Library - Error Code 126

This can also happen when you're trying to load a DLL and that in turn needs another DLL which cannot be not found.

package javax.servlet.http does not exist

The solution that work for is were add the next dependency to my pom.xml file.

<dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
</dependency>

form serialize javascript (no framework)

HTMLElement.prototype.serialize = function(){
    var obj = {};
    var elements = this.querySelectorAll( "input, select, textarea" );
    for( var i = 0; i < elements.length; ++i ) {
        var element = elements[i];
        var name = element.name;
        var value = element.value;

        if( name ) {
            obj[ name ] = value;
        }
    }
    return JSON.stringify( obj );
}

To use like this:

var dataToSend = document.querySelector("form").serialize();

I hope I have helped.

arranging div one below the other

If you want the two divs to be displayed one above the other, the simplest answer is to remove the float: left;from the css declaration, as this causes them to collapse to the size of their contents (or the css defined size), and, well float up against each other.

Alternatively, you could simply add clear:both; to the divs, which will force the floated content to clear previous floats.

What is phtml, and when should I use a .phtml extension rather than .php?

There is usually no difference, as far as page rendering goes. It's a huge facility developer-side, though, when your web project grows bigger.

I make use of both in this fashion:

  • .PHP Page doesn't contain view-related code
  • .PHTML Page contains little (if any) data logic and the most part of it is presentation-related

Detect if user is scrolling

Use an interval to check

You can setup an interval to keep checking if the user has scrolled then do something accordingly.

Borrowing from the great John Resig in his article.

Example:

    let didScroll = false;

    window.onscroll = () => didScroll = true;

    setInterval(() => {
        if ( didScroll ) {
            didScroll = false;
            console.log('Someone scrolled me!')
        }
    }, 250);

See live example

What are the most-used vim commands/keypresses?

tuxfiles.org holds a pretty good cheat sheet. I think there are a couple of points to learning the commands:

  • Read the cheat sheet regularly. Don't worry about using all of them, or remembering all the keys, just know that the command exists. Look up the command and use it when you find yourself doing something repetitive.
  • If you find yourself doing something regularly (like deleting an entire line after a particular character d$), go a quick google search to see if you can find a command for it.
  • Write down commands you think you'll find useful and keep that list where you can see it while you're writing your code. I would argue against printing something out and instead encourage you to use post it notes for just a few commands at a time.
  • If possible, watch other programmers use vim, and ask them what commands they are using as you see them do something interesting.

Besides these tips, there are some basic concepts you should understand.

  • vim will use the same character to represent the same function. For example, to delete a line after a character use d$. To highlight a line after a particular character use v$. So notice that $ indicates you will be doing something to the end of the line from where your cursor currently is.
  • u is undo, and ctrl+r is redo.
  • putting a number in front of a command will execute it repeatedly. 3dd will delete the line your cursor is on and the two lines that follow, similarly 3yy will copy the line your cursor is on and the two lines that follow.
  • understand how to navigate through the buffers use :ls to list the buffers, and :bn, :bp to cycle through them.
  • read through the tutorial found in :help This is probably the best way to 'learn the ropes', and the rest of the commands you will learn through usage.

ImportError: No module named 'Queue'

In my case it should be:

from multiprocessing import JoinableQueue

Since in python2, Queue has methods like .task_done(), but in python3 multiprocessing.Queue doesn't have this method, and multiprocessing.JoinableQueue does.

Normalizing a list of numbers in Python

Use :

norm = [float(i)/sum(raw) for i in raw]

to normalize against the sum to ensure that the sum is always 1.0 (or as close to as possible).

use

norm = [float(i)/max(raw) for i in raw]

to normalize against the maximum

Fixed position but relative to container

With pure CSS you can't manage to do it; at least I haven't. However you can do it with jQuery very simply. I'll explain my problem, and with a little change you can use it.

So for a start, I wanted my element to have a fixed top (from top of the window), and a left component to inherit from the parent element (because the parent element is centered). To set the left component, just put your element into the parent and set position:relative for the parent element.

Then you need to know how much from the top your element is when the a scroll bar is on top (y zero scrolled); there are two options again. First is that is static (some number) or you have to read it from the parent element.

In my case it's 150 pixels from top static. So when you see 150 it's how much is the element from the top when we haven't scrolled.

CSS

#parent-element{position:relative;}
#promo{position:absolute;}

jQuery

$(document).ready(function() { //This check window scroll bar location on start
    wtop=parseInt($(window).scrollTop());
    $("#promo").css('top',150+wtop+'px');

});
$(window).scroll(function () { //This is when the window is scrolling
    wtop=parseInt($(window).scrollTop());
    $("#promo").css('top',150+wtop+'px');
});

Checking if a key exists in a JavaScript object?

For those which have lodash included in their project:
There is a lodash _.get method which tries to get "deep" keys:

Gets the value at path of object. If the resolved value is undefined, the defaultValue is returned in its place.

_x000D_
_x000D_
var object = { 'a': [{ 'b': { 'c': 3 } }] };_x000D_
_x000D_
console.log(_x000D_
  _.get(object, 'a[0].b.c'),           // => 3_x000D_
  _.get(object, ['a', '0', 'b', 'c']), // => 3_x000D_
  _.get(object, 'a.b.c'),              // => undefined _x000D_
  _.get(object, 'a.b.c', 'default')    // => 'default'_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_


This will effectively check if that key, however deep, is defined and will not throw an error which might harm the flow of your program if that key is not defined.

Difference between Git and GitHub

Git — The version control tool that GitHub is built on top of.

GitHub — Our company and the name of our software. We build software and websites to help you interact with Git repositories in a nice way.

GitHub.com — The website you log into to view repositories online.

GitHub Desktop — An application that you can install on your computer to help you synchronize local code with GitHub.com.

source: https://guides.github.com/introduction/getting-your-project-on-github/

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed

Here is a Powershell alternative to @UuDdLrLrSs answer.

Get-Service workstation | Restart-Service -Force

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

What is the Difference Between read() and recv() , and Between send() and write()?

"Performance and speed"? Aren't those kind of ... synonyms, here?

Anyway, the recv() call takes flags that read() doesn't, which makes it more powerful, or at least more convenient. That is one difference. I don't think there is a significant performance difference, but haven't tested for it.

Preserve line breaks in angularjs

I had a similar problem to you. I'm not that keen on the other answers here because they don't really allow you to style the newline behaviour very easily. I'm not sure if you have control over the original data, but the solution I adopted was to switch "items" from being an array of strings to being an array of arrays, where each item in the second array contained a line of text. That way you can do something like:

<div ng-repeat="item in items">
  <p ng-repeat="para in item.description">
     {{para}}
  </p>
</div>

This way you can apply classes to the paragraphs and style them nicely with CSS.

Where and how is the _ViewStart.cshtml layout file linked?

From ScottGu's blog:

Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

Also see this.


In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

Wikipedia

There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

How to select rows for a specific date, ignoring time in SQL Server

You can remove the time component when comparing:

SELECT * 
FROM sales 
WHERE CONVERT(DATETIME, FLOOR(CONVERT(FLOAT, salesDate))) = '11/11/2010'

Another approach is to change the select to cover all the time between the start and end of the date:

SELECT * 
FROM sales 
-- WHERE salesDate BETWEEN '11/11/2010 00:00:00.00' AND '11/11/2010 23:59:59.999'
WHERE salesDate BETWEEN '2020-05-18T00:00:00.00' AND '2020-05-18T23:59:59.999'

SQL - Update multiple records in one query

Assuming you have the list of values to update in an Excel spreadsheet with config_value in column A1 and config_name in B1 you can easily write up the query there using an Excel formula like

=CONCAT("UPDATE config SET config_value = ","'",A1,"'", " WHERE config_name = ","'",B1,"'")

How to import a csv file using python with headers intact, where first column is a non-numerical

Python's csv module handles data row-wise, which is the usual way of looking at such data. You seem to want a column-wise approach. Here's one way of doing it.

Assuming your file is named myclone.csv and contains

workers,constant,age
w0,7.334,-1.406
w1,5.235,-4.936
w2,3.2225,-1.478
w3,0,0

this code should give you an idea or two:

>>> import csv
>>> f = open('myclone.csv', 'rb')
>>> reader = csv.reader(f)
>>> headers = next(reader, None)
>>> headers
['workers', 'constant', 'age']
>>> column = {}
>>> for h in headers:
...    column[h] = []
...
>>> column
{'workers': [], 'constant': [], 'age': []}
>>> for row in reader:
...   for h, v in zip(headers, row):
...     column[h].append(v)
...
>>> column
{'workers': ['w0', 'w1', 'w2', 'w3'], 'constant': ['7.334', '5.235', '3.2225', '0'], 'age': ['-1.406', '-4.936', '-1.478', '0']}
>>> column['workers']
['w0', 'w1', 'w2', 'w3']
>>> column['constant']
['7.334', '5.235', '3.2225', '0']
>>> column['age']
['-1.406', '-4.936', '-1.478', '0']
>>>

To get your numeric values into floats, add this

converters = [str.strip] + [float] * (len(headers) - 1)

up front, and do this

for h, v, conv in zip(headers, row, converters):
  column[h].append(conv(v))

for each row instead of the similar two lines above.

SQL Stored Procedure set variables using SELECT

One advantage your current approach does have is that it will raise an error if multiple rows are returned by the predicate. To reproduce that you can use.

SELECT @currentTerm = currentterm,
       @termID = termid,
       @endDate = enddate
FROM   table1
WHERE  iscurrent = 1

IF( @@ROWCOUNT <> 1 )
  BEGIN
      RAISERROR ('Unexpected number of matching rows',
                 16,
                 1)

      RETURN
  END  

javascript regex : only english letters allowed

Another option is to use the case-insensitive flag i, then there's no need for the extra character range A-Z.

var reg = /^[a-z]+$/i;
console.log( reg.test("somethingELSE") ); //true
console.log( "somethingELSE".match(reg)[0] ); //"somethingELSE"

Here's a DEMO on how this regex works with test() and match().

How to update Android Studio automatically?

for windows users go to HELP> CHECK FOR UPDATES>UPDATE(click the link updates)

How to view method information in Android Studio?

Update Android Studio 4.1 & 4.2, this checkbox has moved under Editor/General/Code Completion enter image description here

How do you cast a List of supertypes to a List of subtypes?

This should would work

List<TestA> testAList = new ArrayList<>();
List<TestB> testBList = new ArrayList<>()
testAList.addAll(new ArrayList<>(testBList));

How to add message box with 'OK' button?

I think there may be problem that you haven't added click listener for ok positive button.

dlgAlert.setPositiveButton("Ok",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
          //dismiss the dialog  
        }
    });

Can't create project on Netbeans 8.2

I had the same problem I installed NetBeans 8.2 on macOS High Sierra, and by default settings, NetBeans will work with the latest JDK release (currently JDK 9).

NetBeans Problem

What I did was forcing NetBeans to use JDK 8, you must config your netbeans.conf file, you can find it on:

/Applications/NetBeans/NetBeans 8.2.app/Contents/Resources/NetBeans/etc/netbeans.conf

enter image description here

You need to uncomment and update your path to JDK, you will find yours at:

/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home

enter image description here

Just save it, restart NetBeans and you are done!

Make Bootstrap 3 Tabs Responsive

Bootstrap tabs are not responsive out of the box. Responsive, IMO, is a style change, changing functions is Adaptive. There are a few plugins to turn the Bootstrap 3 tabs into a Collapse component. The best and most updated one is : https://github.com/flatlogic/bootstrap-tabcollapse.

Here's one way of implementing it:

DEMO: http://jsbin.com/zibani/1/

EDIT: http://jsbin.com/zibani/1/edit

This turns the content into a collapse component:

enter image description here

Dependencies:

  1. Bootstrap 3.2 css or higher but still in the 3 series
  2. Bootstrap 3.2 jQuery or higher but still in the 3 series
  3. Compatible version of bootstrap-tabcollapse.js

HTML -- same as question with class name addition:

       <ul class="nav nav-tabs content-tabs" id="maincontent" role="tablist">

jQuery:

$(document).ready(function() {

    // DEPENDENCY: https://github.com/flatlogic/bootstrap-tabcollapse
    $('.content-tabs').tabCollapse();

    // initialize tab function
    $('.nav-tabs a').click(function(e) {
        e.preventDefault();
        $(this).tab('show');
    });

});

CSS -- optional for fat fingers and active states:

.panel-heading {
    padding: 0
}
.panel-heading a {
    display: block;
    padding: 20px 10px;
}
.panel-heading a.collapsed {
    background: #fff
}
.panel-heading a {
    background: #f7f7f7;
    border-radius: 5px;
}
.panel-heading a:after {
    content: '-'
}
.panel-heading a.collapsed:after {
    content: '+'
}
.nav.nav-tabs li a,
.nav.nav-tabs li.active > a:hover,
.nav.nav-tabs li.active > a:active,
.nav.nav-tabs li.active > a:focus {
    border-bottom-width: 0px;
    outline: none;
}
.nav.nav-tabs li a {
    padding-top: 20px;
    padding-bottom: 20px;
}
.tab-pane {
    background: #fff;
    padding: 10px;
    border: 1px solid #ddd;
    margin-top: -1px;
}

How to sum the values of one column of a dataframe in spark/scala

You must first import the functions:

import org.apache.spark.sql.functions._

Then you can use them like this:

val df = CSV.load(args(0))
val sumSteps =  df.agg(sum("steps")).first.get(0)

You can also cast the result if needed:

val sumSteps: Long = df.agg(sum("steps").cast("long")).first.getLong(0)

Edit:

For multiple columns (e.g. "col1", "col2", ...), you could get all aggregations at once:

val sums = df.agg(sum("col1").as("sum_col1"), sum("col2").as("sum_col2"), ...).first

Edit2:

For dynamically applying the aggregations, the following options are available:

  • Applying to all numeric columns at once:
df.groupBy().sum()
  • Applying to a list of numeric column names:
val columnNames = List("col1", "col2")
df.groupBy().sum(columnNames: _*)
  • Applying to a list of numeric column names with aliases and/or casts:
val cols = List("col1", "col2")
val sums = cols.map(colName => sum(colName).cast("double").as("sum_" + colName))
df.groupBy().agg(sums.head, sums.tail:_*).show()

Batch files : How to leave the console window open

put at the end it will reopen your console

start cmd 

plot data from CSV file with matplotlib

I'm guessing

x= data[:,0]
y= data[:,1]

Managing SSH keys within Jenkins for Git

Have you tried logging in as the jenkins user?

Try this:

sudo -i -u jenkins #For RedHat you might have to do 'su' instead.
git clone [email protected]:your/repo.git

Often times you see failure if the host has not been added or authorized (hence I always manually login as hudson/jenkins for the first connection to github/bitbucket) but that link you included supposedly fixes that.

If the above doesn't work try recopying the key. Make sure its the pub key (ie id_rsa.pub). Maybe you missed some characters?

AngularJS: factory $http.get JSON file

this answer helped me out a lot and pointed me in the right direction but what worked for me, and hopefully others, is:

menuApp.controller("dynamicMenuController", function($scope, $http) {
$scope.appetizers= [];
$http.get('config/menu.json').success(function(data) { 
    console.log("success!");
    $scope.appetizers = data.appetizers;
        console.log(data.appetizers);
    });    
});

How to correctly display .csv files within Excel 2013?

Another possible problem is that the csv file contains a byte order mark "FEFF". The byte order mark is intended to detect whether the file has been moved from a system using big endian or little endian byte ordering to a system of the opposite endianness. https://en.wikipedia.org/wiki/Byte_order_mark

Removing the "FEFF" byte order mark using a hex editor should allow Excel to read the file.

How do you rename a Git tag?

In addition to the other answers:

First you need to build an alias of the old tag name, pointing to the original commit:

git tag new old^{}

Then you need to delete the old one locally:

git tag -d old

Then delete the tag on you remote location(s):

# Check your remote sources:
git remote -v
# The argument (3rd) is your remote location,
# the one you can see with `git remote`. In this example: `origin`
git push origin :refs/tags/old

Finally you need to add your new tag to the remote location. Until you have done this, the new tag(s) will not be added:

git push origin --tags

Iterate this for every remote location.

Be aware, of the implications that a Git Tag change has to consumers of a package!

Obtain smallest value from array in Javascript?

I find that the easiest way to return the smallest value of an array is to use the Spread Operator on Math.min() function.

_x000D_
_x000D_
return Math.min(...justPrices);_x000D_
//returns 1.5 on example given 
_x000D_
_x000D_
_x000D_

The page on MDN helps to understand it better: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min

A little extra: This also works on Math.max() function

return Math.max(...justPrices); //returns 9.9 on example given.

Hope this helps!

How to correctly dismiss a DialogFragment?

I gave an upvote to Terel's answer. I just wanted to post this for any Kotlin users:

supportFragmentManager.findFragmentByTag(TAG_DIALOG)?.let {
    (it as DialogFragment).dismiss()
}

Google maps API V3 method fitBounds()

This happens because LatLngBounds() does not take two arbitrary points as parameters, but SW and NE points

use the .extend() method on an empty bounds object

var bounds = new google.maps.LatLngBounds();
bounds.extend(myPlace);
bounds.extend(Item_1);
map.fitBounds(bounds);

Demo at http://jsfiddle.net/gaby/22qte/

using batch echo with special characters

You can escape shell metacharacters with ^:

echo ^<?xml version="1.0" encoding="utf-8" ?^> > myfile.xml

Note that since echo is a shell built-in it doesn't follow the usual conventions regarding quoting, so just quoting the argument will output the quotes instead of removing them.

TypeScript-'s Angular Framework Error - "There is no directive with exportAs set to ngForm"

I faced this issue, but none of the answers here worked for me. I googled and found that FormsModule not shared with Feature Modules

So If your form is in a featured module, then you have to import and add the FromsModule there.

Please ref: https://github.com/angular/angular/issues/11365

Shell script - remove first and last quote (") from a variable

If you try to remove quotes because the Makefile keeps them, try this:

$(subst $\",,$(YOUR_VARIABLE))

Based on another answer: https://stackoverflow.com/a/10430975/10452175

Wait for a process to finish

Use inotifywait to monitor some file that gets closed, when your process terminates. Example (on Linux):

yourproc >logfile.log & disown
inotifywait -q -e close logfile.log

-e specifies the event to wait for, -q means minimal output only on termination. In this case it will be:

logfile.log CLOSE_WRITE,CLOSE

A single wait command can be used to wait for multiple processes:

yourproc1 >logfile1.log & disown
yourproc2 >logfile2.log & disown
yourproc3 >logfile3.log & disown
inotifywait -q -e close logfile1.log logfile2.log logfile3.log

The output string of inotifywait will tell you, which process terminated. This only works with 'real' files, not with something in /proc/

How can I solve Exception in thread "main" java.lang.NullPointerException error

This is the problem

double a[] = null;

Since a is null, NullPointerException will arise every time you use it until you initialize it. So this:

a[i] = var;

will fail.

A possible solution would be initialize it when declaring it:

double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7

IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.

java.lang.NullPointerException

This exception means there's a variable with null value being used. How to solve? Just make sure the variable is not null before being used.

at twoten.TwoTenB.(TwoTenB.java:29)

This line has two parts:

  • First, shows the class and method where the error was thrown. In this case, it was at <init> method in class TwoTenB declared in package twoten. When you encounter an error message with SomeClassName.<init>, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
  • Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file TwoTenB.java, line number 29. This seems to be a[i] = var;.

From this line, other lines will be similar to tell you where the error arose. So when reading this:

at javapractice.JavaPractice.main(JavaPractice.java:32)

It means that you were trying to instantiate a TwoTenB object reference inside the main method of your class JavaPractice declared in javapractice package.

Correct way to initialize HashMap and can HashMap hold different value types?

Map.of literals

As of Java 9, there is yet another way to instantiate a Map. You can create an unmodifiable map from zero, one, or several pairs of objects in a single-line of code. This is quite convenient in many situations.

For an empty Map that cannot be modified, call Map.of(). Why would you want an empty set that cannot be changed? One common case is to avoid returning a NULL where you have no valid content.

For a single key-value pair, call Map.of( myKey , myValue ). For example, Map.of( "favorite_color" , "purple" ).

For multiple key-value pairs, use a series of key-value pairs. ``Map.of( "favorite_foreground_color" , "purple" , "favorite_background_color" , "cream" )`.

If those pairs are difficult to read, you may want to use Map.of and pass Map.Entry objects.

Note that we get back an object of the Map interface. We do not know the underlying concrete class used to make our object. Indeed, the Java team is free to used different concrete classes for different data, or to vary the class in future releases of Java.

The rules discussed in other Answers still apply here, with regard to type-safety. You declare your intended types, and your passed objects must comply. If you want values of various types, use Object.

Map< String , Color > preferences = Map.of( "favorite_color" , Color.BLUE ) ;

Insert line at middle of file with Python?

There is a combination of techniques which I found useful in solving this issue:

with open(file, 'r+') as fd:
    contents = fd.readlines()
    contents.insert(index, new_string)  # new_string should end in a newline
    fd.seek(0)  # readlines consumes the iterator, so we need to start over
    fd.writelines(contents)  # No need to truncate as we are increasing filesize

In our particular application, we wanted to add it after a certain string:

with open(file, 'r+') as fd:
    contents = fd.readlines()
    if match_string in contents[-1]:  # Handle last line to prevent IndexError
        contents.append(insert_string)
    else:
        for index, line in enumerate(contents):
            if match_string in line and insert_string not in contents[index + 1]:
                contents.insert(index + 1, insert_string)
                break
    fd.seek(0)
    fd.writelines(contents)

If you want it to insert the string after every instance of the match, instead of just the first, remove the else: (and properly unindent) and the break.

Note also that the and insert_string not in contents[index + 1]: prevents it from adding more than one copy after the match_string, so it's safe to run repeatedly.

How to use MySQL DECIMAL?

MySQL 5.x specification for decimal datatype is: DECIMAL[(M[,D])] [UNSIGNED] [ZEROFILL]. The answer above is wrong (now corrected) in saying that unsigned decimals are not possible.

To define a field allowing only unsigned decimals, with a total length of 6 digits, 4 of which are decimals, you would use: DECIMAL (6,4) UNSIGNED.

You can likewise create unsigned (ie. not negative) FLOAT and DOUBLE datatypes.


Update on MySQL 8.0.17+, as in MySQL 8 Manual: 11.1.1 Numeric Data Type Syntax:

"Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.*

As of MySQL 8.0.17, the UNSIGNED attribute is deprecated for columns of type FLOAT, DOUBLE, and DECIMAL (and any synonyms); you should expect support for it to be removed in a future version of MySQL. Consider using a simple CHECK constraint instead for such columns.

C# Error "The type initializer for ... threw an exception

I got this error when I modified an Nlog configuration file and didn't format the XML correctly.

Is there a way to follow redirects with command line cURL?

I had a similar problem. I am posting my solution here because I believe it might help one of the commenters.

For me, the obstacle was that the page required a login and then gave me a new URL through javascript. Here is what I had to do:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <URL>

Note that j_username and j_password is the name of the fields for my website's login form. You will have to open the source of the webpage to see what the 'name' of the username field and the 'name' of the password field is in your case. After that I go an html file with java script in which the new URL was embedded. After parsing this out just resubmit with the new URL:

curl -c cookiejar -g -O -J -L -F "j_username=username" -F "j_password=password" <NEWURL>

How can I print out just the index of a pandas dataframe?

You can access the index attribute of a df using df.index[i]

>> import pandas as pd
>> import numpy as np
>> df = pd.DataFrame({'a':np.arange(5), 'b':np.random.randn(5)})
   a         b
0  0  1.088998
1  1 -1.381735
2  2  0.035058
3  3 -2.273023
4  4  1.345342

>> df.index[1] ## Second index
>> df.index[-1] ## Last index

>> for i in xrange(len(df)):print df.index[i] ## Using loop
... 
0
1
2
3
4

How to show Bootstrap table with sort icon

Use this icons with bootstrap (glyphicon):

<span class="glyphicon glyphicon-triangle-bottom"></span>
<span class="glyphicon glyphicon-triangle-top"></span>

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h

http://www.w3schools.com/bootstrap/tryit.asp?filename=trybs_ref_glyph_triangle-bottom&stacked=h

How to resolve "gpg: command not found" error during RVM installation?

You can also use:

$ sudo gem install rvm

It should give you the following output:

Fetching: rvm-1.11.3.9.gem (100%)
Successfully installed rvm-1.11.3.9
Parsing documentation for rvm-1.11.3.9
Installing ri documentation for rvm-1.11.3.9
1 gem installed

How do you use https / SSL on localhost?

If you have IIS Express (with Visual Studio):

To enable the SSL within IIS Express, you have to just set “SSL Enabled = true” in the project properties window.

See the steps and pictures at this code project.

IIS Express will generate a certificate for you (you'll be prompted for it, etc.). Note that depending on configuration the site may still automatically start with the URL rather than the SSL URL. You can see the SSL URL - note the port number and replace it in your browser address bar, you should be able to get in and test.

From there you can right click on your project, click property pages, then start options and assign the start URL - put the new https with the new port (usually 44301 - notice the similarity to port 443) and your project will start correctly from then on.

enter image description here

Change URL parameters

Here I have taken Adil Malik's answer and fixed the 3 issues I identified with it.

/**
 * Adds or updates a URL parameter.
 *
 * @param {string} url  the URL to modify
 * @param {string} param  the name of the parameter
 * @param {string} paramVal  the new value for the parameter
 * @return {string}  the updated URL
 */
self.setParameter = function (url, param, paramVal){
  // http://stackoverflow.com/a/10997390/2391566
  var parts = url.split('?');
  var baseUrl = parts[0];
  var oldQueryString = parts[1];
  var newParameters = [];
  if (oldQueryString) {
    var oldParameters = oldQueryString.split('&');
    for (var i = 0; i < oldParameters.length; i++) {
      if(oldParameters[i].split('=')[0] != param) {
        newParameters.push(oldParameters[i]);
      }
    }
  }
  if (paramVal !== '' && paramVal !== null && typeof paramVal !== 'undefined') {
    newParameters.push(param + '=' + encodeURI(paramVal));
  }
  if (newParameters.length > 0) {
    return baseUrl + '?' + newParameters.join('&');
  } else {
    return baseUrl;
  }
}

Drop all tables whose names begin with a certain string

On Oracle XE this works:

SELECT 'DROP TABLE "' || TABLE_NAME || '";'
FROM USER_TABLES
WHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'

Or if you want to remove the constraints and free up space as well, use this:

SELECT 'DROP TABLE "' || TABLE_NAME || '" cascade constraints PURGE;'
FROM USER_TABLES
WHERE TABLE_NAME LIKE 'YOURTABLEPREFIX%'

Which will generate a bunch of DROP TABLE cascade constraints PURGE statements...

For VIEWS use this:

SELECT 'DROP VIEW "' || VIEW_NAME || '";'
FROM USER_VIEWS
WHERE VIEW_NAME LIKE 'YOURVIEWPREFIX%'

HTTP POST with URL query parameters -- good idea or not?

From a programmatic standpoint, for the client it's packaging up parameters and appending them onto the url and conducting a POST vs. a GET. On the server-side, it's evaluating inbound parameters from the querystring instead of the posted bytes. Basically, it's a wash.

Where there could be advantages/disadvantages might be in how specific client platforms work with POST and GET routines in their networking stack, as well as how the web server deals with those requests. Depending on your implementation, one approach may be more efficient than the other. Knowing that would guide your decision here.

Nonetheless, from a programmer's perspective, I prefer allowing either a POST with all parameters in the body, or a GET with all params on the url, and explicitly ignoring url parameters with any POST request. It avoids confusion.

enum Values to NSString (iOS)

I found this website (from which the example below is taken) which provides an elegant solution to this problem. The original posting though comes from this StackOverflow answer.

// Place this in your .h file, outside the @interface block
typedef enum {
    JPG,
    PNG,
    GIF,
    PVR
} kImageType;
#define kImageTypeArray @"JPEG", @"PNG", @"GIF", @"PowerVR", nil

...

// Place this in the .m file, inside the @implementation block
// A method to convert an enum to string
-(NSString*) imageTypeEnumToString:(kImageType)enumVal
{
    NSArray *imageTypeArray = [[NSArray alloc] initWithObjects:kImageTypeArray];
    return [imageTypeArray objectAtIndex:enumVal];
}

// A method to retrieve the int value from the NSArray of NSStrings
-(kImageType) imageTypeStringToEnum:(NSString*)strVal
{
    NSArray *imageTypeArray = [[NSArray alloc] initWithObjects:kImageTypeArray];
    NSUInteger n = [imageTypeArray indexOfObject:strVal];
    if(n < 1) n = JPG;
    return (kImageType) n;
}

Difference between text and varchar (character varying)

In my opinion, varchar(n) has it's own advantages. Yes, they all use the same underlying type and all that. But, it should be pointed out that indexes in PostgreSQL has its size limit of 2712 bytes per row.

TL;DR: If you use text type without a constraint and have indexes on these columns, it is very possible that you hit this limit for some of your columns and get error when you try to insert data but with using varchar(n), you can prevent it.

Some more details: The problem here is that PostgreSQL doesn't give any exceptions when creating indexes for text type or varchar(n) where n is greater than 2712. However, it will give error when a record with compressed size of greater than 2712 is tried to be inserted. It means that you can insert 100.000 character of string which is composed by repetitive characters easily because it will be compressed far below 2712 but you may not be able to insert some string with 4000 characters because the compressed size is greater than 2712 bytes. Using varchar(n) where n is not too much greater than 2712, you're safe from these errors.

How to generate sample XML documents from their DTD or XSD?

For Intellij Idea users:

Have a look at Tools -> XML Actions

enter image description here

Seems to work very well (as far as I have tested).

Edit:

As mentioned by @naXa, you can now also right-click on the XSD file and click "Generate XML Document from XSD Schema..."

How to select an element inside "this" in jQuery?

$( this ).find( 'li.target' ).css("border", "3px double red");

or

$( this ).children( 'li.target' ).css("border", "3px double red");

Use children for immediate descendants, or find for deeper elements.

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

Yes. Bootstrap uses CSS transitions so it can be done easily without any Javascript. Just use CSS3. Please take a look at

carousel.carousel-fade

in the CSS of the following examples:

What does "&" at the end of a linux command mean?

In addition, you can use the "&" sign to run many processes through one (1) ssh connections in order to to keep minimum number of terminals. For example, I have one process that listens for messages in order to extract files, the second process listens for messages in order to upload files: Using the "&" I can run both services in one terminal, through single ssh connection to my server.


*****I just realized that these processes running through the "&" will also "stay alive" after ssh session is closed! pretty neat and useful if your connection to the server is interrupted**

How to check if a process id (PID) exists

It seems like you want

wait $PID

which will return when $pid finishes.

Otherwise you can use

ps -p $PID

to check if the process is still alive (this is more effective than kill -0 $pid because it will work even if you don't own the pid).

JavaScript null check

In your case use data==null (which is true ONLY for null and undefined - on second picture focus on rows/columns null-undefined)

_x000D_
_x000D_
function test(data) {_x000D_
    if (data != null) {_x000D_
        console.log('Data: ', data);_x000D_
    }_x000D_
}_x000D_
_x000D_
test();          // the data=undefined_x000D_
test(null);      // the data=null_x000D_
test(undefined); // the data=undefined_x000D_
_x000D_
test(0); _x000D_
test(false); _x000D_
test('something');
_x000D_
_x000D_
_x000D_

Here you have all (src):

if

enter image description here

== (its negation !=)

enter image description here

=== (its negation !==)

enter image description here

Bootstrap datepicker hide after selection

  1. Simply open the bootstrap-datepicker.js
  2. find : var defaults = $.fn.datepicker.defaults
  3. set autoclose: true

Save and refresh your project and this should do.

How to use index in select statement?

If you want to test the index to see if it works, here is the syntax:

SELECT *
FROM Table WITH(INDEX(Index_Name))

The WITH statement will force the index to be used.

Extracting text from a PDF file using PDFMiner in python?

This works in May 2020 using PDFminer six in Python3.

Installing the package

$ pip install pdfminer.six

Importing the package

from pdfminer.high_level import extract_text

Using a PDF saved on disk

text = extract_text('report.pdf')

Or alternatively:

with open('report.pdf','rb') as f:
    text = extract_text(f)

Using PDF already in memory

If the PDF is already in memory, for example if retrieved from the web with the requests library, it can be converted to a stream using the io library:

import io

response = requests.get(url)
text = extract_text(io.BytesIO(response.content))

Performance and Reliability compared with PyPDF2

PDFminer.six works more reliably than PyPDF2 (which fails with certain types of PDFs), in particular PDF version 1.7

However, text extraction with PDFminer.six is significantly slower than PyPDF2 by a factor of 6.

I timed text extraction with timeit on a 15" MBP (2018), timing only the extraction function (no file opening etc.) with a 10 page PDF and got the following results:

PDFminer.six: 2.88 sec
PyPDF2:       0.45 sec

pdfminer.six also has a huge footprint, requiring pycryptodome which needs GCC and other things installed pushing a minimal install docker image on Alpine Linux from 80 MB to 350 MB. PyPDF2 has no noticeable storage impact.

Running EXE with parameters

To start the process with parameters, you can use following code:

string filename = Path.Combine(cPath,"HHTCtrlp.exe");
var proc = System.Diagnostics.Process.Start(filename, cParams);

To kill/exit the program again, you can use following code:

proc.CloseMainWindow(); 
proc.Close();

Strip spaces/tabs/newlines - python

If you want to remove multiple whitespace items and replace them with single spaces, the easiest way is with a regexp like this:

>>> import re
>>> myString="I want to Remove all white \t spaces, new lines \n and tabs \t"
>>> re.sub('\s+',' ',myString)
'I want to Remove all white spaces, new lines and tabs '

You can then remove the trailing space with .strip() if you want to.

How do I center text vertically and horizontally in Flutter?

                       child: Align(
                          alignment: Alignment.center,
                          child: Text(
                            'Text here',
                            textAlign: TextAlign.center,                          
                          ),
                        ),

This produced the best result for me.

How Best to Compare Two Collections in Java and Act on Them?

For a set that small is generally not worth it to convert from an Array to a HashMap/set. In fact, you're probably best off keeping them in an array and then sorting them by key and iterating over both lists simultaneously to do the comparison.

How to split a string into a list?

I want my python function to split a sentence (input) and store each word in a list

The str().split() method does this, it takes a string, splits it into a list:

>>> the_string = "this is a sentence"
>>> words = the_string.split(" ")
>>> print(words)
['this', 'is', 'a', 'sentence']
>>> type(words)
<type 'list'> # or <class 'list'> in Python 3.0

The problem you're having is because of a typo, you wrote print(words) instead of print(word):

Renaming the word variable to current_word, this is what you had:

def split_line(text):
    words = text.split()
    for current_word in words:
        print(words)

..when you should have done:

def split_line(text):
    words = text.split()
    for current_word in words:
        print(current_word)

If for some reason you want to manually construct a list in the for loop, you would use the list append() method, perhaps because you want to lower-case all words (for example):

my_list = [] # make empty list
for current_word in words:
    my_list.append(current_word.lower())

Or more a bit neater, using a list-comprehension:

my_list = [current_word.lower() for current_word in words]

taking input of a string word by word

Put the line in a stringstream and extract word by word back:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    string t;
    getline(cin,t);

    istringstream iss(t);
    string word;
    while(iss >> word) {
        /* do stuff with word */
    }
}

Of course, you can just skip the getline part and read word by word from cin directly.

And here you can read why is using namespace std considered bad practice.

Eclipse C++ : "Program "g++" not found in PATH"

You need a gcc, g++ compiler toolchain (on your windows machine) for the eclipse which you have manually downloaded, One of the options can be done implicit via cygwin installation(by selecting proper development packages for gcc, g++) and then add the location of the compiled gcc ,g++ package like C:\cygwin\etc\alternatives to the PATH variable for windows environment.

After this open eclipse and go to Project->properties->C/C++ Tool Chain Editor and add replace default GNU C++ compiler and GNU C Compiler with Cygwin C++ compiler and Cygwin C compiler and rebuild the project. The errors related to gcc, g++ PATH not found will now be gone.

How to merge a list of lists with same type of items to a single list of items?

For List<List<List<x>>> and so on, use

list.SelectMany(x => x.SelectMany(y => y)).ToList();

This has been posted in a comment, but it does deserves a separate reply in my opinion.

Error creating bean with name 'entityManagerFactory

This sounds like a ClassLoader conflict. I'd bet you have the javax.persistence api 1.x on the classpath somewhere, whereas Spring is trying to access ValidationMode, which was only introduced in JPA 2.0.

Since you use Maven, do mvn dependency:tree, find the artifact:

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>persistence-api</artifactId>
    <version>1.0</version>
</dependency>

And remove it from your setup. (See Excluding Dependencies)

AFAIK there is no such general distribution for JPA 2, but you can use this Hibernate-specific version:

<dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.0-api</artifactId>
    <version>1.0.1.Final</version>
</dependency>

OK, since that doesn't work, you still seem to have some JPA-1 version in there somewhere. In a test method, add this code:

System.out.println(EntityManager.class.getProtectionDomain()
                                      .getCodeSource()
                                      .getLocation());

See where that points you and get rid of that artifact.


Ahh, now I finally see the problem. Get rid of this:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jpa</artifactId>
    <version>2.0.8</version>
</dependency>

and replace it with

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>3.2.5.RELEASE</version>
</dependency>

On a different note, you should set all test libraries (spring-test, easymock etc.) to

<scope>test</scope>

The input is not a valid Base-64 string as it contains a non-base 64 character

Remove the unnecessary string through Regex

Regex regex=new Regex(@"^[\w/\:.-]+;base64,");
base64File=regex.Replace(base64File,string.Empty);

"make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)

I meet the problem in windows7, phpeclipse, when I start the XAMPP. My solution is :

  • 1.Commented out the \xampp\apache\conf\httpd.conf -> line171 -> #LoadModule ssl_module modules/mod_ssl.so

  • 2.line539 -> #Include conf/extra/httpd-ssl.conf

or you can change the 443 port to another one

Can I set subject/content of email using mailto:?

Yes, you can like this:

mailto: [email protected]?subject=something

How to Set Focus on Input Field using JQuery

If the input happens to be in a bootstrap modal dialog, the answer is different. Copying from How to Set focus to first text input in a bootstrap modal after shown this is what is required:

$('#myModal').on('shown.bs.modal', function () {
  $('#textareaID').focus();
})  

From inside of a Docker container, how do I connect to the localhost of the machine?

For those on Windows, assuming you're using the bridge network driver, you'll want to specifically bind MySQL to the ip address of the hyper-v network interface.

This is done via the configuration file under the normally hidden C:\ProgramData\MySQL folder.

Binding to 0.0.0.0 will not work. The address needed is shown in the docker configuration as well, and in my case was 10.0.75.1.

Check if PHP-page is accessed from an iOS device

preg_match("/iPhone|Android|iPad|iPod|webOS/", $_SERVER['HTTP_USER_AGENT'], $matches);
$os = current($matches);

switch($os){
   case 'iPhone': /*do something...*/ break;
   case 'Android': /*do something...*/ break;
   case 'iPad': /*do something...*/ break;
   case 'iPod': /*do something...*/ break;
   case 'webOS': /*do something...*/ break;
}

Python: Adding element to list while iterating

You can use an index and a while loop instead of a for loop if you want the loop to also loop over the elements that is added to the list during the loop:

i = 0
while i < len(myarr):
    a = myarr[i];
    i = i + 1;
    if somecond(a):
        myarr.append(newObj())

Sorting JSON by values

If you don't mind using an external library, Lodash has lots of wonderful utilities

var people = [
  {
     "f_name":"john",
     "l_name":"doe",
     "sequence":"0",
     "title":"president",
     "url":"google.com",
     "color":"333333"
  },
  {
     "f_name":"michael",
     "l_name":"goodyear",
     "sequence":"0",
     "title":"general manager",
     "url":"google.com",
     "color":"333333"
  }
];


var sorted = _.sortBy(people, "l_name")

You can also sort by multiple properties. Here's a plunk showing it in action

Select from multiple tables without a join?

You should try this

 SELECT t1.*,t2.* FROM t1,t2

What is the best method to merge two PHP objects?

I understand that using the generic objects [stdClass()] and casting them as arrays answers the question, but I thought the Compositor was a great answer. Yet I felt it could use some feature enhancements and might be useful for someone else.

Features:

  • Specify reference or clone
  • Specify first or last entry to take precedence
  • Multiple (more than two) object merging with syntax similarity to array_merge
  • Method linking: $obj->f1()->f2()->f3()...
  • Dynamic composites: $obj->merge(...) /* work here */ $obj->merge(...)

Code:

class Compositor {

    protected $composite = array();
    protected $use_reference;
    protected $first_precedence;

    /**
     * __construct, Constructor
     *
     * Used to set options.
     *
     * @param bool $use_reference whether to use a reference (TRUE) or to copy the object (FALSE) [default]
     * @param bool $first_precedence whether the first entry takes precedence (TRUE) or last entry takes precedence (FALSE) [default]
     */
    public function __construct($use_reference = FALSE, $first_precedence = FALSE) {
        // Use a reference
        $this->use_reference = $use_reference === TRUE ? TRUE : FALSE;
        $this->first_precedence = $first_precedence === TRUE ? TRUE : FALSE;

    }

    /**
     * Merge, used to merge multiple objects stored in an array
     *
     * This is used to *start* the merge or to merge an array of objects.
     * It is not needed to start the merge, but visually is nice.
     *
     * @param object[]|object $objects array of objects to merge or a single object
     * @return object the instance to enable linking
     */

    public function & merge() {
        $objects = func_get_args();
        // Each object
        foreach($objects as &$object) $this->with($object);
        // Garbage collection
        unset($object);

        // Return $this instance
        return $this;
    }

    /**
     * With, used to merge a singluar object
     *
     * Used to add an object to the composition
     *
     * @param object $object an object to merge
     * @return object the instance to enable linking
     */
    public function & with(&$object) {
        // An object
        if(is_object($object)) {
            // Reference
            if($this->use_reference) {
                if($this->first_precedence) array_push($this->composite, $object);
                else array_unshift($this->composite, $object);
            }
            // Clone
            else {
                if($this->first_precedence) array_push($this->composite, clone $object);
                else array_unshift($this->composite, clone $object);
            }
        }

        // Return $this instance
        return $this;
    }

    /**
     * __get, retrieves the psudo merged object
     *
     * @param string $name name of the variable in the object
     * @return mixed returns a reference to the requested variable
     *
     */
    public function & __get($name) {
        $return = NULL;
        foreach($this->composite as &$object) {
            if(isset($object->$name)) {
                $return =& $object->$name;
                break;
            }
        }
        // Garbage collection
        unset($object);

        return $return;
    }
}

Usage:

$obj = new Compositor(use_reference, first_precedence);
$obj->merge([object $object [, object $object [, object $...]]]);
$obj->with([object $object]);

Example:

$obj1 = new stdClass();
$obj1->a = 'obj1:a';
$obj1->b = 'obj1:b';
$obj1->c = 'obj1:c';

$obj2 = new stdClass();
$obj2->a = 'obj2:a';
$obj2->b = 'obj2:b';
$obj2->d = 'obj2:d';

$obj3 = new Compositor();
$obj3->merge($obj1, $obj2);
$obj1->c = '#obj1:c';
var_dump($obj3->a, $obj3->b, $obj3->c, $obj3->d);
// obj2:a, obj2:b, obj1:c, obj2:d
$obj1->c;

$obj3 = new Compositor(TRUE);
$obj3->merge($obj1)->with($obj2);
$obj1->c = '#obj1:c';
var_dump($obj3->a, $obj3->b, $obj3->c, $obj3->d);
// obj1:a, obj1:b, obj1:c, obj2:d
$obj1->c = 'obj1:c';

$obj3 = new Compositor(FALSE, TRUE);
$obj3->with($obj1)->with($obj2);
$obj1->c = '#obj1:c';
var_dump($obj3->a, $obj3->b, $obj3->c, $obj3->d);
// obj1:a, obj1:b, #obj1:c, obj2:d
$obj1->c = 'obj1:c';

RedirectToAction with parameter

//How to use RedirectToAction in MVC

return RedirectToAction("actionName", "ControllerName", routevalue);

example

return RedirectToAction("Index", "Home", new { id = 2});

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I have worked alot with msaccess vba. I think you are looking for MID function

example

    dim myReturn as string
    myreturn = mid("bonjour tout le monde",9,4)

will give you back the value "tout"

Check if current date is between two dates Oracle SQL

You don't need to apply to_date() to sysdate. It is already there:

select 1
from dual 
WHERE sysdate BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND TO_DATE('20/06/2014', 'DD/MM/YYYY');

If you are concerned about the time component on the date, then use trunc():

select 1
from dual 
WHERE trunc(sysdate) BETWEEN TO_DATE('28/02/2014', 'DD/MM/YYYY') AND
                             TO_DATE('20/06/2014', 'DD/MM/YYYY');

MySQL - Using COUNT(*) in the WHERE clause

try

SELECT DISTINCT gid
FROM `gd`
group by gid
having count(*) > 10
ORDER BY max(lastupdated) DESC

How do you create a temporary table in an Oracle database?

Just a tip.. Temporary tables in Oracle are different to SQL Server. You create it ONCE and only ONCE, not every session. The rows you insert into it are visible only to your session, and are automatically deleted (i.e., TRUNCATE, not DROP) when you end you session ( or end of the transaction, depending on which "ON COMMIT" clause you use).

How to copy a file from remote server to local machine?

The scp operation is separate from your ssh login. You will need to issue an ssh command similar to the following one assuming jdoe is account with which you log into the remote system and that the remote system is example.com:

scp [email protected]:/somedir/table /home/me/Desktop/.

The scp command issued from the system where /home/me/Desktop resides is followed by the userid for the account on the remote server. You then add a ":" followed by the directory path and file name on the remote server, e.g., /somedir/table. Then add a space and the location to which you want to copy the file. If you want the file to have the same name on the client system, you can indicate that with a period, i.e. "." at the end of the directory path; if you want a different name you could use /home/me/Desktop/newname, instead. If you were using a nonstandard port for SSH connections, you would need to specify that port with a "-P n" (capital P), where "n" is the port number. The standard port is 22 and if you aren't specifying it for the SSH connection then you won't need that.

How to clear all data in a listBox?

In C# Core DataSource does not exist, but this work fine:

listbox.ItemsSource = null;
listbox.Items.Clear();

How to replace item in array?

Easily accomplished with a for loop.

for (var i = 0; i < items.length; i++)
    if (items[i] == 3452)
        items[i] = 1010;

Simple state machine example in C#?

I'm posting another answer here as this is state machines from a different perspective; very visual.

My original answer is classic imperative code. I think its quite visual as code goes because of the array which makes visualizing the state machine simple. The downside is you have to write all this. Remos's answer alleviates the effort of writing the boiler-plate code but is far less visual. There is the third alternative; really drawing the state machine.

If you are using .NET and can target version 4 of the run time then you have the option of using workflow's state machine activities. These in essence let you draw the state machine (much as in Juliet's diagram) and have the WF run-time execute it for you.

See the MSDN article Building State Machines with Windows Workflow Foundation for more details, and this CodePlex site for the latest version.

That's the option I would always prefer when targeting .NET because its easy to see, change and explain to non programmers; pictures are worth a thousand words as they say!

JOIN two SELECT statement results

Use UNION:

SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks
UNION
SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks

Or UNION ALL if you want duplicates:

SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks
UNION ALL
SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks

git rebase merge conflict

Rebasing can be a real headache. You have to resolve the merge conflicts and continue rebasing. For example you can use the merge tool (which differs depending on your settings)

git mergetool

Then add your changes and go on

git rebase --continue

Good luck

Convert List<String> to List<Integer> directly

Guava Converters do the trick.

import com.google.common.base.Splitter;
import com.google.common.primitives.Longs;

final Iterable<Long> longIds = 
    Longs.stringConverter().convertAll(
        Splitter.on(',').trimResults().omitEmptyStrings()
            .splitToList("1,2,3"));

How can I get the values of data attributes in JavaScript code?

You can access it as

element.dataset.points

etc. So in this case: this.dataset.points

How to use Chrome's network debugger with redirects

Just update of @bfncs answer

I think around Chrome 43 the behavior was changed a little. You still need to enable Preserve log to see, but now redirect shown under Other tab, when loaded document is shown under Doc.

This always confuse me, because I have a lot of networks requests and filter it by type XHR, Doc, JS etc. But in case of redirect the Doc tab is empty, so I have to guess.

Load image from url

UrlImageViewHelper will fill an ImageView with an image that is found at a URL. UrlImageViewHelper will automatically download, save, and cache all the image urls the BitmapDrawables. Duplicate urls will not be loaded into memory twice. Bitmap memory is managed by using a weak reference hash table, so as soon as the image is no longer used by you, it will be garbage collected automatically.

UrlImageViewHelper.setUrlDrawable(imageView, "http://example.com/image.png");

https://github.com/koush/UrlImageViewHelper

How to specify different Debug/Release output directories in QMake .pro file

The new version of Qt Creator also has a "profile" build option between debug and release. Here's how I'm detecting that:

CONFIG(debug, debug|release) {  DEFINES += DEBUG_MODE }
else:CONFIG(force_debug_info) { DEFINES += PROFILE_MODE }
else {                          DEFINES += RELEASE_MODE }

How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?

The cc and cxx is located inside /Applications/Xcode.app. This should find the right paths

export CXX=`xcrun -find c++`
export CC=`xcrun -find cc`

How to put attributes via XElement

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);

How to link external javascript file onclick of button

You can load all your scripts in the head tag, and whatever your script is doing in function braces. But make sure you change the scope of the variables if you are using those variables outside the script.

How to create an empty matrix in R?

I'd be cautious as dismissing something as a bad idea because it is slow. If it is a part of the code that does not take much time to execute then the slowness is irrelevant. I just used the following code:

for (ic in 1:(dim(centroid)[2]))
{
cluster[[ic]]=matrix(,nrow=2,ncol=0)
}
# code to identify cluster=pindex[ip] to which to add the point
if(pdist[ip]>-1)
{
cluster[[pindex[ip]]]=cbind(cluster[[pindex[ip]]],points[,ip])
}

for a problem that ran in less than 1 second.

CSS-Only Scrollable Table with fixed headers

I had the same problem and after spending 2 days researching I found this solution from Ksesocss that fits for me and maybe is good for you too. It allows fixed header and dynamic width and only uses CSS. The only problem is that the source is in spanish but you can find the html and css code there.

This is the link:

http://ksesocss.blogspot.com/2014/10/responsive-table-encabezado-fijo-scroll.html

I hope this helps

How to concatenate strings in django templates?

Don't use add for strings, you should define a custom tag like this :

Create a file : <appname>\templatetags\<appname>_extras.py

from django import template

register = template.Library()

@register.filter
def addstr(arg1, arg2):
    """concatenate arg1 & arg2"""
    return str(arg1) + str(arg2)

and then use it as @Steven says

{% load <appname>_extras %}

{% with "shop/"|addstr:shop_name|addstr:"/base.html" as template %}
    {% include template %}
{% endwith %}

Reason for avoiding add:

According to the docs

This filter will first try to coerce both values to integers... Strings that can be coerced to integers will be summed, not concatenated...

If both variables happen to be integers, the result would be unexpected.

ERROR in Cannot find module 'node-sass'

This is what worked for me. I first uninstall node-sass. Then install it back.

npm uninstall node-sass
npm install --save-dev node-sass

AngularJS. How to call controller function from outside of controller component

I have multiple routes and multiple controllers, so I could not get the accepted answer to work. I found that adding the function to the window works:

fooModule.controller("fooViewModel", function ($scope, fooService, $http, $q, $routeParams, $window, $location, viewModelHelper, $interval) {
    $scope.initFoo = function () {
        // do angular stuff
    }
    var initialize = function () {
        $scope.initFoo();
    }

    initialize();

    window.fooreinit = initialize;

}

Then outside the controller, this can be done:

function ElsewhereOnThePage() {
    if (typeof(fooreinit) == 'function') { fooreinit(); }
}

How to change border color of textarea on :focus

so simple :

 outline-color : blue !important;

the whole CSS for my react-boostrap button is:

.custom-btn {
    font-size:1.9em;
    background: #2f5bff;
    border: 2px solid #78e4ff;
    border-radius: 3px;
    padding: 50px 70px;
    outline-color : blue !important;
    text-transform: uppercase;
    user-select: auto;
    -moz-box-shadow: inset 0 0 4px rgba(0,0,0,0.2);
    -webkit-box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.2);
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
}

changing visibility using javascript

function loadpage (page_request, containerid)
{
  var loading = document.getElementById ( "loading" ) ;

  // when connecting to server
  if ( page_request.readyState == 1 )
      loading.style.visibility = "visible" ;

  // when loaded successfully
  if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
  {
      document.getElementById(containerid).innerHTML=page_request.responseText ;
      loading.style.visibility = "hidden" ;
  }
}

Deploying my application at the root in Tomcat

I know that my answer is kind of overlapping with some of the other answer, but this is a complete solution that has some advantages. This works on Tomcat 8:

  1. The main application is served from the root
  2. The deployment of war files through the web interface is maintained.
  3. The main application will run on port 80 while only the admins have access to the managment folders (I realize that *nix systems require superuser for binding to 80, but on windows this is not an issue).

This means that you only have to restart the tomcat once, and after updated war files can be deployed without a problem.

Step 1: In the server.xml file, find the connector entry and replace it with:

<Connector 
    port="8080"
    protocol="HTTP/1.1"
    connectionTimeout="20000"
    redirectPort="8443" />

<Connector
    port="80"
    protocol="HTTP/1.1"
    connectionTimeout="20000"
    redirectPort="8443" />

Step 2: Define contexts within the <Host ...> tag:

<Context path="/" docBase="CAS">
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
<Context path="/ROOT" docBase="ROOT">
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
<Context path="/manager" docBase="manager" privileged="true">
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>
<Context path="/host-manager" docBase="host-manager" privileged="true">
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
</Context>

Note that I addressed all apps in the webapp folder. The first effectively switch the root and the main app from position. ROOT is now on http://example.com/ROOT and the the main application is on http://example.com/. The webapps that are password protected require the privileged="true" attribute.

When you deploy a CAS.war file that matches with the root (<Context path="/" docBase="CAS"> you have to reload that one in the admin panel as it does not refresh with the deployment.

Do not include the <Context path="/CAS" docBase="CAS"> in your contexts as it disables the manager option to deploy war files. This means that you can access the app in two ways: http://example.com/ and http://example.com/APP/

Step 3: In order to prevent unwanted access to the root and manager folder, add a valve to those context tags like this:

<Context path="/manager" docBase="manager" privileged="true">
    <WatchedResource>WEB-INF/web.xml</WatchedResource>
    <Valve className="org.apache.catalina.valves.RemoteAddrValve"
        addConnectorPort="true"
        allow="143\.21\.2\.\d+;8080|127\.0\.0\.1;8080|::1;8080|0:0:0:0:0:0:0:1;8080"/>
</Context>

This essentially limits access to the admin web app folder to people from my own domain (fake IP address) and localhost when they use the default port 8080 and maintains the ability to dynamically deploy the war files through the web interface.

If you want to use this for multiple apps that are using different IP addresses, you can add the IP address to the connector (address="143.21.2.1").

If you want to run multiple web apps from the root, you can duplicate the Service tag (use a different name for the second) and change the docbase of the <Context path="/" docBase="CAS"> to for example <Context path="/" docBase="ICR">.

How to get query string parameter from MVC Razor markup?

If you are using .net core 2.0 this would be:

Context.Request.Query["id"]

Sample usage:

<a href="@Url.Action("Query",new {parm1=Context.Request.Query["queryparm1"]})">GO</a>

What exceptions should be thrown for invalid or unexpected parameters in .NET?

Depending on the actual value and what exception fits best:

If this is not precise enough, just derive your own exception class from ArgumentException.

Yoooder's answer enlightened me. An input is invalid if it is not valid at any time, while an input is unexpected if it is not valid for the current state of the system. So in the later case an InvalidOperationException is a reasonable choice.

jQuery - find child with a specific class

Based on your comment, moddify this:

$( '.bgHeaderH2' ).html (); // will return whatever is inside the DIV

to:

$( '.bgHeaderH2', $( this ) ).html (); // will return whatever is inside the DIV

More about selectors: https://api.jquery.com/category/selectors/

OnItemCLickListener not working in listview

I just found a solution from here, but by deep clicking.

If any row item of list contains focusable or clickable view then OnItemClickListener won't work.

The row item must have a param like android:descendantFocusability = "blocksDescendants".

Here you can see an example of how your list item should look like. Your list item xml should be... row_item.xml (your_xml_file.xml)

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:baselineAligned="false"
    android:descendantFocusability="blocksDescendants"
    android:gravity="center_vertical" >

    // your other widgets here

</LinearLayout>

Javascript .querySelector find <div> by innerTEXT

Use XPath and document.evaluate(), and make sure to use text() and not . for the contains() argument, or else you will have the entire HTML, or outermost div element matched.

var headings = document.evaluate("//h1[contains(text(), 'Hello')]", document, null, XPathResult.ANY_TYPE, null );

or ignore leading and trailing whitespace

var headings = document.evaluate("//h1[contains(normalize-space(text()), 'Hello')]", document, null, XPathResult.ANY_TYPE, null );

or match all tag types (div, h1, p, etc.)

var headings = document.evaluate("//*[contains(text(), 'Hello')]", document, null, XPathResult.ANY_TYPE, null );

Then iterate

let thisHeading;
while(thisHeading = headings.iterateNext()){
    // thisHeading contains matched node
}

Adding to the classpath on OSX

Normally there's no need for that. First of all

echo $CLASSPATH

If there's something in there, you probably want to check Applications -> Utilites -> Java.

Finding the layers and layer sizes for each Docker image

  1. https://hub.docker.com/search?q=* shows all the images in the entire Docker hub, it's not possible to get this via the search command as it doesnt accept wildcards.

  2. As of v1.10 you can find all the layers in an image by pulling it and using these commands:

    docker pull ubuntu
    ID=$(sudo docker inspect -f {{.Id}} ubuntu)
    jq .rootfs.diff_ids /var/lib/docker/image/aufs/imagedb/content/$(echo $ID|tr ':' '/')
    

3) The size can be found in /var/lib/docker/image/aufs/layerdb/sha256/{LAYERID}/size although LAYERID != the diff_ids found with the previous command. For this you need to look at /var/lib/docker/image/aufs/layerdb/sha256/{LAYERID}/diff and compare with the previous command output to properly match the correct diff_id and size.

Comparing date part only without comparing time in JavaScript

An efficient and correct way to compare dates is:

Math.floor(date1.getTime() / 86400000) > Math.floor(date2.getTime() / 86400000);

It ignores the time part, it works for different timezones, and you can compare for equality == too. 86400000 is the number of milliseconds in a day (= 24*60*60*1000).

Beware that the equality operator == should never be used for comparing Date objects because it fails when you would expect an equality test to work because it is comparing two Date objects (and does not compare the two dates) e.g.:

> date1;
outputs: Thu Mar 08 2018 00:00:00 GMT+1300

> date2;
outputs: Thu Mar 08 2018 00:00:00 GMT+1300

> date1 == date2;
outputs: false

> Math.floor(date1.getTime() / 86400000) == Math.floor(date2.getTime() / 86400000);
outputs: true

Notes: If you are comparing Date objects that have the time part set to zero, then you could use date1.getTime() == date2.getTime() but it is hardly worth the optimisation. You can use <, >, <=, or >= when comparing Date objects directly because these operators first convert the Date object by calling .valueOf() before the operator does the comparison.

How to POST a JSON object to a JAX-RS service

I faced the same 415 http error when sending objects, serialized into JSON, via PUT/PUSH requests to my JAX-rs services, in other words my server was not able to de-serialize the objects from JSON. In my case, the server was able to serialize successfully the same objects in JSON when sending them into its responses.

As mentioned in the other responses I have correctly set the Accept and Content-Type headers to application/json, but it doesn't suffice.

Solution

I simply forgot a default constructor with no parameters for my DTO objects. Yes this is the same reasoning behind @Entity objects, you need a constructor with no parameters for the ORM to instantiate objects and populate the fields later.

Adding the constructor with no parameters to my DTO objects solved my issue. Here follows an example that resembles my code:

Wrong

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {
    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

Right

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class NumberDTO {

    public NumberDTO() {
    }

    public NumberDTO(Number number) {
        this.number = number;
    }

    private Number number;

    public Number getNumber() {
        return number;
    }

    public void setNumber(Number string) {
        this.number = string;
    }
}

I lost hours, I hope this'll save yours ;-)

Need to ZIP an entire directory using Node.js

Use Node's native child_process api to accomplish this.

No need for third party libs. Two lines of code.

const child_process = require("child_process");
child_process.execSync(`zip -r DESIRED_NAME_OF_ZIP_FILE_HERE *`, {
  cwd: PATH_TO_FOLDER_YOU_WANT_ZIPPED_HERE
});

I'm using the synchronous API. You can use child_process.exec(path, options, callback) if you need async. There are a lot more options than just specifying the CWD to further finetune your requests. See exec/execSync docs.


Please note: This example assumes you have the zip utility installed on your system (it comes with OSX, at least). Some operating systems may not have utility installed (i.e., AWS Lambda runtime doesn't). In that case, you can easily obtain the zip utility binary here and package it along with your application source code (for AWS Lambda you can package it in a Lambda Layer as well), or you'll have to either use a third party module (of which there are plenty on NPM). I prefer the former approach, as the ZIP utility is tried and tested for decades.

MySQL - Rows to Columns

My solution :

select h.hostid, sum(ifnull(h.A,0)) as A, sum(ifnull(h.B,0)) as B, sum(ifnull(h.C,0)) as  C from (
select
hostid,
case when itemName = 'A' then itemvalue end as A,
case when itemName = 'B' then itemvalue end as B,
case when itemName = 'C' then itemvalue end as C
  from history 
) h group by hostid

It produces the expected results in the submitted case.

How can I conditionally import an ES6 module?

require() is a way to import some module on the run time and it equally qualifies for static analysis like import if used with string literal paths. This is required by bundler to pick dependencies for the bundle.

const defaultOne = require('path/to/component').default;
const NamedOne = require('path/to/component').theName;

For dynamic module resolution with complete static analysis support, first index modules in an indexer(index.js) and import indexer in host module.

// index.js
export { default as ModuleOne } from 'path/to/module/one';
export { default as ModuleTwo } from 'path/to/module/two';
export { SomeNamedModule } from 'path/to/named/module';

// host.js
import * as indexer from 'index';
const moduleName = 'ModuleOne';
const Module = require(indexer[moduleName]);

Java, How to implement a Shift Cipher (Caesar Cipher)

Java Shift Caesar Cipher by shift spaces.

Restrictions:

  1. Only works with a positive number in the shift parameter.
  2. Only works with shift less than 26.
  3. Does a += which will bog the computer down for bodies of text longer than a few thousand characters.
  4. Does a cast number to character, so it will fail with anything but ascii letters.
  5. Only tolerates letters a through z. Cannot handle spaces, numbers, symbols or unicode.
  6. Code violates the DRY (don't repeat yourself) principle by repeating the calculation more than it has to.

Pseudocode:

  1. Loop through each character in the string.
  2. Add shift to the character and if it falls off the end of the alphabet then subtract shift from the number of letters in the alphabet (26)
  3. If the shift does not make the character fall off the end of the alphabet, then add the shift to the character.
  4. Append the character onto a new string. Return the string.

Function:

String cipher(String msg, int shift){
    String s = "";
    int len = msg.length();
    for(int x = 0; x < len; x++){
        char c = (char)(msg.charAt(x) + shift);
        if (c > 'z')
            s += (char)(msg.charAt(x) - (26-shift));
        else
            s += (char)(msg.charAt(x) + shift);
    }
    return s;
}

How to invoke it:

System.out.println(cipher("abc", 3));  //prints def
System.out.println(cipher("xyz", 3));  //prints abc

Avoid printStackTrace(); use a logger call instead

The main reason is that Proguard would remove Log calls from production. Because by logging or printing StackTrace, it is possible to see them (information inside stack trace or Log) inside the Android phone by for example Logcat Reader application. So that it is a bad practice for security. Also, we do not access them during production, it would better to get removed from production. As ProGuard remove all Log calls not stackTrace, so it is better to use Log in catch blocks and let them removed from Production by Proguard.

How can I suppress all output from a command using Bash?

Try

: $(yourcommand)

: is short for "do nothing".

$() is just your command.

How to access ssis package variables inside script component

Strongly typed var don't seem to be available, I have to do the following in order to get access to them:

String MyVar = Dts.Variables["MyVarName"].Value.ToString();

Overlapping elements in CSS

I think you could get away with using relative positioning and then set the top/left positioning of the second DIV until you have it in the position desired.

Setting maxlength of textbox with JavaScript or jQuery

Not sure what you are trying to accomplish on your first few lines but you can try this:

$(document).ready(function()
{
    $("#ms_num").attr('maxlength','6');
});

Rubymine: How to make Git ignore .idea files created by Rubymine

Add .idea/* to your exclusion list to prevent tracking of all .idea files, directories, and sub-resources.

How to cast the size_t to double or int C++

A cast, as Blaz Bratanic suggested:

size_t data = 99999999;
int convertdata = static_cast<int>(data);

is likely to silence the warning (though in principle a compiler can warn about anything it likes, even if there's a cast).

But it doesn't solve the problem that the warning was telling you about, namely that a conversion from size_t to int really could overflow.

If at all possible, design your program so you don't need to convert a size_t value to int. Just store it in a size_t variable (as you've already done) and use that.

Converting to double will not cause an overflow, but it could result in a loss of precision for a very large size_t value. Again, it doesn't make a lot of sense to convert a size_t to a double; you're still better off keeping the value in a size_t variable.

(R Sahu's answer has some suggestions if you can't avoid the cast, such as throwing an exception on overflow.)

react hooks useEffect() cleanup for only componentWillUnmount?

you can use more than one useEffect

for example if my variable is data1 i can use all of this in my component

useEffect( () => console.log("mount"), [] );
useEffect( () => console.log("will update data1"), [ data1 ] );
useEffect( () => console.log("will update any") );
useEffect( () => () => console.log("will update data1 or unmount"), [ data1 ] );
useEffect( () => () => console.log("unmount"), [] );

The 'packages' element is not declared

Taken from this answer.

  1. Close your packages.config file.
  2. Build
  3. Warning is gone!

This is the first time I see ignoring a problem actually makes it go away...

Edit in 2020: if you are viewing this warning, consider upgrading to PackageReference if you can

Turn off display errors using file "php.ini"

In php.ini, comment out:

error_reporting = E_ALL & ~E_NOTICE
error_reporting = E_ALL & ~E_NOTICE | E_STRICT
error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ER… _ERROR
error_reporting = E_ALL & ~E_NOTICE

By placing a ; ahead of it (i.e., like ;error_reporting = E_ALL & ~E_NOTICE)

For disabling in a single file, place error_reporting(0); after opening a php tag.

How to replace all occurrences of a character in string?

here's a solution i rolled, in a maximal DRI spirit. it will search sNeedle in sHaystack and replace it by sReplace, nTimes if non 0, else all the sNeedle occurences. it will not search again in the replaced text.

std::string str_replace(
    std::string sHaystack, std::string sNeedle, std::string sReplace, 
    size_t nTimes=0)
{
    size_t found = 0, pos = 0, c = 0;
    size_t len = sNeedle.size();
    size_t replen = sReplace.size();
    std::string input(sHaystack);

    do {
        found = input.find(sNeedle, pos);
        if (found == std::string::npos) {
            break;
        }
        input.replace(found, len, sReplace);
        pos = found + replen;
        ++c;
    } while(!nTimes || c < nTimes);

    return input;
}

twitter-bootstrap: how to get rid of underlined button text when hovering over a btn-group within an <a>-tag?

Try putting anchor tag inside and adding a{display:block;}....it will work fine

Bootstrap: How to center align content inside column?

Want to center an image? Very easy, Bootstrap comes with two classes, .center-block and text-center.

Use the former in the case of your image being a BLOCK element, for example, adding img-responsive class to your img makes the img a block element. You should know this if you know how to navigate in the web console and see applied styles to an element.

Don't want to use a class? No problem, here is the CSS bootstrap uses. You can make a custom class or write a CSS rule for the element to match the Bootstrap class.

 // In case you're dealing with a block element apply this to the element itself 
.center-block {
   margin-left:auto;
   margin-right:auto;
   display:block;
}

// In case you're dealing with a inline element apply this to the parent 
.text-center {
   text-align:center
}

Angular 2: 404 error occur when I refresh through the browser

For people (like me) who really want PathLocationStrategy (i.e. html5Mode) instead of HashLocationStrategy, see How to: Configure your server to work with html5Mode from a third-party wiki:

When you have html5Mode enabled, the # character will no longer be used in your URLs. The # symbol is useful because it requires no server side configuration. Without #, the URL looks much nicer, but it also requires server side rewrites.

Here I only copy three examples from the wiki, in case the Wiki get lost. Other examples can be found by searching keyword "URL rewrite" (e.g. this answer for Firebase).

Apache

<VirtualHost *:80>
    ServerName my-app

    DocumentRoot /path/to/app

    <Directory /path/to/app>
        RewriteEngine on

        # Don't rewrite files or directories
        RewriteCond %{REQUEST_FILENAME} -f [OR]
        RewriteCond %{REQUEST_FILENAME} -d
        RewriteRule ^ - [L]

        # Rewrite everything else to index.html to allow HTML5 state links
        RewriteRule ^ index.html [L]
    </Directory>
</VirtualHost>

Documentation for rewrite module

nginx

server {
    server_name my-app;

    root /path/to/app;

    location / {
        try_files $uri $uri/ /index.html;
    }
}

Documentation for try_files

IIS

<system.webServer>
  <rewrite>
    <rules> 
      <rule name="Main Rule" stopProcessing="true">
        <match url=".*" />
        <conditions logicalGrouping="MatchAll">
          <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
          <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

Why does SSL handshake give 'Could not generate DH keypair' exception?

You can disable DHE completely in your jdk, edit jre/lib/security/java.security and make sure DHE is disabled, eg. like

jdk.tls.disabledAlgorithms=SSLv3, DHE.

VBA Subscript out of range - error 9

Suggest the following simplification: capture return value from Workbooks.Add instead of subscripting Windows() afterward, as follows:

Set wkb = Workbooks.Add
wkb.SaveAs ...

wkb.Activate ' instead of Windows(expression).Activate


General Philosophy Advice:

Avoid use Excel's built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.

Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.

Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection

During and within macros do not rely on these built-in names, instead capture return values, e.g.

Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate

Also, try to use qualified expressions, e.g.

wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"

or

Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"

Use qualified expressions, e.g.

newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar" 

These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.

Also please note that you'll likely find that you don't need to .Activate nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate could simply be eliminated instead of even being replaced by wkb.Activate.

(Also note: I think the .Select statements you show are not contributing and can be omitted.)

(I think that Excel's macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)

Adding a newline character within a cell (CSV)

On Excel for Mac 2011, the newline had to be a \r instead of an \n

So

"\"first line\rsecond line\""

would show up as a cell with 2 lines

How to implement a property in an interface

The simple example of using a property in an interface:

using System;
interface IName
{
    string Name { get; set; }
}

class Employee : IName
{
    public string Name { get; set; }
}

class Company : IName
{
    private string _company { get; set; }
    public string Name
    {
        get
        {
            return _company;
        }
        set
        {
            _company = value;
        }   
    }
}

class Client
{
    static void Main(string[] args)
    {
        IName e = new Employee();
        e.Name = "Tim Bridges";

        IName c = new Company();
        c.Name = "Inforsoft";

        Console.WriteLine("{0} from {1}.", e.Name, c.Name);
        Console.ReadKey();
    }
}
/*output:
 Tim Bridges from Inforsoft.
 */

How to fill color in a cell in VBA?

Non VBA Solution:

Use Conditional Formatting rule with formula: =ISNA(A1) (to highlight cells with all errors - not only #N/A, use =ISERROR(A1))

enter image description here

VBA Solution:

Your code loops through 50 mln cells. To reduce number of cells, I use .SpecialCells(xlCellTypeFormulas, 16) and .SpecialCells(xlCellTypeConstants, 16)to return only cells with errors (note, I'm using If cell.Text = "#N/A" Then)

Sub ColorCells()
    Dim Data As Range, Data2 As Range, cell As Range
    Dim currentsheet As Worksheet

    Set currentsheet = ActiveWorkbook.Sheets("Comparison")

    With currentsheet.Range("A2:AW" & Rows.Count)
        .Interior.Color = xlNone
        On Error Resume Next
        'select only cells with errors
        Set Data = .SpecialCells(xlCellTypeFormulas, 16)
        Set Data2 = .SpecialCells(xlCellTypeConstants, 16)
        On Error GoTo 0
    End With

    If Not Data2 Is Nothing Then
        If Not Data Is Nothing Then
            Set Data = Union(Data, Data2)
        Else
            Set Data = Data2
        End If
    End If

    If Not Data Is Nothing Then
        For Each cell In Data
            If cell.Text = "#N/A" Then
               cell.Interior.ColorIndex = 4
            End If
        Next
    End If
End Sub

Note, to highlight cells witn any error (not only "#N/A"), replace following code

If Not Data Is Nothing Then
   For Each cell In Data
       If cell.Text = "#N/A" Then
          cell.Interior.ColorIndex = 3
       End If
   Next
End If

with

If Not Data Is Nothing Then Data.Interior.ColorIndex = 3

UPD: (how to add CF rule through VBA)

Sub test()
    With ActiveWorkbook.Sheets("Comparison").Range("A2:AW" & Rows.Count).FormatConditions
        .Delete
        .Add Type:=xlExpression, Formula1:="=ISNA(A1)"
        .Item(1).Interior.ColorIndex = 3
    End With
End Sub

How do I set default values for functions parameters in Matlab?

There is also a 'hack' that can be used although it might be removed from matlab at some point: Function eval actually accepts two arguments of which the second is run if an error occurred with the first.

Thus we can use

function output = fun(input)
   eval('input;', 'input = 1;');
   ...
end

to use value 1 as default for the argument

Increase JVM max heap size for Eclipse

You can use this configuration:

-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M

How can a windows service programmatically restart itself?

You can't be sure that the user account that your service is running under even has permissions to stop and restart the service.

Javascript - Replace html using innerHTML

You are replacing the starting tag and then putting that back in innerHTML, so the code will be invalid. Make all the replacements before you put the code back in the element:

var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;

How can I remove a trailing newline?

Careful with "foo".rstrip(os.linesep): That will only chomp the newline characters for the platform where your Python is being executed. Imagine you're chimping the lines of a Windows file under Linux, for instance:

$ python
Python 2.7.1 (r271:86832, Mar 18 2011, 09:09:48) 
[GCC 4.5.0 20100604 [gcc-4_5-branch revision 160292]] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import os, sys
>>> sys.platform
'linux2'
>>> "foo\r\n".rstrip(os.linesep)
'foo\r'
>>>

Use "foo".rstrip("\r\n") instead, as Mike says above.

Module 'tensorflow' has no attribute 'contrib'

tf.contrib has moved out of TF starting TF 2.0 alpha.
Take a look at these tf 2.0 release notes https://github.com/tensorflow/tensorflow/releases/tag/v2.0.0-alpha0
You can upgrade your TF 1.x code to TF 2.x using the tf_upgrade_v2 script https://www.tensorflow.org/alpha/guide/upgrade

ERROR 1064 (42000) in MySQL

(For those coming to this question from a search engine), check that your stored procedures declare a custom delimiter, as this is the error that you might see when the engine can't figure out how to terminate a statement:

ERROR 1064 (42000) at line 3: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line…

If you have a database dump and see:

DROP PROCEDURE IF EXISTS prc_test;
CREATE PROCEDURE prc_test( test varchar(50))
BEGIN
    SET @sqlstr = CONCAT_WS(' ', 'CREATE DATABASE',  test, 'CHARACTER SET utf8 COLLATE utf8_general_ci');
    SELECT @sqlstr;
    PREPARE stmt FROM @sqlstr;
    EXECUTE stmt;
END;

Try wrapping with a custom DELIMITER:

DROP PROCEDURE IF EXISTS prc_test;
DELIMITER $$
CREATE PROCEDURE prc_test( test varchar(50))
BEGIN
    SET @sqlstr = CONCAT_WS(' ', 'CREATE DATABASE',  test, 'CHARACTER SET utf8 COLLATE utf8_general_ci');
    SELECT @sqlstr;
    PREPARE stmt FROM @sqlstr;
    EXECUTE stmt;
END;
$$
DELIMITER ;

How to get correct timestamp in C#

internal static string UnixToDate(int Timestamp, string ConvertFormat)
{
    DateTime ConvertedUnixTime = DateTimeOffset.FromUnixTimeSeconds(Timestamp).DateTime;
    return ConvertedUnixTime.ToString(ConvertFormat);
}

int Timestamp = (int)DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds;

Usage:

UnixToDate(1607013172, "HH:mm:ss"); // Output 16:32:52
Timestamp; // Output 1607013172

Select the first 10 rows - Laravel Eloquent

First you can use a Paginator. This is as simple as:

$allUsers = User::paginate(15);

$someUsers = User::where('votes', '>', 100)->paginate(15);

The variables will contain an instance of Paginator class. all of your data will be stored under data key.

Or you can do something like:

Old versions Laravel.

Model::all()->take(10)->get();

Newer version Laravel.

Model::all()->take(10);

For more reading consider these links:

How to append multiple items in one line in Python

use for loop. like this:

for x in [1,2,7,8,9,10,13,14,19,20,21,22]:
    new_list.append(my_list[i + x])

Copying a rsa public key to clipboard

For using Git bash on Windows:

cat ~/.ssh/id_rsa.pub > /dev/clipboard

(modified from Jupiter St John's post on Coderwall)

Use of the MANIFEST.MF file in Java

The content of the Manifest file in a JAR file created with version 1.0 of the Java Development Kit is the following.

Manifest-Version: 1.0

All the entries are as name-value pairs. The name of a header is separated from its value by a colon. The default manifest shows that it conforms to version 1.0 of the manifest specification. The manifest can also contain information about the other files that are packaged in the archive. Exactly what file information is recorded in the manifest will depend on the intended use for the JAR file. The default manifest file makes no assumptions about what information it should record about other files, so its single line contains data only about itself. Special-Purpose Manifest Headers

Depending on the intended role of the JAR file, the default manifest may have to be modified. If the JAR file is created only for the purpose of archival, then the MANIFEST.MF file is of no purpose. Most uses of JAR files go beyond simple archiving and compression and require special information to be in the manifest file. Summarized below are brief descriptions of the headers that are required for some special-purpose JAR-file functions

Applications Bundled as JAR Files: If an application is bundled in a JAR file, the Java Virtual Machine needs to be told what the entry point to the application is. An entry point is any class with a public static void main(String[] args) method. This information is provided in the Main-Class header, which has the general form:

Main-Class: classname

The value classname is to be replaced with the application's entry point.

Download Extensions: Download extensions are JAR files that are referenced by the manifest files of other JAR files. In a typical situation, an applet will be bundled in a JAR file whose manifest references a JAR file (or several JAR files) that will serve as an extension for the purposes of that applet. Extensions may reference each other in the same way. Download extensions are specified in the Class-Path header field in the manifest file of an applet, application, or another extension. A Class-Path header might look like this, for example:

Class-Path: servlet.jar infobus.jar acme/beans.jar

With this header, the classes in the files servlet.jar, infobus.jar, and acme/beans.jar will serve as extensions for purposes of the applet or application. The URLs in the Class-Path header are given relative to the URL of the JAR file of the applet or application.

Package Sealing: A package within a JAR file can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR file. A package might be sealed to ensure version consistency among the classes in your software or as a security measure. To seal a package, a Name header needs to be added for the package, followed by a Sealed header, similar to this:

Name: myCompany/myPackage/
Sealed: true

The Name header's value is the package's relative pathname. Note that it ends with a '/' to distinguish it from a filename. Any headers following a Name header, without any intervening blank lines, apply to the file or package specified in the Name header. In the above example, because the Sealed header occurs after the Name: myCompany/myPackage header, with no blank lines between, the Sealed header will be interpreted as applying (only) to the package myCompany/myPackage.

Package Versioning: The Package Versioning specification defines several manifest headers to hold versioning information. One set of such headers can be assigned to each package. The versioning headers should appear directly beneath the Name header for the package. This example shows all the versioning headers:

Name: java/util/
Specification-Title: "Java Utility Classes" 
Specification-Version: "1.2"
Specification-Vendor: "Sun Microsystems, Inc.".
Implementation-Title: "java.util" 
Implementation-Version: "build57"
Implementation-Vendor: "Sun Microsystems, Inc."

How to initialize static variables

If you have control over class loading, you can do static initializing from there.

Example:

class MyClass { public static function static_init() { } }

in your class loader, do the following:

include($path . $klass . PHP_EXT);
if(method_exists($klass, 'static_init')) { $klass::staticInit() }

A more heavy weight solution would be to use an interface with ReflectionClass:

interface StaticInit { public static function staticInit() { } }
class MyClass implements StaticInit { public static function staticInit() { } }

in your class loader, do the following:

$rc = new ReflectionClass($klass);
if(in_array('StaticInit', $rc->getInterfaceNames())) { $klass::staticInit() }

Why am I seeing "TypeError: string indices must be integers"?

This can happen if a comma is missing. I ran into it when I had a list of two-tuples, each of which consisted of a string in the first position, and a list in the second. I erroneously omitted the comma after the first component of a tuple in one case, and the interpreter thought I was trying to index the first component.

How to create a Rectangle object in Java using g.fillRect method

You may try like this:

import java.applet.Applet;
import java.awt.*;

public class Rect1 extends Applet {

  public void paint (Graphics g) {
    g.drawRect (x, y, width, height);    //can use either of the two//
    g.fillRect (x, y, width, height);
    g.setColor(color);
  }

}

where x is x co-ordinate y is y cordinate color=the color you want to use eg Color.blue

if you want to use rectangle object you could do it like this:

import java.applet.Applet;
import java.awt.*;

public class Rect1 extends Applet {

  public void paint (Graphics g) {    
    Rectangle r = new Rectangle(arg,arg1,arg2,arg3);
    g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());
    g.setColor(color);
  }
}       

Full screen background image in an activity

three step for put background

1)you should choose your like picture. for example :enter image description here

2)Then you copy this picture in drawable. warning: you should choose types short for name picture.

enter image description here

3)you go to page xml Intended and write :

android:background="id picture" for example my picture id is @drawable/download.

enter image description here

finish.

Make Https call using HttpClient

I had this issue and in my case the solution was stupidly simple: open Visual Studio with Administrator rights. I tried all the above solutions and it didn't work until I did this. Hope it saves someone some precious time.

best practice to generate random token for forgot password

This answers the 'best random' request:

Adi's answer1 from Security.StackExchange has a solution for this:

Make sure you have OpenSSL support, and you'll never go wrong with this one-liner

$token = bin2hex(openssl_random_pseudo_bytes(16));

1. Adi, Mon Nov 12 2018, Celeritas, "Generating an unguessable token for confirmation e-mails", Sep 20 '13 at 7:06, https://security.stackexchange.com/a/40314/

Jquery Ajax Call, doesn't call Success or Error

Try to encapsulate the ajax call into a function and set the async option to false. Note that this option is deprecated since jQuery 1.8.

function foo() {
    var myajax = $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        async: false, //add this
    });
    return myajax.responseText;
}

You can do this also:

$.ajax({
    type: "POST",
    url: "CHService.asmx/SavePurpose",
    dataType: "text",
    data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
    contentType: "application/json; charset=utf-8",
    async: false, //add this
}).done(function ( data ) {
        Success = true;
}).fail(function ( data ) {
       Success = false;
});

You can read more about the jqXHR jQuery Object

How to create the most compact mapping n ? isprime(n) up to a limit N?

Python 3:

def is_prime(a):
    return a > 1 and all(a % i for i in range(2, int(a**0.5) + 1))

Can I clear cell contents without changing styling?

You should use the ClearContents method if you want to clear the content but preserve the formatting.

Worksheets("Sheet1").Range("A1:G37").ClearContents

Search for string and get count in vi editor

:g/xxxx/d

This will delete all the lines with pattern, and report how many deleted. Undo to get them back after.

check if a file is open in Python

You could use with open("path") as file: so that it automatically closes, else if it's open in another process you can maybe try as in Tims example you should use except IOError to not ignore any other problem with your code :)

try:
   with open("path", "r") as file: # or just open
       # Code here
except IOError:
   # raise error or print

How do you do natural logs (e.g. "ln()") with numpy in Python?

I usually do like this:

from numpy import log as ln

Perhaps this can make you more comfortable.

Understanding unique keys for array children in React.js

I fixed this using Guid for each key like this: Generating Guid:

guid() {
    return this.s4() + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' +
        this.s4() + '-' + this.s4() + this.s4() + this.s4();
}

s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
        .toString(16)
        .substring(1);
}

And then assigning this value to markers:

{this.state.markers.map(marker => (
              <MapView.Marker
                  key={this.guid()}
                  coordinate={marker.coordinates}
                  title={marker.title}
              />
          ))}

How can I add a vertical scrollbar to my div automatically?

You can set :

overflow-y: scroll;height: XX px

Remove all non-"word characters" from a String in Java, leaving accented characters?

At times you do not want to simply remove the characters, but just remove the accents. I came up with the following utility class which I use in my Java REST web projects whenever I need to include a String in an URL:

import java.text.Normalizer;
import java.text.Normalizer.Form;

import org.apache.commons.lang.StringUtils;

/**
 * Utility class for String manipulation.
 * 
 * @author Stefan Haberl
 */
public abstract class TextUtils {
    private static String[] searchList = { "Ä", "ä", "Ö", "ö", "Ü", "ü", "ß" };
    private static String[] replaceList = { "Ae", "ae", "Oe", "oe", "Ue", "ue",
            "sz" };

    /**
     * Normalizes a String by removing all accents to original 127 US-ASCII
     * characters. This method handles German umlauts and "sharp-s" correctly
     * 
     * @param s
     *            The String to normalize
     * @return The normalized String
     */
    public static String normalize(String s) {
        if (s == null)
            return null;

        String n = null;

        n = StringUtils.replaceEachRepeatedly(s, searchList, replaceList);
        n = Normalizer.normalize(n, Form.NFD).replaceAll("[^\\p{ASCII}]", "");

        return n;
    }

    /**
     * Returns a clean representation of a String which might be used safely
     * within an URL. Slugs are a more human friendly form of URL encoding a
     * String.
     * <p>
     * The method first normalizes a String, then converts it to lowercase and
     * removes ASCII characters, which might be problematic in URLs:
     * <ul>
     * <li>all whitespaces
     * <li>dots ('.')
     * <li>(semi-)colons (';' and ':')
     * <li>equals ('=')
     * <li>ampersands ('&')
     * <li>slashes ('/')
     * <li>angle brackets ('<' and '>')
     * </ul>
     * 
     * @param s
     *            The String to slugify
     * @return The slugified String
     * @see #normalize(String)
     */
    public static String slugify(String s) {

        if (s == null)
            return null;

        String n = normalize(s);
        n = StringUtils.lowerCase(n);
        n = n.replaceAll("[\\s.:;&=<>/]", "");

        return n;
    }
}

Being a German speaker I've included proper handling of German umlauts as well - the list should be easy to extend for other languages.

HTH

EDIT: Note that it may be unsafe to include the returned String in an URL. You should at least HTML encode it to prevent XSS attacks.

jQuery Refresh/Reload Page if Ajax Success after time

var val = $.parseJSON(data);
if(val.success == true)
{
 setTimeout(function(){ location.reload(); }, 5000);

}

Wait until flag=true

I tried to used @Kiran approach like follow:

checkFlag: function() {
  var currentObject = this; 
  if(flag == false) {
      setTimeout(currentObject.checkFlag, 100); 
   } else {
     /* do something*/
   }
}

(framework that I am using force me to define functions this way). But without success because when execution come inside checkFlag function second time, this is not my object it is Window. So, I finished with code below

checkFlag: function() {
    var worker = setInterval (function(){
         if(flag == true){             
             /* do something*/
              clearInterval (worker);
         } 
    },100);
 }

how to properly display an iFrame in mobile safari

I have put @Sharon's code together into the following, which works for me on the iPad with two-finger scrolling. The only thing you should have to change to get it working is the src attribute on the iframe (I used a PDF document).

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Pdf Scrolling in mobile Safari</title>
</head>
<body>
<div id="scroller" style="height: 400px; width: 100%; overflow: auto;">
<iframe height="100%" id="iframe" scrolling="no" width="100%" id="iframe" src="data/testdocument.pdf" />
</div>
<script type="text/javascript">
    setTimeout(function () {
        var startY = 0;
        var startX = 0;
        var b = document.body;
        b.addEventListener('touchstart', function (event) {
            parent.window.scrollTo(0, 1);
            startY = event.targetTouches[0].pageY;
            startX = event.targetTouches[0].pageX;
        });
        b.addEventListener('touchmove', function (event) {
            event.preventDefault();
            var posy = event.targetTouches[0].pageY;
            var h = parent.document.getElementById("scroller");
            var sty = h.scrollTop;

            var posx = event.targetTouches[0].pageX;
            var stx = h.scrollLeft;
            h.scrollTop = sty - (posy - startY);
            h.scrollLeft = stx - (posx - startX);
            startY = posy;
            startX = posx;
        });
    }, 1000);
    </script>
</body>
</html>

INSTALL_FAILED_USER_RESTRICTED : android studio using redmi 4 device

The device is temporarily restricted error appears in MIUI 8.5. To resolve the error you need to make WIFI off and make mobile data on and then enable the option “Install via USB” under "Developer Options" in "Settings". it will work for you.

Plot different DataFrames in the same figure

Just to enhance @adivis12 answer, you don't need to do the if statement. Put it like this:

fig, ax = plt.subplots()
for BAR in dict_of_dfs.keys():
    dict_of_dfs[BAR].plot(ax=ax)

External VS2013 build error "error MSB4019: The imported project <path> was not found"

In my case I was using the wrong version of MSBuild.exe.

The version you need to use depends on what version of Visual Studio you used to create your project. In my case I needed 14.0 (having used Visual Studio 2015).

This was found at:

C:\Program Files (x86)\MSBuild\14.0\Bin\msbuild.exe

You can look under:

C:\Program Files (x86)\MSBuild

To find other versions.

Using python PIL to turn a RGB image into a pure black and white image

A PIL only solution for creating a bi-level (black and white) image with a custom threshold:

from PIL import Image
img = Image.open('mB96s.png')
thresh = 200
fn = lambda x : 255 if x > thresh else 0
r = img.convert('L').point(fn, mode='1')
r.save('foo.png')

With just

r = img.convert('1')
r.save('foo.png')

you get a dithered image.

From left to right the input image, the black and white conversion result and the dithered result:

Input Image Black and White Result Dithered Result

You can click on the images to view the unscaled versions.

How can I truncate a double to only two decimal places in Java?

A quick check is to use the Math.floor method. I created a method to check a double for two or less decimal places below:

public boolean checkTwoDecimalPlaces(double valueToCheck) {

    // Get two decimal value of input valueToCheck 
    double twoDecimalValue = Math.floor(valueToCheck * 100) / 100;

    // Return true if the twoDecimalValue is the same as valueToCheck else return false
    return twoDecimalValue == valueToCheck;
}