Programs & Examples On #Buildconfig

Error : Program type already present: android.support.design.widget.CoordinatorLayout$Behavior

Changed all dependencies to compile rather than implementation, then I rebuild the project without errors. Then I switched back to implementation rather than leaving it as compile.

java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex in Android Studio 3.0

I am using Android Studio 3.0 and was facing the same problem. I add this to my gradle:

multiDexEnabled true

And it worked!

Example

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.1'
    defaultConfig {
        applicationId "com.xx.xxx"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        multiDexEnabled true //Add this
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            shrinkResources true
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

And clean the project.

The number of method references in a .dex file cannot exceed 64k API 17

I got this error message because while coding my project auto update compile version in my build.gradle file :

android {
    ...
    buildToolsVersion "23.0.2"
    ...
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0' }

Solve it by correcting the version:

android {
        ...
        buildToolsVersion "23.0.2"
        ...
    }

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.0.1'
    compile 'com.android.support:design:23.0.1'
}

Execution failed for task ':app:processDebugResources' even with latest build tools

Set your compileSdkVersion to 23 in your module's build.gradle file.

Android Error Building Signed APK: keystore.jks not found for signing config 'externalOverride'

This is a problem that can arise from writing down a "filename" instead of a path, while generating the .jks file. Generate a new one, put it on the Desktop (or any other real path) and re-generate APK.

configuring project ':app' failed to find Build Tools revision

It happens because Build Tools revision 24.4.1 doesn't exist.

The latest version is 23.0.2.
These tools is included in the SDK package and installed in the <sdk>/build-tools/ directory.

Don't confuse the Android SDK Tools with SDK Build Tools.

Change in your build.gradle

android {
   buildToolsVersion "23.0.2"
   // ...

}

Android Studio Gradle: Error:Execution failed for task ':app:processDebugGoogleServices'. > No matching client found for package

If this happened to you after renaming your application package name, then you need to update the following:

1)google-services.json file in your application by looking up in the file for "package_name" attribute and update it with the new package name.

2)Update your application client Credentials in Google Developers Console by going to the Credentials and selecting your android client key then update the package name as well with the new one.

Hope this will help.

android : Error converting byte to dex

If you have multiple projects, make sure you are not adding a dependency multiple times, I needed to exclude the other project's dependency like this:

compile(project(':OtherProject-SDK')) {
    compile.exclude module: 'play-services-gcm'
    compile.exclude module: 'play-services-location'
    compile.exclude module: 'support-v4'
    compile.exclude module: 'okhttp'
}

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

same issue i have.

i tired all possible solutions that i found. but non were worked.

always got this error

Cannot add task ':processDebugGoogleServices' as a task with that name already exists

Now, i solved it.

1) first i checked my config.xml

2) and removed unnecessary plugin. (I used firebase fcm plugin for pushnotification, but there was two unnecessary plugin phonegap-plugin-push and cordova-plugin-customurlscheme. I removed both these plugins)

3) then removed platform.

4) then add platform

5) then build it.

6) now it build successfully.

Error:Execution failed for task ':app:transformClassesWithJarMergingForDebug'

Use project root in terminal like this:-/Users/rajnish/Desktop/RankProjects/ProjectCloud

After that enter this command ./gradlew clean

It will work.

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

In my case, I believe this issue was to do with the length of the file path. UNIX and Windows systems impose a maximum path length of 255 and 260 characters respectively, and I believe the crunch process fails when assigning to a dynamically-specified path. So, even if the quoted path lengths in the error message are shorter than the limit (mine was only 187 within a Windows build environment), I think the crunch utility may internally specify a longer path, even if just temporarily.

You may determine whether this is the source of error by moving your project to the root-most directory on your file system, then attempt recompiling.

How to set timeout in Retrofit library?

I found this example

https://github.com/square/retrofit/issues/1557

Here we set custom url client connection client before before we build API rest service implementation.

import com.google.gson.Gson
import com.google.gson.GsonBuilder
import retrofit.Endpoint
import retrofit.RestAdapter
import retrofit.client.Request
import retrofit.client.UrlConnectionClient
import retrofit.converter.GsonConverter


class ClientBuilder {

    public static <T> T buildClient(final Class<T> client, final String serviceUrl) {
        Endpoint mCustomRetrofitEndpoint = new CustomRetrofitEndpoint()


        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()
        RestAdapter.Builder builder = new RestAdapter.Builder()
            .setEndpoint(mCustomRetrofitEndpoint)
            .setConverter(new GsonConverter(gson))
            .setClient(new MyUrlConnectionClient())
        RestAdapter restAdapter = builder.build()
        return restAdapter.create(client)
    }
}

 public final class MyUrlConnectionClient extends UrlConnectionClient {
        @Override
        protected HttpURLConnection openConnection(Request request) {
            HttpURLConnection connection = super.openConnection(request);
            connection.setConnectTimeout(15 * 1000);
            connection.setReadTimeout(30 * 1000);
            return connection;
        }
    }

Android java.exe finished with non-zero exit value 1

Problem RAM. I had similar message in my Messages Gradle Build

Error:Execution failed for task ':app:dexDebug'.
> com.android.ide.common.process.ProcessException: org.gradle.process.internal. 
ExecException: Process 'command 'C:\Program Files\Java\jdk1.8.0_45\bin\java.exe'' 
finished with non-zero exit value 1

Why: I didn't have free RAM on my laptop with the OS windows 8.1.

Solution: I closed a few programs that I don't need. After that, I had more free RAM and my project was built in android studio.

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

As of Android Studio version 0.8.14

You should add:

 android {
     packagingOptions { 
         exclude 'META-INF/LICENSE.txt'
         exclude 'META-INF/NOTICE.txt'
         exclude '...'
     }
 }  

to your build.gradle file.

History:

According to comment 14 in this bug: https://issuetracker.google.com/issues/36982149#comment14 this is a bug in v0.7.0 of the Android Gradle plugin, and is due to be fixed soon in 0.7.1.

Here are the notes from that bug about the addition for 0.7.1:

0.7.1 is out with the fix for this.

The DSL to exclude files is:

android {
    packagingOptions {
        exclude 'META-INF/LICENSE.txt'
    }
}

You can add as many exclude statement as you want. The value is the archive path. No wildcard or glob support yet.

Filenames "LICENSE.txt" and "NOTICE.txt" are case sensitive. Please try out with "license.txt" and "notice.txt" as well.

Where is android studio building my .apk file?

You should Build your app instead of debugging process. Just follow this:

Build -> Build Bundles/APK(s) -> Build APK(s)

enter image description here

Android Studio with Google Play Services

  1. Go to File -> Project Structure
  2. Select 'Project Settings'
  3. Select 'Dependencies' Tab
  4. Click '+' and select '1.Library Dependencies'
  5. Search for : com.google.android.gms:play-services
  6. Select the latest version and click 'OK'

Voila! No need to fight with Gradle :)

Using msbuild to execute a File System Publish Profile

Actually I merged all your answers to my own solution how to solve the above problem:

  1. I create the pubxml file according my needs
  2. Then I copy all the parameters from pubxml file to my own list of parameters "/p:foo=bar" for msbuild.exe
  3. I throw away the pubxml file

The result is like that:

msbuild /t:restore /t:build /p:WebPublishMethod=FileSystem /p:publishUrl=C:\builds\MyProject\ /p:DeleteExistingFiles=True /p:LastUsedPlatform="Any CPU" /p:Configuration=Release

How do I concatenate strings with variables in PowerShell?

You could use the PowerShell equivalent of String.Format - it's usually the easiest way to build up a string. Place {0}, {1}, etc. where you want the variables in the string, put a -f immediately after the string and then the list of variables separated by commas.

Get-ChildItem c:\code|%{'{0}\{1}\{2}.dll' -f $_.fullname,$buildconfig,$_.name}

(I've also taken the dash out of the $buildconfig variable name as I have seen that causes issues before too.)

What is the GAC in .NET?

Right, so basically it's a way to keep DLLs globally accessible without worrying about conflicts. No more DLL Hell. Each architecture and version gets it's own place to live.

It also gets it own way to browse it in Explorer, so if you go to

C:\Windows\assembly

In windows explorer it lists all the DLLs.

But if you fire up cmd, you can see how it's really structured:

C:\Users\tritter>cd C:\Windows\assembly

C:\Windows\assembly>dir

 Directory of C:\Windows\assembly

07/20/2009  02:18 PM    <DIR>          GAC
06/17/2009  04:22 PM    <DIR>          GAC_32
06/17/2009  04:22 PM    <DIR>          GAC_64
06/17/2009  04:22 PM    <DIR>          GAC_MSIL
 ...snip...
               0 File(s)              0 bytes
               9 Dir(s)  90,538,311,680 bytes free

C:\Windows\assembly>cd GAC_64

C:\Windows\assembly\GAC_64>dir

 Directory of C:\Windows\assembly\GAC_64

06/17/2009  04:22 PM    <DIR>          .
06/17/2009  04:22 PM    <DIR>          ..
01/19/2008  09:54 AM    <DIR>          blbproxy
 ...snip...
01/19/2008  09:54 AM    <DIR>          srmlib
01/19/2008  06:11 AM    <DIR>          System.Data
01/19/2008  06:11 AM    <DIR>          System.Data.OracleClient
 ...snip...
               0 File(s)              0 bytes
              34 Dir(s)  90,538,311,680 bytes free

C:\Windows\assembly\GAC_64>cd System.Data

C:\Windows\assembly\GAC_64\System.Data>dir
 Directory of C:\Windows\assembly\GAC_64\System.Data

01/19/2008  06:11 AM    <DIR>          .
01/19/2008  06:11 AM    <DIR>          ..
04/11/2009  12:20 PM    <DIR>          2.0.0.0__b77a5c561934e089
               0 File(s)              0 bytes
               3 Dir(s)  90,538,311,680 bytes free

C:\Windows\assembly\GAC_64\System.Data>cd 2.0.0.0__b77a5c561934e089

C:\Windows\assembly\GAC_64\System.Data\2.0.0.0__b77a5c561934e089>dir

 Directory of C:\Windows\assembly\GAC_64\System.Data\2.0.0.0__b77a5c561934e089

04/11/2009  12:20 PM    <DIR>          .
04/11/2009  12:20 PM    <DIR>          ..
04/11/2009  12:12 PM         3,008,512 System.Data.dll
               1 File(s)      3,008,512 bytes
               2 Dir(s)  90,538,311,680 bytes free

C:\Windows\assembly\GAC_64\System.Data\2.0.0.0__b77a5c561934e089>

Here you can see version 2.0.0.0__b77a5c561934e089 of System.Data.

A DLL is identified by 5 parts:

  1. Name
  2. Version
  3. Architecture
  4. Culture
  5. Public Key

Although the first 3 are generally the big ones.

Difference between Inheritance and Composition

Composition is where something is made up of distinct parts and it has a strong relationship with those parts. If the main part dies so do the others, they cannot have a life of their own. A rough example is the human body. Take out the heart and all the other parts die away.

Inheritance is where you just take something that already exists and use it. There is no strong relationship. A person could inherit his fathers estate but he can do without it.

I don't know Java so I cannot provide an example but I can provide an explanation of the concepts.

Why does Math.Round(2.5) return 2 instead of 3?

Firstly, this wouldn't be a C# bug anyway - it would be a .NET bug. C# is the language - it doesn't decide how Math.Round is implemented.

And secondly, no - if you read the docs, you'll see that the default rounding is "round to even" (banker's rounding):

Return Value
Type: System.Double
The integer nearest a. If the fractional component of a is halfway between two integers, one of which is even and the other odd, then the even number is returned. Note that this method returns a Double instead of an integral type.

Remarks
The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding. It minimizes rounding errors that result from consistently rounding a midpoint value in a single direction.

You can specify how Math.Round should round mid-points using an overload which takes a MidpointRounding value. There's one overload with a MidpointRounding corresponding to each of the overloads which doesn't have one:

Whether this default was well chosen or not is a different matter. (MidpointRounding was only introduced in .NET 2.0. Before then I'm not sure there was any easy way of implementing the desired behaviour without doing it yourself.) In particular, history has shown that it's not the expected behaviour - and in most cases that's a cardinal sin in API design. I can see why Banker's Rounding is useful... but it's still a surprise to many.

You may be interested to take a look at the nearest Java equivalent enum (RoundingMode) which offers even more options. (It doesn't just deal with midpoints.)

How do I get a file name from a full path with PHP?

<?php

  $windows = "F:\Program Files\SSH Communications Security\SSH Secure Shell\Output.map";

  /* str_replace(find, replace, string, count) */
  $unix    = str_replace("\\", "/", $windows);

  print_r(pathinfo($unix, PATHINFO_BASENAME));

?> 

_x000D_
_x000D_
body, html, iframe { _x000D_
  width: 100% ;_x000D_
  height: 100% ;_x000D_
  overflow: hidden ;_x000D_
}
_x000D_
<iframe src="https://ideone.com/Rfxd0P"></iframe>
_x000D_
_x000D_
_x000D_

Align button at the bottom of div using CSS

You can use position:absolute; to absolutely position an element within a parent div. When using position:absolute; the element will be positioned absolutely from the first positioned parent div, if it can't find one it will position absolutely from the window so you will need to make sure the content div is positioned.

To make the content div positioned, all position values that aren't static will work, but relative is the easiest since it doesn't change the divs positioning by itself.

So add position:relative; to the content div, remove the float from the button and add the following css to the button:

position: absolute;
right:    0;
bottom:   0;

Duplicate Symbols for Architecture arm64

For me, I created a method called sampleMethod in ViewController_A and created the same method in ViewController_B too, It caused me this error, then i changed the method name in ViewController_B to secondSampleMethod. It fixed the error.

Seems like a Good feature to reduce the code and not to duplicate the same code in many places.

I tried changing the No Common blocks from Yes to No then enabling testability from Yes to No. It didn't worked. I Checked duplicate files also in build phases, but there is no duplicate files.

Adding rows dynamically with jQuery

This will get you close, the add button has been removed out of the table so you might want to consider this...

<script type="text/javascript">
    $(document).ready(function() {
        $("#add").click(function() {
          $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
          return false;
        });
    });
</script>

HTML markup looks like this

  <a  id="add">+</a></td>
  <table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
  <tbody>
    <tr>
      <td>Name</td>
    </tr>
    <tr class="person">
      <td><input type="text" name="name" id="name" /></td>
    </tr>
    </tbody>
  </table>

EDIT To empty a value of a textbox after insert..

    $('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
    $('#mytable tbody>tr:last #name').val('');
    return false;

EDIT2 Couldn't help myself, to reset all dropdown lists in the inserted TR you can do this

$("#mytable tbody>tr:last").each(function() {this.reset();});           

I will leave the rest to you!

How to copy a file to multiple directories using the gnu cp command

This will copy to the immediate sub-directories, if you want to go deeper, adjust the -maxdepth parameter.

find . -mindepth 1 -maxdepth 1 -type d| xargs -n 1 cp -i index.html

If you don't want to copy to all directories, hopefully you can filter the directories you are not interested in. Example copying to all folders starting with a

find . -mindepth 1 -maxdepth 1 -type d| grep \/a |xargs -n 1 cp -i index.html

If copying to a arbitrary/disjoint set of directories you'll need Robert Gamble's suggestion.

Android AlertDialog Single Button

Another approach

Builder alert = new AlertDialog.Builder(ActivityName.this);
alert.setTitle("Doctor");
alert.setMessage("message");
alert.setPositiveButton("OK",null);
alert.show(); 

Bonus

AlertDialog.Builder builder = new AlertDialog.Builder(YourActivityName.this);
builder.setMessage("Message dialog with three buttons");

       builder.setPositiveButton("YES", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                //do things
           }
       });

      builder.setNegativeButton("NO", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                //do things
           }
       });

       builder.setNeutralButton("CANCEL", new DialogInterface.OnClickListener()     {
           public void onClick(DialogInterface dialog, int id) {
                //do things
           }
       });
AlertDialog alert = builder.create();
alert.show();

Now it is up to you to use one,two or three buttons..

How to verify a method is called two times with mockito verify()

build gradle:

testImplementation "com.nhaarman.mockitokotlin2:mockito-kotlin:2.2.0"

code:

interface MyCallback {
  fun someMethod(value: String)
}

class MyTestableManager(private val callback: MyCallback){
  fun perform(){
    callback.someMethod("first")
    callback.someMethod("second")
    callback.someMethod("third")
  }
}

test:

import com.nhaarman.mockitokotlin2.times
import com.nhaarman.mockitokotlin2.verify
import com.nhaarman.mockitokotlin2.mock
...
val callback: MyCallback = mock()
val manager = MyTestableManager(callback)
manager.perform()

val captor: KArgumentCaptor<String> = com.nhaarman.mockitokotlin2.argumentCaptor<String>()

verify(callback, times(3)).someMethod(captor.capture())

assertTrue(captor.allValues[0] == "first")
assertTrue(captor.allValues[1] == "second")
assertTrue(captor.allValues[2] == "third")

How do I change the figure size for a seaborn plot?

You need to create the matplotlib Figure and Axes objects ahead of time, specifying how big the figure is:

from matplotlib import pyplot
import seaborn

import mylib

a4_dims = (11.7, 8.27)
df = mylib.load_data()
fig, ax = pyplot.subplots(figsize=a4_dims)
seaborn.violinplot(ax=ax, data=df, **violin_options)

What column type/length should I use for storing a Bcrypt hashed password in a Database?

If you are using PHP's password_hash() with the PASSWORD_DEFAULT algorithm to generate the bcrypt hash (which I would assume is a large percentage of people reading this question) be sure to keep in mind that in the future password_hash() might use a different algorithm as the default and this could therefore affect the length of the hash (but it may not necessarily be longer).

From the manual page:

Note that this constant is designed to change over time as new and stronger algorithms are added to PHP. For that reason, the length of the result from using this identifier can change over time. Therefore, it is recommended to store the result in a database column that can expand beyond 60 characters (255 characters would be a good choice).

Using bcrypt, even if you have 1 billion users (i.e. you're currently competing with facebook) to store 255 byte password hashes it would only ~255 GB of data - about the size of a smallish SSD hard drive. It is extremely unlikely that storing the password hash is going to be the bottleneck in your application. However in the off chance that storage space really is an issue for some reason, you can use PASSWORD_BCRYPT to force password_hash() to use bcrypt, even if that's not the default. Just be sure to stay informed about any vulnerabilities found in bcrypt and review the release notes every time a new PHP version is released. If the default algorithm is ever changed it would be good to review why and make an informed decision whether to use the new algorithm or not.

SQL RANK() over PARTITION on joined tables

SELECT a.C_ID,a.QRY_ID,a.RES_ID,b.SCORE,ROW_NUMBER() OVER (ORDER BY SCORE DESC) AS [RANK]
FROM CONTACTS a JOIN RSLTS b ON a.QRY_ID=b.QRY_ID AND a.RES_ID=b.RES_ID
ORDER BY a.C_ID

blur vs focusout -- any real differences?

The documentation for focusout says (emphasis mine):

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

The same distinction exists between the focusin and focus events.

Android Lint contentDescription warning

Go to Gradle file (module app), add below code block

android {
    ... 
    lintOptions {
        disable 'ContentDescription'
    }
    ...
}

No more warning! happy coding

Is there a way to split a widescreen monitor in to two or more virtual monitors?

It seems a window manager is what you want. The problem is finding one that works.

I use a tiling window manager in Linux (dwm) and it seems to do exactly what you are after, PLUS it has multiple workspaces which is what I thought you were going for at first.

A tiling window manager has no concept of "maximized" windows. All windows take up the full amount of space that they are allotted, and they never overlap. When you only have one window up on the screen, it gets the full screen. Open up another window, and it opens next to the first, while the first re-sizes automatically to take up only part of the screen. In dwm, the split between them is adjustable with keystrokes. Additional windows each take up their own allotted space on the screen, and any existing windows re-size to accommodate them depending on the particular layout you have chosen.

Workspaces use "tags"; any window can have one or more tags, and you can choose to see any windows that have one or more of a certain set of tags at a time. Thus you can hide windows that you don't want to see, and let the other windows take up more space.

Unfortunately, the few tiling add-ons I've tried for Windows don't work anywhere near as well. Although dwm has a few quirks with certain apps that use an SDI-style interface like Gimp or Pidgin (you can set windows as "floating" above the tiled layout to work around this), I've never had it get confused about where my windows are or shove windows off the screen like some of the window managers I've tried on Windows. If anyone knows of something with equivalent functionality that actually WORKS on Windows, I would love to know about it.

How to change the window title of a MATLAB plotting figure?

It can also be done this way:

figure(xx);
set(gcf, 'name', 'Name goes here')

gcf gets the current figure handle.

PHP: Split string

to explode with '.' use

explode('\\.','a.b');

Remove all whitespace from C# string with regex

Instead of a RegEx use Replace for something that simple:

LastName = LastName.Replace(" ", String.Empty);

Display an image into windows forms

There could be many reasons for this. A few that come up quickly to my mind:

  1. Did you call this routine AFTER InitializeComponent()?
  2. Is the path syntax you are using correct? Does it work if you try it in the debugger? Try using backslash (\) instead of Slash (/) and see.
  3. This may be due to side-effects of some other code in your form. Try using the same code in a blank Form (with just the constructor and this function) and check.

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Please use chomp() or chomp() with STDIN

i.e. test1.rb

print 'Enter File name: '

fname = STDIN.gets.chomp()  # or fname = gets.chomp()


fname_read = File.open(fname)

puts fname_read.read()

keyCode values for numeric keypad?

The answer by @.A. Morel I find to be the best easy to understand solution with a small footprint. Just wanted to add on top if you want a smaller code amount this solution which is a modification of Morel works well for not allowing letters of any sort including inputs notorious 'e' character.

function InputTypeNumberDissallowAllCharactersExceptNumeric() {
  let key = Number(inputEvent.key);
  return !isNaN(key);
}

Foreach loop in C++ equivalent of C#

After getting used to the var keyword in C#, I'm starting to use the auto keyword in C++11. They both determine type by inference and are useful when you just want the compiler to figure out the type for you. Here's the C++11 port of your code:

#include <array>
#include <string>

using namespace std;

array<string, 3> strarr = {"ram", "mohan", "sita"};
for(auto str: strarr) {
  listbox.items.add(str);
}

QLabel: set color of text and background

This one is working perfect

QColorDialog *dialog = new QColorDialog(this);
QColor color=  dialog->getColor();
QVariant variant= color;
QString colcode = variant.toString();
ui->label->setStyleSheet("QLabel { background-color :"+colcode+" ; color : blue; }");

getColor() method returns the selected color. You can change label color using stylesheet

jQuery Dialog Box

I encountered the same issue (dialog would only open once, after closing, it wouldn't open again), and tried the solutions above which did not fix my problem. I went back to the docs and realized I had a fundamental misunderstanding of how the dialog works.

The $('#myDiv').dialog() command creates/instantiates the dialog, but is not necessarily the proper way to open it. The proper way to open it is to instantiate the dialog with dialog(), then use dialog('open') to display it, and dialog('close') to close/hide it. This means you'll probably want to set the autoOpen option to false.

So the process is: instantiate the dialog on document ready, then listen for the click or whatever action you want to show the dialog. Then it will work, time after time!

<script type="text/javascript"> 
        jQuery(document).ready( function(){       
            jQuery("#myButton").click( showDialog );

            //variable to reference window
            $myWindow = jQuery('#myDiv');

            //instantiate the dialog
            $myWindow.dialog({ height: 350,
                width: 400,
                modal: true,
                position: 'center',
                autoOpen:false,
                title:'Hello World',
                overlay: { opacity: 0.5, background: 'black'}
                });
            }

        );
    //function to show dialog   
    var showDialog = function() {
        //if the contents have been hidden with css, you need this
        $myWindow.show(); 
        //open the dialog
        $myWindow.dialog("open");
        }

    //function to close dialog, probably called by a button in the dialog
    var closeDialog = function() {
        $myWindow.dialog("close");
    }


</script>
</head>

<body>

<input id="myButton" name="myButton" value="Click Me" type="button" />
<div id="myDiv" style="display:none">
    <p>I am a modal dialog</p>
</div>

Key error when selecting columns in pandas dataframe after read_csv

use sep='\s*,\s*' so that you will take care of spaces in column-names:

transactions = pd.read_csv('transactions.csv', sep=r'\s*,\s*',
                           header=0, encoding='ascii', engine='python')

alternatively you can make sure that you don't have unquoted spaces in your CSV file and use your command (unchanged)

prove:

print(transactions.columns.tolist())

Output:

['product_id', 'customer_id', 'store_id', 'promotion_id', 'month_of_year', 'quarter', 'the_year', 'store_sales', 'store_cost', 'unit_sales', 'fact_count']

csv.Error: iterator should return strings, not bytes

In Python3, csv.reader expects, that passed iterable returns strings, not bytes. Here is one more solution to this problem, that uses codecs module:

import csv
import codecs
ifile  = open('sample.csv', "rb")
read = csv.reader(codecs.iterdecode(ifile, 'utf-8'))
for row in read :
    print (row) 

if condition in sql server update query

this worked great:

UPDATE
    table_Name
SET 
  column_A = CASE WHEN @flag = '1' THEN column_A + @new_value ELSE column_A END,
  column_B = CASE WHEN @flag = '0' THEN column_B + @new_value ELSE column_B END
WHERE
    ID = @ID

Sequelize OR condition object

In Sequelize version 5 you might also can use this way (full use Operator Sequelize) :

var condition = 
{ 
  [Op.or]: [ 
   { 
     LastName: {
      [Op.eq]: "Doe"
      },
    },
   { 
     FirstName: {
      [Op.or]: ["John", "Jane"]
      }
   },
   {
      Age:{
        [Op.gt]: 18
      }
    }
 ]
}

And then, you must include this :

const Op = require('Sequelize').Op

and pass it in :

Student.findAll(condition)
.success(function(students){ 
//
})

It could beautifully generate SQL like this :

"SELECT * FROM Student WHERE LastName='Doe' OR FirstName in ("John","Jane") OR Age>18"

Get current location of user in Android without using GPS or internet

It appears that it is possible to track a smart phone without using GPS.

Sources:

Primary: "PinMe: Tracking a Smartphone User around the World"

Secondary: "How to Track a Cellphone Without GPS—or Consent"

I have not yet found a link to the team's final code. When I do I will post, if another has not done so.

What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab

The Request Payload - or to be more precise: payload body of a HTTP Request - is the data normally send by a POST or PUT Request. It's the part after the headers and the CRLF of a HTTP Request.

A request with Content-Type: application/json may look like this:

POST /some-path HTTP/1.1
Content-Type: application/json

{ "foo" : "bar", "name" : "John" }

If you submit this per AJAX the browser simply shows you what it is submitting as payload body. That’s all it can do because it has no idea where the data is coming from.

If you submit a HTML-Form with method="POST" and Content-Type: application/x-www-form-urlencoded or Content-Type: multipart/form-data your request may look like this:

POST /some-path HTTP/1.1
Content-Type: application/x-www-form-urlencoded

foo=bar&name=John

In this case the form-data is the request payload. Here the Browser knows more: it knows that bar is the value of the input-field foo of the submitted form. And that’s what it is showing to you.

So, they differ in the Content-Type but not in the way data is submitted. In both cases the data is in the message-body. And Chrome distinguishes how the data is presented to you in the Developer Tools.

How can I combine multiple nested Substitute functions in Excel?

  • nesting SUBSTITUTE() in a string can be nasty, however, it's always possible to arrange it:

Screenshot formula bar

How can I truncate a string to the first 20 words in PHP?

Here is what I have implemented.

function summaryMode($text, $limit, $link) {
    if (str_word_count($text, 0) > $limit) {
        $numwords = str_word_count($text, 2);
        $pos = array_keys($numwords);
        $text = substr($text, 0, $pos[$limit]).'... <a href="'.$link.'">Read More</a>';
    }
    return $text;
}

As you can see it is based off karim79's answer, all that needed changing was that the if statement also needed to check against words not characters.

I also added a link to main function for convenience. So far it hsa worked flawlessly. Thanks to the original solution provider.

CreateProcess: No such file or directory

I had this same problem and none of the suggested fixes worked for me. So even though this is an old thread, I figure I might as well post my solution in case someone else finds this thread through Google(like I did).

For me, I had to uninstall MinGW/delete the MinGW folder, and re-install. After re-installing it works like a charm.

What is :: (double colon) in Python when subscripting sequences?

seq[::n] is a sequence of each n-th item in the entire sequence.

Example:

>>> range(10)[::2]
[0, 2, 4, 6, 8]

The syntax is:

seq[start:end:step]

So you can do (in Python 2):

>>> range(100)[5:18:2]
[5, 7, 9, 11, 13, 15, 17]

The apk must be signed with the same certificates as the previous version

I had faced this issue recently, after trying different ways to sign in like enable V1 Or V2, signed in by changing alias name and last come to know that I am using wrong key store file

SMTP error 554

SMTP error 554 is one of the more vague error codes, but is typically caused by the receiving server seeing something in the From or To headers that it doesn't like. This can be caused by a spam trap identifying your machine as a relay, or as a machine not trusted to send mail from your domain.

We ran into this problem recently when adding a new server to our array, and we fixed it by making sure that we had the correct reverse DNS lookup set up.

replace NULL with Blank value or Zero in sql server

Different ways to replace NULL in sql server

Replacing NULL value using:

1. ISNULL() function

2. COALESCE() function

3. CASE Statement

SELECT Name as EmployeeName, ISNULL(Bonus,0) as EmployeeBonus from tblEmployee

SELECT Name as EmployeeName, COALESCE(Bonus, 0) as EmployeeBonus 
FROM tblEmployee

SELECT Name as EmployeeName, CASE WHEN Bonus IS NULL THEN 0 
ELSE Bonus  END as EmployeeBonus 
FROM  tblEmployee

What is for Python what 'explode' is for PHP?

The alternative for explode in php is split.

The first parameter is the delimiter, the second parameter the maximum number splits. The parts are returned without the delimiter present (except possibly the last part). When the delimiter is None, all whitespace is matched. This is the default.

>>> "Rajasekar SP".split()
['Rajasekar', 'SP']

>>> "Rajasekar SP".split('a',2)
['R','j','sekar SP']

Display html text in uitextview

You can also use one more way. Three20 library offers a method through which we can construct a styled textView. You can get the library here: http://github.com/facebook/three20/

The class TTStyledTextLabel has a method called textFromXHTML: I guess this would serve the purpose. But it would be possible in readonly mode. I don't think it will allow to write or edit HTML content.

There is also a question which can help you regarding this: HTML String content for UILabel and TextView

I hope its helpful.

SQL to LINQ Tool

I know that this isn't what you asked for but LINQPad is a really great tool to teach yourself LINQ (and it's free :o).

When time isn't critical, I have been using it for the last week or so instead or a query window in SQL Server and my LINQ skills are getting better and better.

It's also a nice little code snippet tool. Its only downside is that the free version doesn't have IntelliSense.

How to make inline plots in Jupyter Notebook larger?

If you only want the image of your figure to appear larger without changing the general appearance of your figure increase the figure resolution. Changing the figure size as suggested in most other answers will change the appearance since font sizes do not scale accordingly.

import matplotlib.pylab as plt
plt.rcParams['figure.dpi'] = 200

How do I change UIView Size?

Assigning questionFrame.frame.size.height= screenSize.height * 0.30 will not reflect anything in the view. because it is a get-only property. If you want to change the frame of questionFrame you can use the below code.

questionFrame.frame = CGRect(x: 0, y: 0, width: 0, height: screenSize.height * 0.70)

Gridview with two columns and auto resized images

Here's a relatively easy method to do this. Throw a GridView into your layout, setting the stretch mode to stretch the column widths, set the spacing to 0 (or whatever you want), and set the number of columns to 2:

res/layout/main.xml

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

    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="0dp"
        android:horizontalSpacing="0dp"
        android:stretchMode="columnWidth"
        android:numColumns="2"/>

</FrameLayout>

Make a custom ImageView that maintains its aspect ratio:

src/com/example/graphicstest/SquareImageView.java

public class SquareImageView extends ImageView {
    public SquareImageView(Context context) {
        super(context);
    }

    public SquareImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); //Snap to width
    }
}

Make a layout for a grid item using this SquareImageView and set the scaleType to centerCrop:

res/layout/grid_item.xml

<?xml version="1.0" encoding="utf-8"?>

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

    <com.example.graphicstest.SquareImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="centerCrop"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:paddingTop="15dp"
        android:paddingBottom="15dp"
        android:layout_gravity="bottom"
        android:textColor="@android:color/white"
        android:background="#55000000"/>

</FrameLayout>

Now make some sort of adapter for your GridView:

src/com/example/graphicstest/MyAdapter.java

private final class MyAdapter extends BaseAdapter {
    private final List<Item> mItems = new ArrayList<Item>();
    private final LayoutInflater mInflater;

    public MyAdapter(Context context) {
        mInflater = LayoutInflater.from(context);

        mItems.add(new Item("Red",       R.drawable.red));
        mItems.add(new Item("Magenta",   R.drawable.magenta));
        mItems.add(new Item("Dark Gray", R.drawable.dark_gray));
        mItems.add(new Item("Gray",      R.drawable.gray));
        mItems.add(new Item("Green",     R.drawable.green));
        mItems.add(new Item("Cyan",      R.drawable.cyan));
    }

    @Override
    public int getCount() {
        return mItems.size();
    }

    @Override
    public Item getItem(int i) {
        return mItems.get(i);
    }

    @Override
    public long getItemId(int i) {
        return mItems.get(i).drawableId;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v = view;
        ImageView picture;
        TextView name;

        if (v == null) {
            v = mInflater.inflate(R.layout.grid_item, viewGroup, false);
            v.setTag(R.id.picture, v.findViewById(R.id.picture));
            v.setTag(R.id.text, v.findViewById(R.id.text));
        }

        picture = (ImageView) v.getTag(R.id.picture);
        name = (TextView) v.getTag(R.id.text);

        Item item = getItem(i);

        picture.setImageResource(item.drawableId);
        name.setText(item.name);

        return v;
    }

    private static class Item {
        public final String name;
        public final int drawableId;

        Item(String name, int drawableId) {
            this.name = name;
            this.drawableId = drawableId;
        }
    }
}

Set that adapter to your GridView:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    GridView gridView = (GridView)findViewById(R.id.gridview);
    gridView.setAdapter(new MyAdapter(this));
}

And enjoy the results:

Example GridView

What does "app.run(host='0.0.0.0') " mean in Flask

To answer to your second question. You can just hit the IP address of the machine that your flask app is running, e.g. 192.168.1.100 in a browser on different machine on the same network and you are there. Though, you will not be able to access it if you are on a different network. Firewalls or VLans can cause you problems with reaching your application. If that computer has a public IP, then you can hit that IP from anywhere on the planet and you will be able to reach the app. Usually this might impose some configuration, since most of the public servers are behind some sort of router or firewall.

How do you run a Python script as a service in Windows?

The simplest way is to use the: NSSM - the Non-Sucking Service Manager. Just download and unzip to a location of your choosing. It's a self-contained utility, around 300KB (much less than installing the entire pywin32 suite just for this purpose) and no "installation" is needed. The zip contains a 64-bit and a 32-bit version of the utility. Either should work well on current systems (you can use the 32-bit version to manage services on 64-bit systems).

GUI approach

1 - install the python program as a service. Open a Win prompt as admin

c:\>nssm.exe install WinService

2 - On NSSM´s GUI console:

path: C:\Python27\Python27.exe

Startup directory: C:\Python27

Arguments: c:\WinService.py

3 - check the created services on services.msc

Scripting approach (no GUI)

This is handy if your service should be part of an automated, non-interactive procedure, that may be beyond your control, such as a batch or installer script. It is assumed that the commands are executed with administrative privileges.

For convenience the commands are described here by simply referring to the utility as nssm.exe. It is advisable, however, to refer to it more explicitly in scripting with its full path c:\path\to\nssm.exe, since it's a self-contained executable that may be located in a private path that the system is not aware of.

1. Install the service

You must specify a name for the service, the path to the proper Python executable, and the path to the script:

nssm.exe install ProjectService "c:\path\to\python.exe" "c:\path\to\project\app\main.py"

More explicitly:

nssm.exe install ProjectService 
nssm.exe set ProjectService Application "c:\path\to\python.exe"
nssm.exe set ProjectService AppParameters "c:\path\to\project\app\main.py"

Alternatively you may want your Python app to be started as a Python module. One easy approach is to tell nssm that it needs to change to the proper starting directory, as you would do yourself when launching from a command shell:

nssm.exe install ProjectService "c:\path\to\python.exe" "-m app.main"
nssm.exe set ProjectService AppDirectory "c:\path\to\project"

This approach works well with virtual environments and self-contained (embedded) Python installs. Just make sure to have properly resolved any path issues in those environments with the usual methods. nssm has a way to set environment variables (e.g. PYTHONPATH) if needed, and can also launch batch scripts.

2. To start the service

nssm.exe start ProjectService 

3. To stop the service

nssm.exe stop ProjectService

4. To remove the service, specify the confirm parameter to skip the interactive confirmation.

nssm.exe remove ProjectService confirm

Finding repeated words on a string and counting the repetitions

If this is a homework, then all I can say is: use String.split() and HashMap<String,Integer>.

(I see you've found split() already. You're along the right lines then.)

How to end C++ code

Dude... exit() function is defined under stdlib.h

So you need to add a preprocessor.

Put include stdlib.h in the header section

Then use exit(); wherever you like but remember to put an interger number in the parenthesis of exit.

for example:

exit(0);

Bootstrap center heading

Bootstrap comes with many pre-build classes and one of them is class="text-left". Please call this class whenever needed. :-)

port 8080 is already in use and no process using 8080 has been listed

In windows " wmic process where processid="pid of the process running" get commandline " worked for me. The culprit was wrapper.exe process of webhuddle jboss soft.

Convert float to string with precision & number of decimal digits specified?

A typical way would be to use stringstream:

#include <iomanip>
#include <sstream>

double pi = 3.14159265359;
std::stringstream stream;
stream << std::fixed << std::setprecision(2) << pi;
std::string s = stream.str();

See fixed

Use fixed floating-point notation

Sets the floatfield format flag for the str stream to fixed.

When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part.

and setprecision.


For conversions of technical purpose, like storing data in XML or JSON file, C++17 defines to_chars family of functions.

Assuming a compliant compiler (which we lack at the time of writing), something like this can be considered:

#include <array>
#include <charconv>

double pi = 3.14159265359;
std::array<char, 128> buffer;
auto [ptr, ec] = std::to_chars(buffer.data(), buffer.data() + buffer.size(), pi,
                               std::chars_format::fixed, 2);
if (ec == std::errc{}) {
    std::string s(buffer.data(), ptr);
    // ....
}
else {
    // error handling
}

How to insert an object in an ArrayList at a specific position

This method Appends the specified element to the end of this list.

add(E e) //append element to the end of the arraylist.

This method Inserts the specified element at the specified position in this list.

void add(int index, E element) //inserts element at the given position in the array list.

This method Replaces the element at the specified position in this list with the specified element.

set(int index, E element) //Replaces the element at the specified position in this list with the specified element.
      

      

How do AX, AH, AL map onto EAX?

no your ans is Wrong

Selection of Al and Ah is from AX not from EAX

e.g

EAX=0000 0000 0000 0000 0000 0000 0000 0111

So if we call AX it should return

0000 0000 0000 0111

if we call AH it should return

0000 0000

and when we call AL it should return

0000 0111

Example number 2

EAX: 22 33 55 77
AX: 55 77
AH: 55    
AL: 77

example 3

EAX: 1111 0000 0000 0000 0000 0000 0000 0111    
AX= 0000 0000 0000 0111
AH= 0000 0000
AL= 0000 0111  

How do you run a SQL Server query from PowerShell?

There isn't a built-in "PowerShell" way of running a SQL query. If you have the SQL Server tools installed, you'll get an Invoke-SqlCmd cmdlet.

Because PowerShell is built on .NET, you can use the ADO.NET API to run your queries.

Calling a javascript function in another js file

Use cache if your server allows it to improve speed.

var extern =(url)=> {           // load extern javascript
    let scr = $.extend({}, {
        dataType: 'script',
        cache: true,
        url: url
    });
    return $.ajax(scr);
}
function ext(file, func) {
    extern(file).done(func);    // calls a function from an extern javascript file
}

And then use it like this:

ext('somefile.js',()=>              
    myFunc(args)
);  

Optionally, make a prototype of it to have it more flexible. So that you don't have to define the file every time, if you call a function or if you want to fetch code from multiple files.

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

Thank you, user374559 and reneD -- that code and description is very helpful.

My stab at some Python to parse and print out the information in a Unix ls-l like format:

#!/usr/bin/env python
import sys

def getint(data, offset, intsize):
    """Retrieve an integer (big-endian) and new offset from the current offset"""
    value = 0
    while intsize > 0:
        value = (value<<8) + ord(data[offset])
        offset = offset + 1
        intsize = intsize - 1
    return value, offset

def getstring(data, offset):
    """Retrieve a string and new offset from the current offset into the data"""
    if data[offset] == chr(0xFF) and data[offset+1] == chr(0xFF):
        return '', offset+2 # Blank string
    length, offset = getint(data, offset, 2) # 2-byte length
    value = data[offset:offset+length]
    return value, (offset + length)

def process_mbdb_file(filename):
    mbdb = {} # Map offset of info in this file => file info
    data = open(filename).read()
    if data[0:4] != "mbdb": raise Exception("This does not look like an MBDB file")
    offset = 4
    offset = offset + 2 # value x05 x00, not sure what this is
    while offset < len(data):
        fileinfo = {}
        fileinfo['start_offset'] = offset
        fileinfo['domain'], offset = getstring(data, offset)
        fileinfo['filename'], offset = getstring(data, offset)
        fileinfo['linktarget'], offset = getstring(data, offset)
        fileinfo['datahash'], offset = getstring(data, offset)
        fileinfo['unknown1'], offset = getstring(data, offset)
        fileinfo['mode'], offset = getint(data, offset, 2)
        fileinfo['unknown2'], offset = getint(data, offset, 4)
        fileinfo['unknown3'], offset = getint(data, offset, 4)
        fileinfo['userid'], offset = getint(data, offset, 4)
        fileinfo['groupid'], offset = getint(data, offset, 4)
        fileinfo['mtime'], offset = getint(data, offset, 4)
        fileinfo['atime'], offset = getint(data, offset, 4)
        fileinfo['ctime'], offset = getint(data, offset, 4)
        fileinfo['filelen'], offset = getint(data, offset, 8)
        fileinfo['flag'], offset = getint(data, offset, 1)
        fileinfo['numprops'], offset = getint(data, offset, 1)
        fileinfo['properties'] = {}
        for ii in range(fileinfo['numprops']):
            propname, offset = getstring(data, offset)
            propval, offset = getstring(data, offset)
            fileinfo['properties'][propname] = propval
        mbdb[fileinfo['start_offset']] = fileinfo
    return mbdb

def process_mbdx_file(filename):
    mbdx = {} # Map offset of info in the MBDB file => fileID string
    data = open(filename).read()
    if data[0:4] != "mbdx": raise Exception("This does not look like an MBDX file")
    offset = 4
    offset = offset + 2 # value 0x02 0x00, not sure what this is
    filecount, offset = getint(data, offset, 4) # 4-byte count of records 
    while offset < len(data):
        # 26 byte record, made up of ...
        fileID = data[offset:offset+20] # 20 bytes of fileID
        fileID_string = ''.join(['%02x' % ord(b) for b in fileID])
        offset = offset + 20
        mbdb_offset, offset = getint(data, offset, 4) # 4-byte offset field
        mbdb_offset = mbdb_offset + 6 # Add 6 to get past prolog
        mode, offset = getint(data, offset, 2) # 2-byte mode field
        mbdx[mbdb_offset] = fileID_string
    return mbdx

def modestr(val):
    def mode(val):
        if (val & 0x4): r = 'r'
        else: r = '-'
        if (val & 0x2): w = 'w'
        else: w = '-'
        if (val & 0x1): x = 'x'
        else: x = '-'
        return r+w+x
    return mode(val>>6) + mode((val>>3)) + mode(val)

def fileinfo_str(f, verbose=False):
    if not verbose: return "(%s)%s::%s" % (f['fileID'], f['domain'], f['filename'])
    if (f['mode'] & 0xE000) == 0xA000: type = 'l' # symlink
    elif (f['mode'] & 0xE000) == 0x8000: type = '-' # file
    elif (f['mode'] & 0xE000) == 0x4000: type = 'd' # dir
    else: 
        print >> sys.stderr, "Unknown file type %04x for %s" % (f['mode'], fileinfo_str(f, False))
        type = '?' # unknown
    info = ("%s%s %08x %08x %7d %10d %10d %10d (%s)%s::%s" % 
            (type, modestr(f['mode']&0x0FFF) , f['userid'], f['groupid'], f['filelen'], 
             f['mtime'], f['atime'], f['ctime'], f['fileID'], f['domain'], f['filename']))
    if type == 'l': info = info + ' -> ' + f['linktarget'] # symlink destination
    for name, value in f['properties'].items(): # extra properties
        info = info + ' ' + name + '=' + repr(value)
    return info

verbose = True
if __name__ == '__main__':
    mbdb = process_mbdb_file("Manifest.mbdb")
    mbdx = process_mbdx_file("Manifest.mbdx")
    for offset, fileinfo in mbdb.items():
        if offset in mbdx:
            fileinfo['fileID'] = mbdx[offset]
        else:
            fileinfo['fileID'] = "<nofileID>"
            print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
        print fileinfo_str(fileinfo, verbose)

Python: finding lowest integer

Or no float conversion at all by just specifying floats in the list.

l = [-1.2, 0.0, 1]
x = min(l)

or

l = min([-1.2, 0.0, 1])

Upgrading React version and it's dependencies by reading package.json

Yes, you can use Yarn or NPM to edit your package.json.

yarn upgrade [package | package@tag | package@version | @scope/]... [--ignore-engines] [--pattern]

Something like:

yarn upgrade react@^16.0.0

Then I'd see what warns or errors out and then run yarn upgrade [package]. No need to edit the file manually. Can do everything from the CLI.

Or just run yarn upgrade to update all packages to latest, probably a bad idea for a large project. APIs may change, things may break.

Alternatively, with NPM run npm outdated to see what packages will be affected. Then

npm update

https://yarnpkg.com/lang/en/docs/cli/upgrade/

https://docs.npmjs.com/getting-started/updating-local-packages

Insert/Update Many to Many Entity Framework . How do I do it?

In entity framework, when object is added to context, its state changes to Added. EF also changes state of each object to added in object tree and hence you are either getting primary key violation error or duplicate records are added in table.

Failure [INSTALL_FAILED_INVALID_APK]

i got similar issue once, what i observed was, package name in my Androidmanifest.xml was started with one empty space character. like " com.example.test" instead of "com.example.test"

I removed all such invalid spaces from my manifest file, it solved my problem

Edit 1: '-' in package name also cause same issue on some android versions

Set the value of a variable with the result of a command in a Windows batch file

To do what Jesse describes, from a Windows batch file you will need to write:

for /f "delims=" %%a in ('ver') do @set foobar=%%a 

But, I instead suggest using Cygwin on your Windows system if you are used to Unix-type scripting.

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

You have an error in you script tag construction, this:

<script language="JavaScript" type="text/javascript" script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

Should look like this:

<script language="JavaScript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

You have a 'script' word lost in the middle of your script tag. Also you should remove the http:// to let the browser decide whether to use HTTP or HTTPS.

UPDATE

But your main error is that you are including jQuery UI (ONLY) you must include jQuery first! jQuery UI and jQuery are used together, not in separate. jQuery UI depends on jQuery. You should put this line before jQuery UI:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

Is there a way to crack the password on an Excel VBA Project?

It's worth pointing out that if you have an Excel 2007 (xlsm) file, then you can simply save it as an Excel 2003 (xls) file and use the methods outlined in other answers.

How to do scanf for single char in C

Provides a space before %c conversion specifier so that compiler will ignore white spaces. The program may be written as below:

#include <stdio.h>
#include <stdlib.h>
int main()
{
    char ch;
    printf("Enter one char");
    scanf(" %c", &ch); /*Space is given before %c*/
    printf("%c\n",ch);
return 0;
}

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

This is nice but doesn't answer the question:

"A VARCHAR should always be used instead of TINYTEXT." Tinytext is useful if you have wide rows - since the data is stored off the record. There is a performance overhead, but it does have a use.

How can I get the request URL from a Java Filter?

Building on another answer on this page,

public static String getCurrentUrlFromRequest(ServletRequest request)
{
   if (! (request instanceof HttpServletRequest))
       return null;

   return getCurrentUrlFromRequest((HttpServletRequest)request);
}

public static String getCurrentUrlFromRequest(HttpServletRequest request)
{
    StringBuffer requestURL = request.getRequestURL();
    String queryString = request.getQueryString();

    if (queryString == null)
        return requestURL.toString();

    return requestURL.append('?').append(queryString).toString();
}

how to insert date and time in oracle?

You can use

insert into table_name
(date_field)
values
(TO_DATE('2003/05/03 21:02:44', 'yyyy/mm/dd hh24:mi:ss'));

Hope it helps.

Script for rebuilding and reindexing the fragmented index?

Two solutions: One simple and one more advanced.

Introduction

There are two solutions available to you depending on the severity of your issue

Replace with your own values, as follows:

  • Replace XXXMYINDEXXXX with the name of an index.
  • Replace XXXMYTABLEXXX with the name of a table.
  • Replace XXXDATABASENAMEXXX with the name of a database.

Solution 1. Indexing

Rebuild all indexes for a table in offline mode

ALTER INDEX ALL ON XXXMYTABLEXXX REBUILD

Rebuild one specified index for a table in offline mode

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REBUILD

Solution 2. Fragmentation

Fragmentation is an issue in tables that regularly have entries both added and removed.

Check fragmentation percentage

SELECT  
    ips.[index_id] ,
    idx.[name] ,
    ips.[avg_fragmentation_in_percent]
FROM    
    sys.dm_db_index_physical_stats(DB_ID(N'XXXMYDATABASEXXX'), OBJECT_ID(N'XXXMYTABLEXXX'), NULL, NULL, NULL) AS [ips]
    INNER JOIN sys.indexes AS [idx] ON [ips].[object_id] = [idx].[object_id] AND [ips].[index_id] = [idx].[index_id]

Fragmentation 5..30%

If the fragmentation value is greater than 5%, but less than 30% then it is worth reorganising indexes.

Reorganise all indexes for a table

ALTER INDEX ALL ON XXXMYTABLEXXX REORGANIZE

Reorganise one specified index for a table

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REORGANIZE

Fragmentation 30%+

If the fragmentation value is 30% or greater then it is worth rebuilding then indexes in online mode.

Rebuild all indexes in online mode for a table

ALTER INDEX ALL ON XXXMYTABLEXXX REBUILD WITH (ONLINE = ON)

Rebuild one specified index in online mode for a table

ALTER INDEX XXXMYINDEXXXX ON XXXMYTABLEXXX REBUILD WITH (ONLINE = ON)

How to change the icon of .bat file programmatically?

i recommand to use BAT to EXE converter for your desires

..The underlying connection was closed: An unexpected error occurred on a receive

Before Execute query I put the statement as below and it resolved my error. Just FYI in case it will help someone.

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; ctx.ExecuteQuery();

GCC: array type has incomplete element type

The compiler needs to know the size of the second dimension in your two dimensional array. For example:

void print_graph(g_node graph_node[], double weight[][5], int nodes);

Undo git pull, how to bring repos to old state

If there is a failed merge, which is the most common reason for wanting to undo a git pull, running git reset --merge does exactly what one would expect: keep the fetched files, but undo the merge that git pull attempted to merge. Then one can decide what to do without the clutter that git merge sometimes generates. And it does not need one to find the exact commit ID which --hard mentioned in every other answer requires.

Apply pandas function to column to create multiple new columns?

For me this worked:

Input df

df = pd.DataFrame({'col x': [1,2,3]})
   col x
0      1
1      2
2      3

Function

def f(x):
    return pd.Series([x*x, x*x*x])

Create 2 new columns:

df[['square x', 'cube x']] = df['col x'].apply(f)

Output:

   col x  square x  cube x
0      1         1       1
1      2         4       8
2      3         9      27

Get all mysql selected rows into an array

I would suggest the use of MySQLi or MySQL PDO for performance and security purposes, but to answer the question:

while($row = mysql_fetch_assoc($result)){
     $json[] = $row;
}

echo json_encode($json);

If you switched to MySQLi you could do:

$query = "SELECT * FROM table";
$result = mysqli_query($db, $query);

$json = mysqli_fetch_all ($result, MYSQLI_ASSOC);
echo json_encode($json );

Find out time it took for a python script to complete execution

from datetime import datetime
startTime = datetime.now()

#do something

#Python 2: 
print datetime.now() - startTime 

#Python 3: 
print(datetime.now() - startTime)

Multi-dimensional associative arrays in JavaScript

You don't need to necessarily use Objects, you can do it with normal multi-dimensional Arrays.

This is my solution without Objects:

// Javascript
const matrix = [];

matrix.key1 = [
  'value1',
  'value2',
];

matrix.key2 = [
  'value3',
];

which in PHP is equivalent to:

// PHP
$matrix = [
    "key1" => [
        'value1',
        'value2',
    ],
    "key2" => [
        'value3',
    ]
];

Can you do a partial checkout with Subversion?

I wrote a script to automate complex sparse checkouts.

#!/usr/bin/env python

'''
This script makes a sparse checkout of an SVN tree in the current working directory.

Given a list of paths in an SVN repository, it will:
1. Checkout the common root directory
2. Update with depth=empty for intermediate directories
3. Update with depth=infinity for the leaf directories
'''

import os
import getpass
import pysvn

__author__ = "Karl Ostmo"
__date__ = "July 13, 2011"

# =============================================================================

# XXX The os.path.commonprefix() function does not behave as expected!
# See here: http://mail.python.org/pipermail/python-dev/2002-December/030947.html
# and here: http://nedbatchelder.com/blog/201003/whats_the_point_of_ospathcommonprefix.html
# and here (what ever happened?): http://bugs.python.org/issue400788
from itertools import takewhile
def allnamesequal(name):
    return all(n==name[0] for n in name[1:])

def commonprefix(paths, sep='/'):
    bydirectorylevels = zip(*[p.split(sep) for p in paths])
    return sep.join(x[0] for x in takewhile(allnamesequal, bydirectorylevels))

# =============================================================================
def getSvnClient(options):

    password = options.svn_password
    if not password:
        password = getpass.getpass('Enter SVN password for user "%s": ' % options.svn_username)

    client = pysvn.Client()
    client.callback_get_login = lambda realm, username, may_save: (True, options.svn_username, password, True)
    return client

# =============================================================================
def sparse_update_with_feedback(client, new_update_path):
    revision_list = client.update(new_update_path, depth=pysvn.depth.empty)

# =============================================================================
def sparse_checkout(options, client, repo_url, sparse_path, local_checkout_root):

    path_segments = sparse_path.split(os.sep)
    path_segments.reverse()

    # Update the middle path segments
    new_update_path = local_checkout_root
    while len(path_segments) > 1:
        path_segment = path_segments.pop()
        new_update_path = os.path.join(new_update_path, path_segment)
        sparse_update_with_feedback(client, new_update_path)
        if options.verbose:
            print "Added internal node:", path_segment

    # Update the leaf path segment, fully-recursive
    leaf_segment = path_segments.pop()
    new_update_path = os.path.join(new_update_path, leaf_segment)

    if options.verbose:
        print "Will now update with 'recursive':", new_update_path
    update_revision_list = client.update(new_update_path)

    if options.verbose:
        for revision in update_revision_list:
            print "- Finished updating %s to revision: %d" % (new_update_path, revision.number)

# =============================================================================
def group_sparse_checkout(options, client, repo_url, sparse_path_list, local_checkout_root):

    if not sparse_path_list:
        print "Nothing to do!"
        return

    checkout_path = None
    if len(sparse_path_list) > 1:
        checkout_path = commonprefix(sparse_path_list)
    else:
        checkout_path = sparse_path_list[0].split(os.sep)[0]



    root_checkout_url = os.path.join(repo_url, checkout_path).replace("\\", "/")
    revision = client.checkout(root_checkout_url, local_checkout_root, depth=pysvn.depth.empty)

    checkout_path_segments = checkout_path.split(os.sep)
    for sparse_path in sparse_path_list:

        # Remove the leading path segments
        path_segments = sparse_path.split(os.sep)
        start_segment_index = 0
        for i, segment in enumerate(checkout_path_segments):
            if segment == path_segments[i]:
                start_segment_index += 1
            else:
                break

        pruned_path = os.sep.join(path_segments[start_segment_index:])
        sparse_checkout(options, client, repo_url, pruned_path, local_checkout_root)

# =============================================================================
if __name__ == "__main__":

    from optparse import OptionParser
    usage = """%prog  [path2] [more paths...]"""

    default_repo_url = "http://svn.example.com/MyRepository"
    default_checkout_path = "sparse_trunk"

    parser = OptionParser(usage)
    parser.add_option("-r", "--repo_url", type="str", default=default_repo_url, dest="repo_url", help='Repository URL (default: "%s")' % default_repo_url)
    parser.add_option("-l", "--local_path", type="str", default=default_checkout_path, dest="local_path", help='Local checkout path (default: "%s")' % default_checkout_path)

    default_username = getpass.getuser()
    parser.add_option("-u", "--username", type="str", default=default_username, dest="svn_username", help='SVN login username (default: "%s")' % default_username)
    parser.add_option("-p", "--password", type="str", dest="svn_password", help="SVN login password")

    parser.add_option("-v", "--verbose", action="store_true", default=False, dest="verbose", help="Verbose output")
    (options, args) = parser.parse_args()

    client = getSvnClient(options)
    group_sparse_checkout(
        options,
        client,
        options.repo_url,
        map(os.path.relpath, args),
        options.local_path)

How to create a table from select query result in SQL Server 2008

Use following syntax to create new table from old table in SQL server 2008

Select * into new_table  from  old_table 

Why does my Spring Boot App always shutdown immediately after starting?

In my case I fixed this issue like below:-

  1. First I removed (apache) C:\Users\myuserId\.m2\repository\org\apache

  2. I added below dependencies in my pom.xml file

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    
  3. I have changed the default socket by adding below lines in resource file ..\yourprojectfolder\src\main\resourcesand\application.properties(I manually created this file)

     server.port=8099
     [email protected]@
    

    for that I have added below block in my pom.xml under <build> section.

      <build>
      .
      .
     <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
        </resource>
    </resources>
       .
       .    
      </build>
    

My final pom.xml file look like

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.bhaiti</groupId>
    <artifactId>spring-boot-rest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>spring-boot-rest</name>
    <description>Welcome project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>       

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>

    </build>


</project>

Passing a method as a parameter in Ruby

I would recommend to use ampersand to have an access to named blocks within a function. Following the recommendations given in this article you can write something like this (this is a real scrap from my working program):

  # Returns a valid hash for html form select element, combined of all entities
  # for the given +model+, where only id and name attributes are taken as
  # values and keys correspondingly. Provide block returning boolean if you
  # need to select only specific entities.
  #
  # * *Args*    :
  #   - +model+ -> ORM interface for specific entities'
  #   - +&cond+ -> block {|x| boolean}, filtering entities upon iterations
  # * *Returns* :
  #   - hash of {entity.id => entity.name}
  #
  def make_select_list( model, &cond )
    cond ||= proc { true } # cond defaults to proc { true }
    # Entities filtered by cond, followed by filtration by (id, name)
    model.all.map do |x|
      cond.( x ) ? { x.id => x.name } : {}
    end.reduce Hash.new do |memo, e| memo.merge( e ) end
  end

Afterwerds, you can call this function like this:

@contests = make_select_list Contest do |contest|
  logged_admin? or contest.organizer == @current_user
end

If you don't need to filter your selection, you simply omit the block:

@categories = make_select_list( Category ) # selects all categories

So much for the power of Ruby blocks.

How to make sure that a certain Port is not occupied by any other process

It's netstat -ano|findstr port no

Result would show process id in last column

Change Spinner dropdown icon

dummy.xml(remember image size should be less)

<?xml version="1.0" encoding="utf-8"?>
    <selector xmlns:android="http://schemas.android.com/apk/res/android">
        <item>
            <layer-list android:opacity="transparent">
                <item android:width="60dp" android:gravity="left" android:start="20dp">
                    <bitmap  android:src="@drawable/down_button_dummy_dummy" android:gravity="left"/>
                </item>
            </layer-list>
        </item>
    </selector>

layout file snippet be like

<android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:cardUseCompatPadding="true"
        app:cardElevation="5dp"
        >
     <Spinner
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:background="@drawable/dummy">

     </Spinner>
    </android.support.v7.widget.CardView>

click to see result layout image

MySQL query finding values in a comma separated string

Take a look at the FIND_IN_SET function for MySQL.

SELECT * 
    FROM shirts 
    WHERE FIND_IN_SET('1',colors) > 0

Scrolling a div with jQuery

This worked for me:

<html>
<head>
<title>scroll</title>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript"></script>

</head>
<body>

<style>
div.container {
  overflow:hidden;
  width:200px;
  height:200px;
}
div.content {
  position:relative;
  width:200px;
  height:200px;  
  overflow:hidden;
  top:0;
}
</style>

<div class="container">
  <p>
    <a href="javascript:up();"><img src="/images/img_flecha_left.png" class="up" /></a>
    <a href="javascript:down();"><img src="/images/img_flecha_left.png" class="down" /></a>   

  </p>
  <div class="content">
    <p>Hello World</p><p>Hello World</p>
    <p>Hello World</p>
    <p>Hello World</p>
    <p>Hello World</p>
    <p>Hello World</p>
    <p>Hello World</p>
    <p>Hello World</p>
    <p>Hello World</p>
  </div>
</div>

<script>
function up() {
    var topVal = $(".content").css("top"); //alert(topVal);
    var val=parseInt(topVal.replace("px",""));
    val=val-20;
    $(".content").css("top", val+"px");    
}
function down() {
    var topVal = $(".content").css("top"); //alert(topVal);
    var val=parseInt(topVal.replace("px",""));
    val=val+20;
    $(".content").css("top", val+"px");  
}
</script>
</body>
</html>

Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)

If you are using the portable XAMPP installation and Windows 7, and, like me have the version after they removed the XAMPP shell from the control panel none of the suggested answers here will do you much good as the packages will not install.

The problem is with the config file. I found the correct settings after a lot of trial and error.

Simply pull up a command window in the \xampp\php directory and run

pear config-set doc_dir :\xampp\php\docs\PEAR
pear config-set cfg_dir :\xampp\php\cfg
pear config-set data_dir :\xampp\php\data\PEAR
pear config-set test_dir :\xampp\php\tests
pear config-set www_dir :\xampp\php\www

you will want to replace the ':' with the actual drive letter that your portable drive is running on at the moment. Unfortunately, this needs to be done any time this drive letter changes, but it did get the module I needed installed.

Where is debug.keystore in Android Studio

On Windows,

All you need to do is goto command prompt and cd C:\Program Files\Java\jdk-10.0.2\bin>where jdk-10.0.2 or full path can be different in your case. once you are in the bin, enter this code keytool -keystore C:\Users\GB\.android/debug.keystore -list -v where C:\Users\GB\.android/debug.keystore is path to keystore in my case.

You will get results like this.

enter image description here

Error: fix the version conflict (google-services plugin)

as the message says go to: com.google.gms.google-services versions

And copy the last version's number . Mine was less than 3.3.1. Then in project's build.gradle put/change dependencies node as :

dependencies {
    classpath 'com.android.tools.build:gradle:3.1.2' // as it was before             
    classpath 'com.google.gms:google-services:3.3.1' // <-- the version change                  
        }

Then I synced the project and error went

Django - after login, redirect user to his custom page --> mysite.com/username

Got into django recently and been looking into a solution to that and found a method that might be useful.

So for example, if using allouth the default redirect is accounts/profile. Make a view that solely redirects to a location of choice using the username field like so:

def profile(request):
    name=request.user.username
    return redirect('-----choose where-----' + name + '/')

Then create a view that captures it in one of your apps, for example:

def profile(request, name):
    user = get_object_or_404(User, username=name)
    return render(request, 'myproject/user.html', {'profile': user})

Where the urlpatterns capture would look like this:

url(r'^(?P<name>.+)/$', views.profile, name='user')

Works well for me.

How to add a class with React.js?

It is simple. take a look at this

https://codepen.io/anon/pen/mepogj?editors=001

basically you want to deal with states of your component so you check the currently active one. you will need to include

getInitialState: function(){}
//and 
isActive: function(){}

check out the code on the link

How to list processes attached to a shared memory segment in linux?

I wrote a tool called who_attach_shm.pl, it parses /proc/[pid]/maps to get the information. you can download it from github

sample output:

shm attach process list, group by shm key
##################################################################

0x2d5feab4:    /home/curu/mem_dumper /home/curu/playd
0x4e47fc6c:    /home/curu/playd
0x77da6cfe:    /home/curu/mem_dumper /home/curu/playd /home/curu/scand

##################################################################
process shm usage
##################################################################
/home/curu/mem_dumper [2]:    0x2d5feab4 0x77da6cfe
/home/curu/playd [3]:    0x2d5feab4 0x4e47fc6c 0x77da6cfe
/home/curu/scand [1]:    0x77da6cfe

Visual Studio - How to change a project's folder name and solution name without breaking the solution

This is what I did:

  1. Change project and solution name in Visual Studio
  2. Close the project and open the folder containing the project (The Visual studio solution name is already changed).
  3. Change the old project folder names to the new project name
  4. Open the .sln file and the change the project folder names manually from old to new folder names.
  5. Save the .sln file in the text editor
  6. Open the project again with Visual Studio and the solution is ready to modify

Getting Database connection in pure JPA setup

Where you want to get that connection is unclear. One possibility would be to get it from the underlying Hibernate Session used by the EntityManager. With JPA 1.0, you'll have to do something like this:

Session session = (Session)em.getDelegate();
Connection conn = session.connection();

Note that the getDelegate() is not portable, the result of this method is implementation specific: the above code works in JBoss, for GlassFish you'd have to adapt it - have a look at Be careful while using EntityManager.getDelegate().

In JPA 2.0, things are a bit better and you can do the following:

Connection conn = em.unwrap(Session.class).connection();

If you are running inside a container, you could also perform a lookup on the configured DataSource.

How to convert Strings to and from UTF8 byte arrays in Java

As an alternative, StringUtils from Apache Commons can be used.

 byte[] bytes = {(byte) 1};
 String convertedString = StringUtils.newStringUtf8(bytes);

or

 String myString = "example";
 byte[] convertedBytes = StringUtils.getBytesUtf8(myString);

If you have non-standard charset, you can use getBytesUnchecked() or newString() accordingly.

SQL Server: IF EXISTS ; ELSE

I know its been a while since the original post but I like using CTE's and this worked for me:

WITH cte_table_a
AS
(
    SELECT [id] [id]
    , MAX([value]) [value]
    FROM table_a
    GROUP BY [id]
)
UPDATE table_b
SET table_b.code = CASE WHEN cte_table_a.[value] IS NOT NULL THEN cte_table_a.[value] ELSE 124 END
FROM table_b
LEFT OUTER JOIN  cte_table_a
ON table_b.id = cte_table_a.id

How can I open two pages from a single click without using JavaScript?

<a href="http://www.omsaicreche.blogspot.com" onclick="location.href='http://www.omsaivatikanoida.blogspot.com';" target="_blank">Open Two Links With One Click</a>

I tried the above codes. I could not get success in old page. Than I created a new page in blogger and types following codes... I was successful

Angular ng-class if else

Just make a rule for each case:

<div id="homePage" ng-class="{ 'center': page.isSelected(1) , 'left': !page.isSelected(1)  }">

Or use the ternary operator:

<div id="homePage" ng-class="page.isSelected(1) ? 'center' : 'left'">

Where are $_SESSION variables stored?

They're generally stored on the server. Where they're stored is up to you as the developer. You can use the session.save_handler configuration variable and the session_set_save_handler to control how sessions get saved on the server. The default save method is to save sessions to files. Where they get saved is controlled by the session.save_path variable.

member names cannot be the same as their enclosing type C#

Method names which are same as the class name are called constructors. Constructors do not have a return type. So correct as:

private Flow()
{
   X = x;
   Y = y;
}

Or rename the function as:

private void DoFlow()
{
   X = x;
   Y = y;
}

Though the whole code does not make any sense to me.

HTML5 Canvas 100% Width Height of Viewport?

In order to make the canvas full screen width and height always, meaning even when the browser is resized, you need to run your draw loop within a function that resizes the canvas to the window.innerHeight and window.innerWidth.

Example: http://jsfiddle.net/jaredwilli/qFuDr/

HTML

<canvas id="canvas"></canvas>

JavaScript

(function() {
    var canvas = document.getElementById('canvas'),
            context = canvas.getContext('2d');

    // resize the canvas to fill browser window dynamically
    window.addEventListener('resize', resizeCanvas, false);

    function resizeCanvas() {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;

            /**
             * Your drawings need to be inside this function otherwise they will be reset when 
             * you resize the browser window and the canvas goes will be cleared.
             */
            drawStuff(); 
    }
    resizeCanvas();

    function drawStuff() {
            // do your drawing stuff here
    }
})();

CSS

* { margin:0; padding:0; } /* to remove the top and left whitespace */

html, body { width:100%; height:100%; } /* just to be sure these are full screen*/

canvas { display:block; } /* To remove the scrollbars */

That is how you properly make the canvas full width and height of the browser. You just have to put all the code for drawing to the canvas in the drawStuff() function.

JavaScript Promises - reject vs. throw

An example to try out. Just change isVersionThrow to false to use reject instead of throw.

_x000D_
_x000D_
const isVersionThrow = true_x000D_
_x000D_
class TestClass {_x000D_
  async testFunction () {_x000D_
    if (isVersionThrow) {_x000D_
      console.log('Throw version')_x000D_
      throw new Error('Fail!')_x000D_
    } else {_x000D_
      console.log('Reject version')_x000D_
      return new Promise((resolve, reject) => {_x000D_
        reject(new Error('Fail!'))_x000D_
      })_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
const test = async () => {_x000D_
  const test = new TestClass()_x000D_
  try {_x000D_
    var response = await test.testFunction()_x000D_
    return response _x000D_
  } catch (error) {_x000D_
    console.log('ERROR RETURNED')_x000D_
    throw error _x000D_
  }  _x000D_
}_x000D_
_x000D_
test()_x000D_
.then(result => {_x000D_
  console.log('result: ' + result)_x000D_
})_x000D_
.catch(error => {_x000D_
  console.log('error: ' + error)_x000D_
})
_x000D_
_x000D_
_x000D_

How to change max_allowed_packet size

If getting this error while performing a backup, max_allowed_packet can be set in the my.cnf particularly for mysqldump.

[mysqldump]
max_allowed_packet=512M

I kept getting this error while performing a mysqldump and I did not understand because I had this set in my.cnf under the [mysqld] section. Once I figured out I could set it for [mysqldump] and I set the value, my backups completed without issue.

How do I rename a file using VBScript?

From what I understand, your context is to download from ALM. In this case, ALM saves the files under: C:/Users/user/AppData/Local/Temp/TD_80/ALM_VERSION/random_string/Attach/artefact_type/ID

where :

ALM_VERSION is the version of your alm installation, e.g 12.53.2.0_952

artefact_type is the type of the artefact, e.g : REQ

ID is the ID of the artefact

Herebelow a code sample which connects to an instance of ALM, domain 'DEFAUT', project 'MY_PROJECT', gets all the attachments from a REQ with id 6 and saves them in c:/tmp. It's ruby code, but it's easy to transcribe to VBSctript

require 'win32ole'
require 'fileutils'

# login to ALM and domain/project 
alm_server = ENV['CURRRENT_ALM_SERVER']
tdc = WIN32OLE.new('TDApiOle80.TDConnection')
tdc.InitConnectionEx(alm_server)
username, password = ENV['ALM_CREDENTIALS'].split(':')
tdc.Login(username, password)
tdc.Connect('DEFAULT', 'MY_PROJECT')

# get a handle for the Requirements 
reqFact = tdc.ReqFactory

# get Requirement with ID=6
req = reqFact.item(6)

# get a handle for the attachment of REQ 
att = req.Attachments

# get a handle for the list of attachements
attList = att.NewList("")

thePath= 'c:/tmp'

# for each attachment:
attList.each do |el|
  clientPath = nil

  # download the attachment to its default location
  el.Load true, clientPath

  baseName = File.basename(el.FileName)
  dirName = File.dirname(el.FileName)
  puts "file downloaded as : #{baseName}\n in Folder #{dirName}"  
  FileUtils.mkdir_p thePath
  puts "now moving #{baseName} to #{thePath}"  
  FileUtils.mv el.FileName, thePath
end

The output:

=> file downloaded as : REQ_6_20191112_143346.png

=> in Folder C:\Users\user\AppData\Local\Temp\TD_80\12.53.2.0_952\e68ab622\Attach\REQ\6

=> now moving REQ_6_20191112_143346.png to c:/tmp

Giving multiple conditions in for loop in Java

If you prefer a code with a pretty look, you can do a break:

for(int j = 0; ; j++){
    if(j < 6
    && j < ( (int) abc[j] & 0xff)){
        break;
    }

    // Put your code here
}

What is the difference between `Enum.name()` and `Enum.toString()`?

The main difference between name() and toString() is that name() is a final method, so it cannot be overridden. The toString() method returns the same value that name() does by default, but toString() can be overridden by subclasses of Enum.

Therefore, if you need the name of the field itself, use name(). If you need a string representation of the value of the field, use toString().

For instance:

public enum WeekDay {
    MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY;

    public String toString() {
        return name().charAt(0) + name().substring(1).toLowerCase();
    }
}

In this example, WeekDay.MONDAY.name() returns "MONDAY", and WeekDay.MONDAY.toString() returns "Monday".

WeekDay.valueOf(WeekDay.MONDAY.name()) returns WeekDay.MONDAY, but WeekDay.valueOf(WeekDay.MONDAY.toString()) throws an IllegalArgumentException.

open cv error: (-215) scn == 3 || scn == 4 in function cvtColor

Only pass name of the image, no need of 0:

img=cv2.imread('sample.jpg')

CSS selectors ul li a {...} vs ul > li > a {...}

ul > li > a selects only the direct children. In this case only the first level <a> of the first level <li> inside the <ul> will be selected.

ul li a on the other hand will select ALL <a>-s in ALL <li>-s in the unordered list

Example of ul > li

_x000D_
_x000D_
ul > li.bg {_x000D_
  background: red;_x000D_
}
_x000D_
<ul>_x000D_
  <li class="bg">affected</li>_x000D_
  <li class="bg">affected</li>    _x000D_
  <li>_x000D_
    <ol>_x000D_
      <li class="bg">NOT affected</li>_x000D_
      <li class="bg">NOT affected</li>_x000D_
    </ol>_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

if you'd be using ul li - ALL of the li-s would be affected

UPDATE The order of more to less efficient CSS selectors goes thus:

  • ID, e.g.#header
  • Class, e.g. .promo
  • Type, e.g. div
  • Adjacent sibling, e.g. h2 + p
  • Child, e.g. li > ul
  • Descendant, e.g. ul a
  • Universal, i.e. *
  • Attribute, e.g. [type="text"]
  • Pseudo-classes/-elements, e.g. a:hover

So your better bet is to use the children selector instead of just descendant. However the difference on a regular page (without tens of thousands elements to go through) might be absolutely negligible.

How to style an asp.net menu with CSS

I tried MikeTeeVee's solution, still not work, I mean the selected tab still not change and keep different color. This post solved my problem: Set CSS class 'selected' in ASP.NET menu parents and their children? Need put code in code behind.

RGB to hex and hex to RGB

I'm working with XAML data that has a hex format of #AARRGGBB (Alpha, Red, Green, Blue). Using the answers above, here's my solution:

function hexToRgba(hex) {
    var bigint, r, g, b, a;
    //Remove # character
    var re = /^#?/;
    var aRgb = hex.replace(re, '');
    bigint = parseInt(aRgb, 16);

    //If in #FFF format
    if (aRgb.length == 3) {
        r = (bigint >> 4) & 255;
        g = (bigint >> 2) & 255;
        b = bigint & 255;
        return "rgba(" + r + "," + g + "," + b + ",1)";
    }

    //If in #RRGGBB format
    if (aRgb.length >= 6) {
        r = (bigint >> 16) & 255;
        g = (bigint >> 8) & 255;
        b = bigint & 255;
        var rgb = r + "," + g + "," + b;

        //If in #AARRBBGG format
        if (aRgb.length == 8) {
            a = ((bigint >> 24) & 255) / 255;
            return "rgba(" + rgb + "," + a.toFixed(1) + ")";
        }
    }
    return "rgba(" + rgb + ",1)";
}

http://jsfiddle.net/kvLyscs3/

How to remove undefined and null values from an object using lodash?

To remove undefined, null, and empty string from object

_.omitBy(object, (v) => _.isUndefined(v) || _.isNull(v) || v === '');

Unable to copy file - access to the path is denied

Go to file's path then un-check read only checkbox of this file.

How to dump only specific tables from MySQL?

Usage: mysqldump [OPTIONS] database [tables]

i.e.

mysqldump -u username -p db_name table1_name table2_name table3_name > dump.sql

How to add an image in Tkinter?

Following code works on my machine

  1. you probably have something missing in your code.
  2. please also check the code files's encoding.
  3. make sure you have PIL package installed

    import Tkinter as tk
    from PIL import ImageTk, Image
    
    path = 'C:/xxxx/xxxx.jpg'
    
    root = tk.Tk()
    img = ImageTk.PhotoImage(Image.open(path))
    panel = tk.Label(root, image = img)
    panel.pack(side = "bottom", fill = "both", expand = "yes")
    root.mainloop()
    

Detecting installed programs via registry

You can use a PowerShell script to look at registers and get the installed program details. The script bellow will generate a file with the complete list of installed programs. Save it with ".ps" extension and double click the file.

#
# Generates a full list of installed programs.
#

# Temporary auxiliar file.
$tmpFile = "tmp.txt"

# File that will hold the programs list.
$fileName = "programas-instalados.txt"

# Columns separator.
$separator = ","

# Delete previous files.
Remove-Item $tmpFile
Remove-Item $fileName

# Creates the temporary file.
Create-Item $tmpFile

# Searchs register for programs - part 1
$loc = Get-ChildItem HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall
$names = $loc |foreach-object {Get-ItemProperty $_.PsPath}
foreach ($name in $names)
{
    IF(-Not [string]::IsNullOrEmpty($name.DisplayName)) {      
        $line = $name.DisplayName+$separator+$name.DisplayVersion+$separator+$name.InstallDate
        Write-Host $line
        Add-Content $tmpFile "$line`n"        
    }
}

# Searchs register for programs - part 2
$loc = Get-ChildItem HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall
$names = $loc |foreach-object {Get-ItemProperty $_.PsPath}
foreach ($name in $names)
{
    IF(-Not [string]::IsNullOrEmpty($name.DisplayName)) {      
        $line = $name.DisplayName+$separator+$name.DisplayVersion+$separator+$name.InstallDate
        Write-Host $line
        Add-Content $tmpFile "$line`n"
    }
}

# Sorts the result, removes duplicate lines and
# generates the final file.
gc $tmpFile | sort | get-unique > $filename

What to gitignore from the .idea folder?

You can simply ignore all of them by adding .idea/* to the .gitignore file.

break statement in "if else" - java

The issue is that you are trying to have multiple statements in an if without using {}. What you currently have is interpreted like:

if( choice==5 )
{
    System.out.println( ... );
}
break;
else
{
    //...
}

You really want:

if( choice==5 )
{
    System.out.println( ... );
    break;
}
else
{
    //...
}

Also, as Farce has stated, it would be better to use else if for all the conditions instead of if because if choice==1, it will still go through and check if choice==5, which would fail, and it will still go into your else block.

if( choice==1 )
    //...
else if( choice==2 )
    //...
else if( choice==3 )
    //...
else if( choice==4 )
    //...
else if( choice==5 )
{
    //...
}
else
    //...

A more elegant solution would be using a switch statement. However, break only breaks from the most inner "block" unless you use labels. So you want to label your loop and break from that if the case is 5:

LOOP:
for(;;)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch( choice )
    {
        case 1:
            playGame();
            break;
        case 2:
            loadGame();
            break;
        case 2:
            options();
            break;
        case 4:
            credits();
            break;
        case 5:
            System.out.println("End of Game\n Thank you for playing with us!");
            break LOOP;
        default:
            System.out.println( ... );
    }
}

Instead of labeling the loop, you could also use a flag to tell the loop to stop.

bool finished = false;
while( !finished )
{
    switch( choice )
    {
        // ...
        case 5:
            System.out.println( ... )
            finished = true;
            break;
        // ...
    }
}

How do I drop a MongoDB database from the command line?

Like this:

mongo <dbname> --eval "db.dropDatabase()"

More info on scripting the shell from the command line here: https://docs.mongodb.com/manual/tutorial/write-scripts-for-the-mongo-shell/#scripting

How to make a website secured with https

@balalakshmi mentioned about the correct authentication settings. Authentication is only half of the problem, the other half is authorization.

If you're using Forms Authentication and standard controls like <asp:Login> there are a couple of things you'll need to do to ensure that only your authenticated users can access secured pages.

In web.config, under the <system.web> section you'll need to disable anonymous access by default:

<authorization>
 <deny users="?" />
</authorization>

Any pages that will be accessed anonymously (such as the Login.aspx page itself) will need to have an override that re-allows anonymous access. This requires a <location> element and must be located at the <configuration> level (outside the <system.web> section), like this:

<!-- Anonymous files -->
<location path="Login.aspx">
 <system.web>
  <authorization>
   <allow users="*" />
  </authorization>
 </system.web>
</location>

Note that you'll also need to allow anonymous access to any style sheets or scripts that are used by the anonymous pages:

<!-- Anonymous folders -->
<location path="styles">
 <system.web>
  <authorization>
   <allow users="*" />
  </authorization>
 </system.web>
</location>

Be aware that the location's path attribute is relative to the web.config folder and cannot have a ~/ prefix, unlike most other path-type configuration attributes.

sorting a vector of structs

Just make a comparison function/functor:

bool my_cmp(const data& a, const data& b)
{
    // smallest comes first
    return a.word.size() < b.word.size();
}

std::sort(info.begin(), info.end(), my_cmp);

Or provide an bool operator<(const data& a) const in your data class:

struct data {
    string word;
    int number;

    bool operator<(const data& a) const
    {
        return word.size() < a.word.size();
    }
};

or non-member as Fred said:

struct data {
    string word;
    int number;
};

bool operator<(const data& a, const data& b)
{
    return a.word.size() < b.word.size();
}

and just call std::sort():

std::sort(info.begin(), info.end());

pip cannot install anything

pip has mirror support

pip --use-mirrors install yolk

As of version 1.5, this option will be removed:

1.5 (unreleased)

BACKWARD INCOMPATIBLE pip no longer supports the --use-mirrors, -M, and --mirrors flags. The mirroring support has been removed. In order to use a mirror specify it as the primary index with -i or --index-url, or as an additional index with --extra-index-url. (Pull #1098, CVE-2013-5123)

BACKWARD INCOMPATIBLE pip no longer will scrape insecure external urls by default nor will it install externally hosted files by default. Users may opt into installing externally hosted or insecure files or urls using --allow-external PROJECT and --allow-insecure PROJECT. (Pull #1055)

Added colors to the logging output in order to draw attention to important warnings and errors. (Pull #1109)

Added warnings when using an insecure index, find-link, or dependency link. (Pull #1121)

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

file_get_contents(php://input) - gets the raw POST data and you need to use this when you write APIs and need XML/JSON/... input that cannot be decoded to $_POST by PHP some example :

send by post JSON string

<input type="button" value= "click" onclick="fn()">
<script>
 function fn(){


    var js_obj = {plugin: 'jquery-json', version: 2.3};

    var encoded = JSON.stringify( js_obj );

var data= encoded


    $.ajax({
  type: "POST",
  url: '1.php',
  data: data,
  success: function(data){
    console.log(data);
  }

});

    }
</script>

1.php

//print_r($_POST); //empty!!! don't work ... 
var_dump( file_get_contents('php://input'));

How to Reload ReCaptcha using JavaScript?

For AngularJS users:

$window.grecaptcha.reset();

How can I save application settings in a Windows Forms application?

The registry/configurationSettings/XML argument still seems very active. I've used them all, as the technology has progressed, but my favourite is based on Threed's system combined with Isolated Storage.

The following sample allows storage of an objects named properties to a file in isolated storage. Such as:

AppSettings.Save(myobject, "Prop1,Prop2", "myFile.jsn");

Properties may be recovered using:

AppSettings.Load(myobject, "myFile.jsn");

It is just a sample, not suggestive of best practices.

internal static class AppSettings
{
    internal static void Save(object src, string targ, string fileName)
    {
        Dictionary<string, object> items = new Dictionary<string, object>();
        Type type = src.GetType();

        string[] paramList = targ.Split(new char[] { ',' });
        foreach (string paramName in paramList)
            items.Add(paramName, type.GetProperty(paramName.Trim()).GetValue(src, null));

        try
        {
            // GetUserStoreForApplication doesn't work - can't identify.
            // application unless published by ClickOnce or Silverlight
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForAssembly();
            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
            using (StreamWriter writer = new StreamWriter(stream))
            {
                writer.Write((new JavaScriptSerializer()).Serialize(items));
            }

        }
        catch (Exception) { }   // If fails - just don't use preferences
    }

    internal static void Load(object tar, string fileName)
    {
        Dictionary<string, object> items = new Dictionary<string, object>();
        Type type = tar.GetType();

        try
        {
            // GetUserStoreForApplication doesn't work - can't identify
            // application unless published by ClickOnce or Silverlight
            IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForAssembly();
            using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(fileName, FileMode.Open, storage))
            using (StreamReader reader = new StreamReader(stream))
            {
                items = (new JavaScriptSerializer()).Deserialize<Dictionary<string, object>>(reader.ReadToEnd());
            }
        }
        catch (Exception) { return; }   // If fails - just don't use preferences.

        foreach (KeyValuePair<string, object> obj in items)
        {
            try
            {
                tar.GetType().GetProperty(obj.Key).SetValue(tar, obj.Value, null);
            }
            catch (Exception) { }
        }
    }
}

Styling the arrow on bootstrap tooltips

This one worked for me!

.tooltip .tooltip-arrow {
border-top: 5px solid red !important;}

Vlookup referring to table data in a different sheet

One of the common problems with VLOOKUP is "data mismatch" where #N/A is returned because a numeric lookup value doesn't match a text-formatted value in the VLOOKUP table (or vice versa)

Does either of these versions work?

=VLOOKUP(M3&"",Sheet1!$A$2:$Q$47,13,FALSE)

or

=VLOOKUP(M3+0,Sheet1!$A$2:$Q$47,13,FALSE)

The former converts a numeric lookup value to text (assuming that lookup table 1st column contains numbers formatted as text). The latter does the reverse, changing a text-formatted lookup value to a number.

Depending on which one works (assuming one does) then you may want to permanently change the format of your data so that the standard VLOOKUP will work

"And" and "Or" troubles within an IF statement

This is not an answer, but too long for a comment.

In reply to JP's answers / comments, I have run the following test to compare the performance of the 2 methods. The Profiler object is a custom class - but in summary, it uses a kernel32 function which is fairly accurate (Private Declare Sub GetLocalTime Lib "kernel32" (lpSystemTime As SYSTEMTIME)).

Sub test()

  Dim origNum As String
  Dim creditOrDebit As String
  Dim b As Boolean
  Dim p As Profiler
  Dim i As Long

  Set p = New_Profiler

  origNum = "30062600006"
  creditOrDebit = "D"

  p.startTimer ("nested_ifs")

  For i = 1 To 1000000

    If creditOrDebit = "D" Then
      If origNum = "006260006" Then
        b = True
      ElseIf origNum = "30062600006" Then
        b = True
      End If
    End If

  Next i

  p.stopTimer ("nested_ifs")
  p.startTimer ("or_and")

  For i = 1 To 1000000

    If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
      b = True
    End If

  Next i

  p.stopTimer ("or_and")

  p.printReport

End Sub

The results of 5 runs (in ms for 1m loops):

20-Jun-2012 19:28:25
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125

20-Jun-2012 19:28:26
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125

20-Jun-2012 19:28:27
nested_ifs (x1): 140 - Last Run: 140 - Average Run: 140
or_and (x1): 125 - Last Run: 125 - Average Run: 125

20-Jun-2012 19:28:28
nested_ifs (x1): 140 - Last Run: 140 - Average Run: 140
or_and (x1): 141 - Last Run: 141 - Average Run: 141

20-Jun-2012 19:28:29
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125

Note

If creditOrDebit is not "D", JP's code runs faster (around 60ms vs. 125ms for the or/and code).

Refresh certain row of UITableView based on Int in Swift

SWIFT 4.2

    func reloadYourRows(name: <anyname>) {
    let row = <your array name>.index(of: <name passing in>)
    let reloadPath = IndexPath(row: row!, section: 0)
    tableView.reloadRows(at: [reloadPath], with: .middle)
    }

Linux command for extracting war file?

A war file is just a zip file with a specific directory structure. So you can use unzip or the jar tool for unzipping.

But you probably don't want to do that. If you add the war file into the webapps directory of Tomcat the Tomcat will take care of extracting/installing the war file.

nginx - nginx: [emerg] bind() to [::]:80 failed (98: Address already in use)

I know this is old, but also make sure that none of your docker containers are already on port 80. That was my issue.

Volatile Vs Atomic

The volatile keyword is used:

  • to make non atomic 64-bit operations atomic: long and double. (all other, primitive accesses are already guaranteed to be atomic!)
  • to make variable updates guaranteed to be seen by other threads + visibility effects: after writing to a volatile variable, all the variables that where visible before writing that variable become visible to another thread after reading the same volatile variable (happen-before ordering).

The java.util.concurrent.atomic.* classes are, according to the java docs:

A small toolkit of classes that support lock-free thread-safe programming on single variables. In essence, the classes in this package extend the notion of volatile values, fields, and array elements to those that also provide an atomic conditional update operation of the form:

boolean compareAndSet(expectedValue, updateValue);

The atomic classes are built around the atomic compareAndSet(...) function that maps to an atomic CPU instruction. The atomic classes introduce the happen-before ordering as the volatile variables do. (with one exception: weakCompareAndSet(...)).

From the java docs:

When a thread sees an update to an atomic variable caused by a weakCompareAndSet, it does not necessarily see updates to any other variables that occurred before the weakCompareAndSet.

To your question:

Does this mean that whosoever takes lock on it, that will be setting its value first. And in if meantime, some other thread comes up and read old value while first thread was changing its value, then doesn't new thread will read its old value?

You don't lock anything, what you are describing is a typical race condition that will happen eventually if threads access shared data without proper synchronization. As already mentioned declaring a variable volatile in this case will only ensure that other threads will see the change of the variable (the value will not be cached in a register of some cache that is only seen by one thread).

What is the difference between AtomicInteger and volatile int?

AtomicInteger provides atomic operations on an int with proper synchronization (eg. incrementAndGet(), getAndAdd(...), ...), volatile int will just ensure the visibility of the int to other threads.

Exiting out of a FOR loop in a batch file?

As jeb noted, the rest of the loop is skipped but evaluated, which makes the FOR solution too slow for this purpose. An alternative:

set F=1
:nextpart
if not exist "%F%" goto :EOF
echo %F%
set /a F=%F%+1
goto nextpart

You might need to use delayed expansion and call subroutines when using this in loops.

How do I Search/Find and Replace in a standard string?

#include <boost/algorithm/string.hpp> // include Boost, a C++ library
...
std::string target("Would you like a foo of chocolate. Two foos of chocolate?");
boost::replace_all(target, "foo", "bar");

Here is the official documentation on replace_all.

What is external linkage and internal linkage?

As dudewat said external linkage means the symbol (function or global variable) is accessible throughout your program and internal linkage means that it is only accessible in one translation unit.

You can explicitly control the linkage of a symbol by using the extern and static keywords. If the linkage is not specified then the default linkage is extern (external linkage) for non-const symbols and static (internal linkage) for const symbols.

// In namespace scope or global scope.
int i; // extern by default
const int ci; // static by default
extern const int eci; // explicitly extern
static int si; // explicitly static

// The same goes for functions (but there are no const functions).
int f(); // extern by default
static int sf(); // explicitly static 

Note that instead of using static (internal linkage), it is better to use anonymous namespaces into which you can also put classes. Though they allow extern linkage, anonymous namespaces are unreachable from other translation units, making linkage effectively static.

namespace {
  int i; // extern by default but unreachable from other translation units
  class C; // extern by default but unreachable from other translation units
}

How do I see which version of Swift I'm using?

To see the default version of swift installed on your machine then from the command line, type the following :

swift --version

Apple Swift version 4.1.2 (swiftlang-902.0.54 clang-902.0.39.2)

Target: x86_64-apple-darwin17.6.0

This is most likely the version that is included in the app store version of Xcode that you have installed (unless you have changed it).

If you want to determine the actual version of Swift being used by a particular version of Xcode (a beta, for instance) then from the command line, invoke the swift binary within the Xcode bundle and pass it the parameter --version

/Applications/Xcode-beta.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift --version

Apple Swift version 4.2 (swiftlang-1000.0.16.7 clang-1000.10.25.3)

Target: x86_64-apple-darwin17.6.0

How to make grep only match if the entire line matches?

Simply specify the regexp anchors.

grep '^ABB\.log$' a.tmp

How can I get the username of the logged-in user in Django?

For template, you can use

{% firstof request.user.get_full_name request.user.username %}

firstof will return the first one if not null else the second one

Using event.target with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(e.target, space, txt);
}

Example


event.target gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

<button 
  data-space="home" 
  className="home" 
  data-txt="Home" 
  onClick={ this.props.onClick } 
/> 
  Button
</button>

onClick(e) {
   console.log(e.target.dataset.txt, e.target.dataset.space);
}

Example

Phone: numeric keyboard for text input

I couldn't find a type that worked best for me in all situations: I needed to default to numeric entry (entry of "7.5" for example) but also at certain times allow text ("pass" for example). Users wanted a numeric keypad (entry of 7.5 for example) but occasional text entry was required ("pass" for example).

Rather what I did was to add a checkbox to the form and allow the user to toggle my input (id="inputSresult") between type="number" and type="text".

<input type="number" id="result"... >
<label><input id="cbAllowTextResults" type="checkbox" ...>Allow entry of text results.</label>

Then I wired a click handler to the checkbox that toggles the type between text and number based on whether the checkbox above is checked:

$(document).ready(function () {
    var cb = document.getElementById('cbAllowTextResults');
    cb.onclick = function (event) {
        if ($("#cbAllowTextResults").is(":checked"))
            $("#result").attr("type", "text");
        else
            $("#result").attr("type", "number");

    }
});

This worked out well for us.

Microsoft Excel mangles Diacritics in .csv files?

Note that including the UTF-8 BOM is not necessarily a good idea - Mac versions of Excel ignore it and will actually display the BOM as ASCII… three nasty characters at the start of the first field in your spreadsheet…

Getting JavaScript object key list

_x000D_
_x000D_
var obj = {_x000D_
   key1: 'value1',_x000D_
   key2: 'value2',_x000D_
   key3: 'value3',_x000D_
   key4: 'value4'_x000D_
}_x000D_
var keys = Object.keys(obj);_x000D_
console.log('obj contains ' + keys.length + ' keys: '+  keys);
_x000D_
_x000D_
_x000D_

It's supported on most major browsers now.

Installing OpenCV on Windows 7 for Python 2.7

One thing that needs to be mentioned. You have to use the x86 version of Python 2.7. OpenCV doesn't support Python x64. I banged my head on this for a bit until I figured that out.

That said, follow the steps in Abid Rahman K's answer. And as Antimony said, you'll need to do a 'from cv2 import cv'

Extract substring in Bash

just try to use cut -c startIndx-stopIndx

Change default global installation directory for node.js modules in Windows?

Using a Windows symbolic link from the C:\Users{username}\AppData\Roaming\npm and C:\Users{username}\AppData\Roaming\npm-cache paths to the destination worked great for me.

How to add a symbolic link

enter image description here

Vertical dividers on horizontal UL menu

A simpler solution would be to just add #navigation ul li~li { border-left: 1px solid #857D7A; }

How do you do relative time in Rails?

Sounds like you're looking for the time_ago_in_words method (or distance_of_time_in_words), from ActiveSupport. Call it like this:

<%= time_ago_in_words(timestamp) %>

Team Build Error: The Path ... is already mapped to workspace

I had this issue with this with Azure DevOps automated builds in an on-prem TFS build agent. Removing the workspace using TFS Sidekicks did not work. And tf.exe could not even find the workspace to delete it.

This solution should work for TFS 2017, TFS 2018, Azure DevOps, and possibly other versions:

  1. Take note of the workspace GUID in the error message.
  2. On the machine where the build is taking place, navigate to: %USERPROFILE%\AppData\Local\Microsoft\Team Foundation\ (where %USERPROFILE% belongs to the user that triggered the build).
  3. Search for and remove all instances of the workspace GUID under that directory. There will likely be a folder in a 'cache' directory, as well as entries in 'LocationServerMap.xml' and 'LocalItemExclusions.config'. Remove them all.

That worked in my circumstance.

Razor Views not seeing System.Web.Mvc.HtmlHelper

Right, I've been trying to fix this issue for sometime. I've used all the solutions in the various Stack Overflow topics regarding this and none seemed to be working.

I have just fixed the issue this morning. After you gave fixed the web.config for both the project and the views, making sure all the .dll versions are matching with what you have in the references folder. You will need to unload the project, edit the .csproj, and then update all the .dll versions in that file.

System.Web.Helpers
System.Web.Mvc
System.Web.WebPages

Hope this helps, as I have finally fixed this issue! No more red squiggly lines.

This has also fixed the context menu issue I was having where, I wasn't getting the option to add a controller, view etc.

How to check for valid email address?

Email addresses are not as simple as they seem! For example, Bob_O'[email protected], is a valid email address.

I've had some luck with the lepl package (http://www.acooke.org/lepl/). It can validate email addresses as indicated in RFC 3696: http://www.faqs.org/rfcs/rfc3696.html

Found some old code:

import lepl.apps.rfc3696
email_validator = lepl.apps.rfc3696.Email()
if not email_validator("[email protected]"):
    print "Invalid email"

Select rows having 2 columns equal value

select t.* from table t
    join (
        select C2, C3, C4
        from table
        group by C2, C3, C4
        having count(*) > 1
    ) t2
    using (C2, C3, C4);

What's the equivalent of Java's Thread.sleep() in JavaScript?

This eventually helped me:

    var x = 0;
    var buttonText = 'LOADING';

    $('#startbutton').click(function(){
        $(this).text(buttonText);
        window.setTimeout(addDotToButton,2000);
    })

    function addDotToButton(){
        x++;
        buttonText += '.';
        $('#startbutton').text(buttonText);

        if (x < 4) window.setTimeout(addDotToButton, 2000);
        else location.reload(true);
    }

What is SELF JOIN and when would you use it?

SQL self-join simply is a normal join which is used to join a table to itself.

Example:

Select *
FROM Table t1, Table t2
WHERE t1.Id = t2.ID

What are the differences between the urllib, urllib2, urllib3 and requests module?

A key point that I find missing in the above answers is that urllib returns an object of type <class http.client.HTTPResponse> whereas requests returns <class 'requests.models.Response'>.

Due to this, read() method can be used with urllib but not with requests.

P.S. : requests is already rich with so many methods that it hardly needs one more as read() ;>

Search code inside a Github project

Go here: https://github.com/search and enter "pattern repo:user_name/repo_name".

For example, to search for cnn_learner in the fastai repo of user fastai, enter this:

cnn_learner repo:fastai/fastai

That's it. The only annoyance is you'll need an extra click. It will tell you:

We couldn’t find any repositories matching 'cnn_learner repo:fastai/fastai'

because by default it searches for repositories matching that search string...

So just click on the left on "Code" and it will display what you want.

Or get the code search results directly with a URL like this:

https://github.com/search?q=cnn_learner+repo%3Afastai%2Ffastai&type=code

Strings in C, how to get subString

#include <string.h>
...
char otherString[6]; // note 6, not 5, there's one there for the null terminator
...
strncpy(otherString, someString, 5);
otherString[5] = '\0'; // place the null terminator

Start a fragment via Intent within a Fragment

You cannot open new fragments. Fragments need to be always hosted by an activity. If the fragment is in the same activity (eg tabs) then the back key navigation is going to be tricky I am assuming that you want to open a new screen with that fragment.

So you would simply create a new activity and put the new fragment in there. That activity would then react to the intent either explicitly via the activity class or implicitly via intent filters.

How to disable scrolling in UITableView table when the content fits on the screen

You can set enable/disable bounce or scrolling the tableview by selecting/deselecting these in the Scroll View area

Scroll View editing area

Navigate to another page with a button in angular 2

you can change

    this.router.routeReuseStrategy.shouldReuseRoute = () => false;

at the component level in constructor like bellow

    constructor(private router: Router) {
            this.router.routeReuseStrategy.shouldReuseRoute = () => false; 
}

Replace all non Alpha Numeric characters, New Lines, and multiple White Space with one Space

A saw a different post that also had diacritical marks, which is great

s.replace(/[^a-zA-Z0-9À-ž\s]/g, "")

How to close the current fragment by using Button like the back button?

if you need in 2020

    Objects.requireNonNull(getActivity()).onBackPressed();

Can I change the headers of the HTTP request sent by the browser?

I don't think it's possible to do it in the way you are trying to do it.

Indication of the accepted data format is usually done through adding the extension to the resource name. So, if you have resource like

/resources/resource

and GET /resources/resource returns its HTML representation, to indicate that you want its XML representation instead, you can use following pattern:

/resources/resource.xml

You have to do the accepted content type determination magic on the server side, then.

Or use Javascript as James suggests.

Get values from an object in JavaScript

To access the properties of an object without knowing the names of those properties you can use a for ... in loop:

for(key in data) {
    if(data.hasOwnProperty(key)) {
        var value = data[key];
        //do something with value;
    }
}

Responsive background image in div full width

I also tried this style for ionic hybrid app background. this is also having style for background blur effect.

.bg-image {
   position: absolute;
   background: url(../img/bglogin.jpg) no-repeat;
   height: 100%;
   width: 100%;
   background-size: cover;
   bottom: 0px;
   margin: 0 auto;
   background-position: 50%;


  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);

}

Python unicode equal comparison failed

You may use the == operator to compare unicode objects for equality.

>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>> 
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>> 

But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode object to a str object, like so:

>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.

Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.

I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."

Create patch or diff file from git repository and apply it to another different git repository

you can apply two commands

  1. git diff --patch > mypatch.patch // to generate the patch
  2. git apply mypatch.patch // to apply the patch

Finding all possible permutations of a given string in python

itertools.permutations is good, but it doesn't deal nicely with sequences that contain repeated elements. That's because internally it permutes the sequence indices and is oblivious to the sequence item values.

Sure, it's possible to filter the output of itertools.permutations through a set to eliminate the duplicates, but it still wastes time generating those duplicates, and if there are several repeated elements in the base sequence there will be lots of duplicates. Also, using a collection to hold the results wastes RAM, negating the benefit of using an iterator in the first place.

Fortunately, there are more efficient approaches. The code below uses the algorithm of the 14th century Indian mathematician Narayana Pandita, which can be found in the Wikipedia article on Permutation. This ancient algorithm is still one of the fastest known ways to generate permutations in order, and it is quite robust, in that it properly handles permutations that contain repeated elements.

def lexico_permute_string(s):
    ''' Generate all permutations in lexicographic order of string `s`

        This algorithm, due to Narayana Pandita, is from
        https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order

        To produce the next permutation in lexicographic order of sequence `a`

        1. Find the largest index j such that a[j] < a[j + 1]. If no such index exists, 
        the permutation is the last permutation.
        2. Find the largest index k greater than j such that a[j] < a[k].
        3. Swap the value of a[j] with that of a[k].
        4. Reverse the sequence from a[j + 1] up to and including the final element a[n].
    '''

    a = sorted(s)
    n = len(a) - 1
    while True:
        yield ''.join(a)

        #1. Find the largest index j such that a[j] < a[j + 1]
        for j in range(n-1, -1, -1):
            if a[j] < a[j + 1]:
                break
        else:
            return

        #2. Find the largest index k greater than j such that a[j] < a[k]
        v = a[j]
        for k in range(n, j, -1):
            if v < a[k]:
                break

        #3. Swap the value of a[j] with that of a[k].
        a[j], a[k] = a[k], a[j]

        #4. Reverse the tail of the sequence
        a[j+1:] = a[j+1:][::-1]

for s in lexico_permute_string('data'):
    print(s)

output

aadt
aatd
adat
adta
atad
atda
daat
data
dtaa
taad
tada
tdaa

Of course, if you want to collect the yielded strings into a list you can do

list(lexico_permute_string('data'))

or in recent Python versions:

[*lexico_permute_string('data')]

Create a Path from String in Java7

You can just use the Paths class:

Path path = Paths.get(textPath);

... assuming you want to use the default file system, of course.

Android Studio Gradle Already disposed Module

I also face this problem sometimes. Click on gradle console in bottom bar of android studio, at right side. It will show the exact error in logs. My problem was that I had compile SDK 22 and imported appcomact library was of sdk 23.

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

How to locate the php.ini file (xampp)

in my case it is present as "php.ini-development" and "php.ini-production" in php folder

Can't access 127.0.0.1

If it's a DNS problem, you could try:

  • ipconfig /flushdns
  • ipconfig /registerdns

If this doesn't fix it, you could try editing the hosts file located here:

C:\Windows\System32\drivers\etc\hosts

And ensure that this line (and no other line referencing localhost) is in there:

127.0.0.1 localhost

How to run a JAR file

java -classpath Predit.jar your.package.name.MainClass

Public class is inaccessible due to its protection level

This error is a result of the protection level of ClassB's constructor, not ClassB itself. Since the name of the constructor is the same as the name of the class* , the error may be interpreted incorrectly. Since you did not specify the protection level of your constructor, it is assumed to be internal by default. Declaring the constructor public will fix this problem:

public ClassB() { } 

* One could also say that constructors have no name, only a type; this does not change the essence of the problem.

How to source virtualenv activate in a Bash script

Although it doesn't add the "(.env)" prefix to the shell prompt, I found this script works as expected.

#!/bin/bash
script_dir=`dirname $0`
cd $script_dir
/bin/bash -c ". ../.env/bin/activate; exec /bin/bash -i"

e.g.

user@localhost:~/src$ which pip
/usr/local/bin/pip
user@localhost:~/src$ which python
/usr/bin/python
user@localhost:~/src$ ./shell
user@localhost:~/src$ which pip
~/.env/bin/pip
user@localhost:~/src$ which python
~/.env/bin/python
user@localhost:~/src$ exit
exit

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I know it's quite old questions and many persons has answered. but I am summarizing the things for understanding:

If the file extension is xls and OS is 32 bit then only you can use "Microsoft.Jet.OLEDB.4.0". Microsoft has not released 64 bit version of this driver.

If file extension is xlsx or OS is 64 bit then you must have to use "Microsoft.ACE.OLEDB.12.0". The application compiled in 32/64 bit mode does not impact the selection of driver.

Always install the 64 bit driver of Microsoft.ACE.OLEDB.12.0 on OS 64 bit. If you have already installed Office 32 bit then you need to run driver from cmd with /passive argument. This hack works till Office 2013 only, Microsoft stopped this workaround from Office 2016 for Microsoft.ACE.OLEDB.16.0 drivers.

AccessDatabaseEngine_x64.exe /passive

Download drivers Microsoft.ACE.OLEDB.12.0

private void ProcessFile(string path)
{
    string connString = string.Empty;

    if (Path.GetExtension(path).ToLower().Trim() == ".xls" && Environment.Is64BitOperatingSystem == false)
        connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + path + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
    else
        connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
}

If Application is compiled with AnyCPU flag, it will look for 64 bit Access drivers on 64 bit OS and 32 bit access drivers on 32 bit OS.

ASP.NET Web Site or ASP.NET Web Application?

It depends on what you are developing.

A content-oriented website will have its content changing frequently and a Website is better for that.

An application tends to have its data stored in a database and its pages and code change rarely. In this case it's better to have a Web application where deployment of assemblies is much more controlled and has better support for unit testing.

CentOS: Copy directory to another directory

cp -r /home/server/folder/test /home/server/

Confusing "duplicate identifier" Typescript error message

Update: Version 1.0 of Typings changed the output structure and the below answer relates to pre 1.0 version.

If you are using Typings and exclude in your tsconfig.json, you may run into the issue of duplicate types and need something like the following:

{
  "exclude": [
    "typings/browser.d.ts",
    "typings/browser",
    "node_modules"
  ]
}

To simplify integration with TypeScript, two files - typings/main.d.ts and typings/browser.d.ts - are generated which reference all the typings installed in the project only one of which can be used at a time.

So depending on which version you need, you should exclude (or include) the "browser" or the "main" type files, but not both, as this is where the duplicates come from.

This Typings issue discusses it more.

Angular ui-grid dynamically calculate height of the grid

UPDATE:

The HTML was requested so I've pasted it below.

<div ui-grid="gridOptions" class="my-grid"></div>

ORIGINAL:

We were able to adequately solve this problem by using responsive CSS (@media) that sets the height and width based on screen real estate. Something like (and clearly you can add more based on your needs):

@media (min-width: 1024px) {
  .my-grid {
    width: 772px;
  }
}

@media (min-width: 1280px) {
  .my-grid {
    width: 972px;
  }
}

@media (min-height: 768px) {
  .my-grid {
    height: 480px;
  }
}

@media (min-height: 900px) {
  .my-grid {
    height: 615px;
  }
}

The best part about this solution is that we need no resize event handling to monitor for grid size changes. It just works.

Add spaces between the characters of a string in Java?

If you use a stringbuilder, it would be efficient to initalize the length when you create the object. Length is going to be 2*lengthofString-1.

Or creating a char array and converting it back to the string would yield the same result.

Aand when you write some code please be sure that you write a few test cases as well, it will make your solution complete.

Querying data by joining two tables in two database on different servers

for this simply follow below query

select a.Id,a.type,b.Name,b.City from DatabaseName.dbo.TableName a left join DatabaseName.dbo.TableName b on a.Id=b.Id

Where I wrote databasename, you have to define the name of the database. If you are in same database so you don't need to define the database name but if you are in other database you have to mention database name as path or it will show you error. Hope I made your work easy

REST API 404: Bad URI, or Missing Resource?

So in essence, it sounds like the answer could depend on how the request is formed.

If the requested resource forms part of the URI as per a request to http://mywebsite/restapi/user/13 and user 13 does not exist, then a 404 is probably appropriate and intuitive because the URI is representative of a non-existent user/entity/document/etc. The same would hold for the more secure technique using a GUID http://mywebsite/api/user/3dd5b770-79ea-11e1-b0c4-0800200c9a66 and the api/restapi argument above.

However, if the requested resource ID was included in the request header [include your own example], or indeed, in the URI as a parameter, eg http://mywebsite/restapi/user/?UID=13 then the URI would still be correct (because the concept of a USER does exits at http://mywebsite/restapi/user/); and therefore the response could reasonable be expected to be a 200 (with an appropriately verbose message) because the specific user known as 13 does not exist but the URI does. This way we are saying the URI is good, but the request for data has no content.

Personally a 200 still doesn't feel right (though I have previously argued it does). A 200 response code (without a verbose response) could cause an issue not to be investigated when an incorrect ID is sent for example.

A better approach would be to send a 204 - No Contentresponse. This is compliant with w3c's description *The server has fulfilled the request but does not need to return an entity-body, and might want to return updated metainformation.*1 The confusion, in my opinion is caused by the Wikipedia entry stating 204 No Content - The server successfully processed the request, but is not returning any content. Usually used as a response to a successful delete request. The last sentence is highly debateable. Consider the situation without that sentence and the solution is easy - just send a 204 if the entity does not exist. There is even an argument for returning a 204 instead of a 404, the request has been processed and no content has been returned! Please be aware though, 204's do not allow content in the response body

Sources

http://en.wikipedia.org/wiki/List_of_HTTP_status_codes 1. http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

Add Foreign Key to existing table

check this link. It has helped me with errno 150: http://verysimple.com/2006/10/22/mysql-error-number-1005-cant-create-table-mydbsql-328_45frm-errno-150/

On the top of my head two things come to mind.

  • Is your foreign key index a unique name in the whole database (#3 in the list)?
  • Are you trying to set the table PK to NULL on update (#5 in the list)?

I'm guessing the problem is with the set NULL on update (if my brains aren't on backwards today as they so often are...).

Edit: I missed the comments on your original post. Unsigned/not unsigned int columns maybe resolved your case. Hope my link helps someone in the future thought.

Visual Studio 2017 - Git failed with a fatal error

AngelBlueSky's answer worked partially for me. I had to execute these additional lines to clean the Git global configuration after step 4:

git config --global credential.helper wincred
git config http.sslcainfo "C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt"
git config --global --unset core.askpass
git config --global --unset mergetool.vsdiffmerge.keepbackup
git config --global --unset mergetool.vsdiffmerge.trustexitcode
git config --global --unset mergetool.vsdiffmerge.cmd
git config --global --unset mergetool.prompt
git config --global --unset merge.tool
git config --global --unset difftool.vsdiffmerge.keepbackup
git config --global --unset difftool.vsdiffmerge.cmd
git config --global --unset difftool.prompt
git config --global --unset diff.tool

Then git config -l (executed from any git repo) should return only this:

core.symlinks=false
core.autocrlf=false
core.fscache=true
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
help.format=html
diff.astextplain.textconv=astextplain
rebase.autosquash=true
user.name=xxxxxxxxxxxx
[email protected]
credential.helper=wincred
core.bare=false
core.filemode=false
core.symlinks=false
core.ignorecase=true
core.logallrefupdates=true
core.repositoryformatversion=0
remote.origin.url=https://[email protected]/xxx/xxx.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
branch.master.remote=origin
branch.master.merge=refs/heads/master
branch.identityserver.remote=origin
branch.identityserver.merge=refs/heads/identityserver
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt

Run the git status and git fetch commands to validate that it works from the command line.

Then go to Visual Studio, where your repositories should be back, and all sync/push/pull should work without issues.

Margin while printing html page

You should use cm or mm as unit when you specify for printing. Using pixels will cause the browser to translate it to something similar to what it looks like on screen. Using cm or mm will ensure consistent size on the paper.

body
{
  margin: 25mm 25mm 25mm 25mm;
}

For font sizes, use pt for the print media.

Note that setting the margin on the body in css style will not adjust the margin in the printer driver that defines the printable area of the printer, or margin controlled by the browser (may be adjustable in print preview on some browsers)... It will just set margin on the document inside the printable area.

You should also be aware that IE7++ automatically adjusts the size to best fit, and causes everything to be wrong even if you use cm or mm. To override this behaviour, the user must select 'Print preview' and then set the print size to 100% (default is Shrink To Fit).

A better option for full control on printed margins is to use the @page directive to set the paper margin, which will affect the margin on paper outside the html body element, which is normally controlled by the browser. See http://www.w3.org/TR/1998/REC-CSS2-19980512/page.html.
This currently works in all major browsers except Safari.
In Internet explorer, the margin is actually set to this value in the settings for this printing, and if you do Preview you will get this as default, but the user can change it in the preview.

@page  
{ 
    size: auto;   /* auto is the initial value */ 

    /* this affects the margin in the printer settings */ 
    margin: 25mm 25mm 25mm 25mm;  
} 

body  
{ 
    /* this affects the margin on the content before sending to printer */ 
    margin: 0px;  
} 

Related answer: Disabling browser print options (headers, footers, margins) from page?

when exactly are we supposed to use "public static final String"?

The keyword final means that the value is constant(it cannot be changed). It is analogous to const in C.

And you can treat static as a global variable which has scope. It basically means if you change it for one object it will be changed for all just like a global variable(limited by scope).

Hope it helps.

Java check if boolean is null

boolean is a primitive type, and therefore can not be null.

Its boxed type, Boolean, can be null.

The function is probably returning a Boolean as opposed to a boolean, so assigning the result to a Boolean-type variable will allow you to test for nullity.

Regular Expression usage with ls

You don't say what shell you are using, but they generally don't support regular expressions that way, although there are common *nix CLI tools (grep, sed, etc) that do.

What shells like bash do support is globbing, which uses some similiar characters (eg, *) but is not the same thing.

Newer versions of bash do have a regular expression operator, =~:

for x in `ls`; do 
    if [[ $x =~ .+\..* ]]; then 
        echo $x; 
    fi; 
done

How to deal with the URISyntaxException

You have to encode your parameters.

Something like this will do:

import java.net.*;
import java.io.*;

public class EncodeParameter { 

    public static void main( String [] args ) throws URISyntaxException ,
                                         UnsupportedEncodingException   { 

        String myQuery = "^IXIC";

        URI uri = new URI( String.format( 
                           "http://finance.yahoo.com/q/h?s=%s", 
                           URLEncoder.encode( myQuery , "UTF8" ) ) );

        System.out.println( uri );

    }
}

http://java.sun.com/javase/6/docs/api/java/net/URLEncoder.html

View stored procedure/function definition in MySQL

Perfect, try it:

SELECT ROUTINE_DEFINITION FROM INFORMATION_SCHEMA.ROUTINES
    WHERE ROUTINE_SCHEMA = 'yourdb' AND ROUTINE_TYPE = 'PROCEDURE' AND ROUTINE_NAME = "procedurename";

Get visible items in RecyclerView

For StaggeredGridLayoutManager do this:

RecyclerView rv = findViewById(...);
StaggeredGridLayoutManager lm = new StaggeredGridLayoutManager(...);
rv.setLayoutManager(lm);

And to get visible item views:

int[] viewsIds = lm.findFirstCompletelyVisibleItemPositions(null);
ViewHolder firstViewHolder = rvPlantios.findViewHolderForLayoutPosition(viewsIds[0]);
View itemView = viewHolder.itemView;

Remember to check if it is empty.

Nginx fails to load css files

For me this was ad blocker installed on web browser. It was not letting load the style.css

jQuery Clone table row

Try this variation:

$(".tr_clone_add").live('click', CloneRow);

function CloneRow()
{
    $(this).closest('.tr_clone').clone().insertAfter(".tr_clone:last");
}

PHP function overloading

What about this:

function($arg = NULL) {

    if ($arg != NULL) {
        etc.
        etc.
    }
}

Where does Java's String constant pool live, the heap or the stack?

As explained by this answer, the exact location of the string pool is not specified and can vary from one JVM implementation to another.

It is interesting to note that until Java 7, the pool was in the permgen space of the heap on hotspot JVM but it has been moved to the main part of the heap since Java 7:

Area: HotSpot
Synopsis: In JDK 7, interned strings are no longer allocated in the permanent generation of the Java heap, but are instead allocated in the main part of the Java heap (known as the young and old generations), along with the other objects created by the application. This change will result in more data residing in the main Java heap, and less data in the permanent generation, and thus may require heap sizes to be adjusted. Most applications will see only relatively small differences in heap usage due to this change, but larger applications that load many classes or make heavy use of the String.intern() method will see more significant differences. RFE: 6962931

And in Java 8 Hotspot, Permanent Generation has been completely removed.

How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?

In order to create an anonymous type (or any type) with a property that has a reserved keyword as its name in C#, you can prepend the property name with an at sign, @:

Html.BeginForm("Foo", "Bar", FormMethod.Post, new { @class = "myclass"})

For VB.NET this syntax would be accomplished using the dot, ., which in that language is default syntax for all anonymous types:

Html.BeginForm("Foo", "Bar", FormMethod.Post, new with { .class = "myclass" })

Duplicate AssemblyVersion Attribute

If you're having this problem in a Build Pipeline on Azure DevOps, try putting the Build Action as "Content" and Copy to Output Directory equal to "Copy if newer" in the AssembyInfo.cs file properties.

PHP function to make slug (URL string)

This may be a way to do it too. Inspired from these links Experts-exchange and alinalexander

function slugifier($txt){

   /* Get rid of accented characters */
   $search = explode(",","ç,æ,œ,á,é,í,ó,ú,à,è,ì,ò,ù,ä,ë,ï,ö,ü,ÿ,â,ê,î,ô,û,å,e,i,ø,u");
   $replace = explode(",","c,ae,oe,a,e,i,o,u,a,e,i,o,u,a,e,i,o,u,y,a,e,i,o,u,a,e,i,o,u");
   $txt = str_replace($search, $replace, $txt);

   /* Lowercase all the characters */
   $txt = strtolower($txt);

   /* Avoid whitespace at the beginning and the ending */
   $txt = trim($txt);

   /* Replace all the characters that are not in a-z or 0-9 by a hyphen */
   $txt = preg_replace("/[^a-z0-9]/", "-", $txt);
   /* Remove hyphen anywhere it's more than one */
   $txt = preg_replace("/[\-]+/", '-', $txt);
   return $txt;   
}

maxFileSize and acceptFileTypes in blueimp file upload plugin do not work. Why?

This works for me in firefox

$('#fileupload').fileupload({

    dataType: 'json',
    //acceptFileTypes: /(\.|\/)(xml|pdf)$/i,
    //maxFileSize: 15000000,

    add: function (e, data) {
        var uploadErrors = [];

        var acceptFileTypes = /\/(pdf|xml)$/i;
        if(data.originalFiles[0]['type'].length && !acceptFileTypes.test(data.originalFiles[0]['type'])) {
            uploadErrors.push('File type not accepted');
        }

        console.log(data.originalFiles[0]['size']) ;
        if (data.originalFiles[0]['size'] > 5000000) {
            uploadErrors.push('Filesize too big');
        }
        if(uploadErrors.length > 0) {
            alert(uploadErrors.join("\n"));
        } else {
            data.context = $('<p/>').text('Uploading...').appendTo(document.body);
            data.submit();
        }

    },
    done: function (e, data) {
        data.context.text('Success!.');
    }
});