Programs & Examples On #Radiobuttonfor

How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

It's not too pretty, but if you have to implement only very few radio buttons for the entire site, something like this might also be an option:

<%=Html.RadioButtonFor(m => m.Gender,"Male",Model.Gender=="Male" ? new { @checked = "checked" } : null)%>

Installing a dependency with Bower from URL and specify version

Just specifying the uri endpoint worked for me, bower 1.3.9

  "dependencies": {
    "jquery.cookie": "latest",
    "everestjs": "http://www.everestjs.net/static/st.v2.js"
  }

Running bower install, I received following output:

bower new           version for http://www.everestjs.net/static/st.v2.js#*
bower resolve       http://www.everestjs.net/static/st.v2.js#*
bower download      http://www.everestjs.net/static/st.v2.js

You could also try updating bower

  • npm update -g bower

According to documentation: the following types of urls are supported:

http://example.com/script.js
http://example.com/style.css
http://example.com/package.zip (contents will be extracted)
http://example.com/package.tar (contents will be extracted)

How to refer to relative paths of resources when working with a code repository

If you are using setup tools or distribute (a setup.py install) then the "right" way to access these packaged resources seem to be using package_resources.

In your case the example would be

import pkg_resources
my_data = pkg_resources.resource_string(__name__, "foo.dat")

Which of course reads the resource and the read binary data would be the value of my_data

If you just need the filename you could also use

resource_filename(package_or_requirement, resource_name)

Example:

resource_filename("MyPackage","foo.dat")

The advantage is that its guaranteed to work even if it is an archive distribution like an egg.

See http://packages.python.org/distribute/pkg_resources.html#resourcemanager-api

Is it possible to change the speed of HTML's <marquee> tag?

This attribute takes the time in milliseconds.

Delay : 100 Milliseconds

<marquee scrolldelay="100">Scrolling text</marquee>

Delay : 400 Milliseconds

<marquee scrolldelay="400">Scrolling text</marquee>

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

This worked for me:

  1. Delete the originally created site.
  2. Recreate the site in IIS
  3. Clean solution
  4. Build solution

Seems like something went south when I originally created the site. I hate solutions that are similar to "Restart your machine, then reinstall windows" without knowing what caused the error. But, this worked for me. Quick and simple. Hope it helps someone else.

Jquery: how to trigger click event on pressing enter key

You can use this code

$(document).keypress(function(event){
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if(keycode == '13'){
       alert('You pressed a ENTER key.');
    }
});

Table cell widths - fixing width, wrapping/truncating long words

try td {background-color:white}

It just worked for a column I didn't want to get trampled by a previous column's long text.

How to change progress bar's progress color in Android

This is not programmatically but I think it could help a lot of people anyway.
I tried a lot and the most efficient way was to add this lines to my ProgressBar in the .xml File:

            android:indeterminate="true"
            android:indeterminateTintMode="src_atop"
            android:indeterminateTint="@color/secondary"

So in the end this code did it for me:

<ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:layout_marginTop="50dp"
            android:layout_marginBottom="50dp"
            android:visibility="visible"
            android:indeterminate="true"
            android:indeterminateTintMode="src_atop"
            android:indeterminateTint="@color/secondary">

This solution works for API 21+

Javascript (+) sign concatenates instead of giving sum of variables

var divID = "question-" + (parseInt(i)+1);

Use this + operator behave as concat that's why it showing 11.

substring of an entire column in pandas dataframe

Use the str accessor with square brackets:

df['col'] = df['col'].str[:9]

Or str.slice:

df['col'] = df['col'].str.slice(0, 9)

In Java, how to append a string more efficiently?

You can use StringBuffer or StringBuilder for this. Both are for dynamic string manipulation. StringBuffer is thread-safe where as StringBuilder is not.

Use StringBuffer in a multi-thread environment. But if it is single threaded StringBuilder is recommended and it is much faster than StringBuffer.

Best way to do multi-row insert in Oracle?

This works in Oracle:

insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE)
          select 8000,0,'Multi 8000',1 from dual
union all select 8001,0,'Multi 8001',1 from dual

The thing to remember here is to use the from dual statement.

number_format() with MySQL

At least as far back as MySQL 5.5 you can use format:

SELECT FORMAT(123456789.123456789,2);
/* produces 123,456,789.12 */

SELECT FORMAT(123456789.123456789,2,'de_DE');
/* 
    produces 123.456.789,12
    note the swapped . and , for the de_DE locale (German-Germany) 
*/

From the MySQL docs: https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_format

Available locales are listed elsewhere in the docs: https://dev.mysql.com/doc/refman/5.5/en/locale-support.html

Disabled form fields not submitting data

We can also use the readonly only with below attributes -

readonly onclick='return false;'

This is because if we will only use the readonly then radio buttons will be editable. To avoid this situation we can use readonly with above combination. It will restrict the editing and element's values will also passed during form submission.

What regex will match every character except comma ',' or semi-colon ';'?

Use character classes. A character class beginning with caret will match anything not in the class.

[^,;]

PHP class: Global variable as property in class

class myClass { protected $foo;

public function __construct(&$var)
{
    $this->foo = &$var;
}

public function foo()
{
    return ++$this->foo;
}

}

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

• A Dockerfile should specify at least one CMD or ENTRYPOINT instruction

• Only the last CMD and ENTRYPOINT in a Dockerfile will be used

• ENTRYPOINT should be defined when using the container as an executable

• You should use the CMD instruction as a way of defining default arguments for the command defined as ENTRYPOINT or for executing an ad-hoc command in a container

• CMD will be overridden when running the container with alternative arguments

• ENTRYPOINT sets the concrete default application that is used every time a container is created using the image

• If you couple ENTRYPOINT with CMD, you can remove an executable from CMD and just leave its arguments which will be passed to ENTRYPOINT

• The best use for ENTRYPOINT is to set the image's main command, allowing that image to be run as though it was that command (and then use CMD as the default flags)

throwing an exception in objective-c/cocoa

There is no reason not to use exceptions normally in objective C even to signify business rule exceptions. Apple can say use NSError who cares. Obj C has been around a long time and at one time ALL C++ documentation said the same thing. The reason it doesnt matter how expensive throwing and catching an exception is, is the lifetime of an exception is exceedingly short and...its an EXCEPTION to the normal flow. I have never heard anyone say ever in my life, man that exception took a long time to be thrown and caught.

Also, there are people that think that objective C itself is too expensive and code in C or C++ instead. So saying always use NSError is ill-informed and paranoid.

But the question of this thread hasnt yet been answered whats the BEST way to throw an exception. The ways to return NSError are obvious.

So is it: [NSException raise:... @throw [[NSException alloc] initWithName.... or @throw [[MyCustomException... ?

I use the checked/unchecked rule here slightly differently than above.

The real difference between the (using the java metaphor here) checked/unchecked is important --> whether you can recover from the exception. And by recover I mean not just NOT crash.

So I use custom exception classes with @throw for recoverable exceptions, because its likely I will have some app method looking for certain types of failures in multiple @catch blocks. For example if my app is an ATM machine, I would have a @catch block for the "WithdrawalRequestExceedsBalanceException".

I use NSException:raise for runtime exceptions since I have no way to recover from the exception, except to catch it at a higher level and log it. And theres no point in creating a custom class for that.

Anyway thats what I do, but if there's a better, similarly expressive way I would like to know as well. In my own code, since I stopped coding C a hella long time ago I never return an NSError even if I am passed one by an API.

Twitter Bootstrap - borders

If you look at Twitter's own container-app.html demo on GitHub, you'll get some ideas on using borders with their grid.

For example, here's the extracted part of the building blocks to their 940-pixel wide 16-column grid system:

.row {
    zoom: 1;
    margin-left: -20px;
}

.row > [class*="span"] {
    display: inline;
    float: left;
    margin-left: 20px;
}

.span4 {
    width: 220px;
}

To allow for borders on specific elements, they added embedded CSS to the page that reduces matching classes by enough amount to account for the border(s).

Screenshot of Example Page

For example, to allow for the left border on the sidebar, they added this CSS in the <head> after the the main <link href="../bootstrap.css" rel="stylesheet">.

.content .span4 {
    margin-left: 0;
    padding-left: 19px;
    border-left: 1px solid #eee;
}

You'll see they've reduced padding-left by 1px to allow for the addition of the new left border. Since this rule appears later in the source order, it overrides any previous or external declarations.

I'd argue this isn't exactly the most robust or elegant approach, but it illustrates the most basic example.

How to pass a null variable to a SQL Stored Procedure from C#.net code

I use a method to convert to DBNull if it is null

    // Converts to DBNull, if Null
    public static object ToDBNull(object value)
    {
        if (null != value)
            return value;
        return DBNull.Value;
    }

So when setting the parameter, just call the function

    sqlComm.Parameters.Add(new SqlParameter("@NoteNo", LibraryHelper.ToDBNull(NoteNo)));

This will ensure any nulls, get changed to DBNull.Value, else it will stay the same.

What is a NoReverseMatch error, and how do I fix it?

It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView - I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name for the new class, it worked fine.

MySQL "Group By" and "Order By"

Do a GROUP BY after the ORDER BY by wrapping your query with the GROUP BY like this:

SELECT t.* FROM (SELECT * FROM table ORDER BY time DESC) t GROUP BY t.from

error: package com.android.annotations does not exist

You shouldn't edit any code manually jetify should do this job for you, if you are running/building from cli using react-native you dont' need to do anything but if you are running/building Andriod studio you need to run jetify as pre-build, here is how can you automate this:

1- From the above menu go to edit configurations:

enter image description here

2- Add the bottom of the screen you will find before launch click on the plus and choose Run External Tool

enter image description here

2- Fill the following information, note that the working directory is your project root directory (not the android directory):

enter image description here

3- Make sure this run before anything else, in the end, your configuration should look something like this: enter image description here

Can't update data-attribute value

For myself, using Jquery lib 2.1.1 the following did NOT work the way I expected:

Set element data attribute value:

$('.my-class').data('num', 'myValue');
console.log($('#myElem').data('num'));// as expected = 'myValue'

BUT the element itself remains without the attribute:

<div class="my-class"></div>

I needed the DOM updated so I could later do $('.my-class[data-num="myValue"]') //current length is 0

So I had to do

$('.my-class').attr('data-num', 'myValue');

To get the DOM to update:

<div class="my-class" data-num="myValue"></div>

Whether the attribute exists or not $.attr will overwrite.

For..In loops in JavaScript - key value pairs

You can use a 'for in' loop for this:

for (var key in bar) {
     var value = bar[key];
}

How do I load a file from resource folder?

this.getClass().getClassLoader().getResource("filename").getPath()

Why does Path.Combine not properly concatenate filenames that start with Path.DirectorySeparatorChar?

Following Christian Graus' advice in his "Things I Hate about Microsoft" blog titled "Path.Combine is essentially useless.", here is my solution:

public static class Pathy
{
    public static string Combine(string path1, string path2)
    {
        if (path1 == null) return path2
        else if (path2 == null) return path1
        else return path1.Trim().TrimEnd(System.IO.Path.DirectorySeparatorChar)
           + System.IO.Path.DirectorySeparatorChar
           + path2.Trim().TrimStart(System.IO.Path.DirectorySeparatorChar);
    }

    public static string Combine(string path1, string path2, string path3)
    {
        return Combine(Combine(path1, path2), path3);
    }
}

Some advise that the namespaces should collide, ... I went with Pathy, as a slight, and to avoid namespace collision with System.IO.Path.

Edit: Added null parameter checks

How do you Make A Repeat-Until Loop in C++?

Repeat is supposed to be a simple loop n times loop... a conditionless version of a loop.

#define repeat(n) for (int i = 0; i < n; i++) 

repeat(10) {
    //do stuff
}

you can also also add an extra barce to isolate the i variable even more

#define repeat(n) { for (int i = 0; i < n; i++) 
#define endrepeat }

repeat(10) {
    //do stuff
} endrepeat;

[edit] Someone posted a concern about passing a something other than a value, such as an expression. just change to loop to run backwards, causing the expression to be evaluated only once

#define repeat(n) { for (int i = (n); i > 0; --i)

How can I debug a HTTP POST in Chrome?

  1. Go to Chrome Developer Tools (Chrome Menu -> More Tools -> Developer Tools)
  2. Choose "Network" tab
  3. Refresh the page you're on
  4. You'll get list of http queries that happened, while the network console was on. Select one of them in the left
  5. Choose "Headers" tab

Voila!

enter image description here

How to handle change text of span

Found the solution here

Lets say you have span1 as <span id='span1'>my text</span>
text change events can be captured with:

$(document).ready(function(){
    $("#span1").on('DOMSubtreeModified',function(){
         // text change handler
     });

 });
 

Swing vs JavaFx for desktop applications

On older notebooks with integrated video Swing app starts and works much faster than JavaFX app. As for development, I'd recommend switch to Scala - comparable Scala Swing app contains 2..3 times less code than Java. As for Swing vs SWT: Netbeans GUI considerably faster than Eclipse...

Is it possible to use raw SQL within a Spring Repository

we can use createNativeQuery("Here Nagitive SQL Query ");

for Example :

Query q = em.createNativeQuery("SELECT a.firstname, a.lastname FROM Author a");
List<Object[]> authors = q.getResultList();

Class Not Found: Empty Test Suite in IntelliJ

In your Maven project structure src/main/java right click on java directory and select option Mark directory as --> Sources Root

Similarly do the same with test directory so: src/test/java right click on java directory and select option Mark directory as --> Test Sources Root

Worked for me :-)

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

Documenting in detail for future readers:

The short answer is you need to override both the methods. The shouldOverrideUrlLoading(WebView view, String url) method is deprecated in API 24 and the shouldOverrideUrlLoading(WebView view, WebResourceRequest request) method is added in API 24. If you are targeting older versions of android, you need the former method, and if you are targeting 24 (or later, if someone is reading this in distant future) it's advisable to override the latter method as well.

The below is the skeleton on how you would accomplish this:

class CustomWebViewClient extends WebViewClient {

    @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        final Uri uri = Uri.parse(url);
        return handleUri(uri);
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        final Uri uri = request.getUrl();
        return handleUri(uri);
    }

    private boolean handleUri(final Uri uri) {
        Log.i(TAG, "Uri =" + uri);
        final String host = uri.getHost();
        final String scheme = uri.getScheme();
        // Based on some condition you need to determine if you are going to load the url 
        // in your web view itself or in a browser. 
        // You can use `host` or `scheme` or any part of the `uri` to decide.
        if (/* any condition */) {
            // Returning false means that you are going to load this url in the webView itself
            return false;
        } else {
            // Returning true means that you need to handle what to do with the url
            // e.g. open web page in a Browser
            final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
            return true;
        }
    }
}

Just like shouldOverrideUrlLoading, you can come up with a similar approach for shouldInterceptRequest method.

How to add a .dll reference to a project in Visual Studio

You probably are looking for AddReference dialog accessible from Project Context Menu (right click..)

From there you can reference dll's, after which you can reference namespaces that you need in your code.

AngularJS - Trigger when radio button is selected

Another approach is using Object.defineProperty to set valueas a getter setter property in the controller scope, then each change on the value property will trigger a function specified in the setter:

The HTML file:

<input type="radio" ng-model="value" value="one"/>
<input type="radio" ng-model="value" value="two"/>
<input type="radio" ng-model="value" value="three"/>

The javascript file:

var _value = null;
Object.defineProperty($scope, 'value', {
  get: function () {
    return _value;
  },         
  set: function (value) {
    _value = value;
    someFunction();
  }
});

see this plunker for the implementation

Where do I put my php files to have Xampp parse them?

This will work for me:

.../xampp/htdocs/php/test.phtml

What is w3wp.exe?

Chris pretty much sums up what w3wp is. In order to disable the warning, go to this registry key:

HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0\Debugger

And set the value DisableAttachSecurityWarning to 1.

How to find index of STRING array in Java from a given value?

Use Arrays class to do this

Arrays.sort(TYPES);
int index = Arrays.binarySearch(TYPES, "Sedan");

support FragmentPagerAdapter holds reference to old fragments

I solved this issue by accessing my fragments directly through the FragmentManager instead of via the FragmentPagerAdapter like so. First I need to figure out the tag of the fragment auto generated by the FragmentPagerAdapter...

private String getFragmentTag(int pos){
    return "android:switcher:"+R.id.viewpager+":"+pos;
}

Then I simply get a reference to that fragment and do what I need like so...

Fragment f = this.getSupportFragmentManager().findFragmentByTag(getFragmentTag(1));
((MyFragmentInterface) f).update(id, name);
viewPager.setCurrentItem(1, true);

Inside my fragments I set the setRetainInstance(false); so that I can manually add values to the savedInstanceState bundle.

@Override
public void onSaveInstanceState(Bundle outState) {
    if(this.my !=null)
        outState.putInt("myId", this.my.getId());

    super.onSaveInstanceState(outState);
}

and then in the OnCreate i grab that key and restore the state of the fragment as necessary. An easy solution which was hard (for me at least) to figure out.

SQL Server: Examples of PIVOTing String data

Well, for your sample and any with a limited number of unique columns, this should do it.

select 
    distinct a,
    (select distinct t2.b  from t t2  where t1.a=t2.a and t2.b='VIEW'),
    (select distinct t2.b from t t2  where t1.a=t2.a and t2.b='EDIT')
from t t1

How to add app icon within phonegap projects?

FAQ: ICON / SPLASH SCREEN (Cordova 5.x / 2015)

I present my answer as a general FAQ that may help you to solve many problems I've encountered while dealing with icons/splash screens. You may find out like me that the documentation is not always very clear nor up to date. This will probably go to StackOverflow documentation when available.

First: answering the question

How can I add custom app icons for iOS and Android with phonegap?

In your version of Cordova the icon tag is useless. It is not even documented in Cordova 3.0.0. You should use the documentation version that fits the cli you are using and not the latest one!

The icon tag does not work for Android at all before the version 3.5.0 according to what I can see in the different versions of the documentation. In 3.4.0 they still advice to manually copy the files

In newer versions: your config.xml looks better for newer Cordova versions. However there are still many things you may want to know. If you decide to upgrade here are some useful things to modify:

  • You don't need the gap: namespace
  • You need <preference name="SplashScreen" value="screen" /> for Android

Here are more details of the questions you might ask yourself when trying to deal with icons and splash screen:

Can I use an old version of Cordova / Phonegap

No, the icon/splashscreen feature was not in former versions of Cordova so you must use a recent version. In former versions, only Phonegap Build did handle the icons/splash screen so building locally and handling icons was only possible with a hook. I don't know the minimum version to use this feature but with 5.1.1 it works fine in both Cordova/Phonegap cli. With Cordova 3.5 it didn't work for me.

Edit: for Android you must use at least 3.5.0

How can I debug the build process about icons?

The cli use a CP command. If you provide an invalid icon path, it will show a cp error:

sebastien@sebastien-xps:cordova (dev *+$%)$ cordova run android --device
cp: no such file or directory: /home/sebastien/Desktop/Stample-react/cordova/res/www/stample_splash.png

Edit: you have use cordova build <platform> --verbose to get logs of cp command usage to see where your icons gets copied

The icons should go in a folder according to the config. For me it goes in many subfolders in : platforms/android/build/intermediates/res/armv7/debug/drawable-hdpi-v4/icon.png

Then you can find the APK, and open it as a zip archive to check the icons are present. They must be in a res/drawable* folder because it's a special folder for Android.

Where should I put the icons/splash screens in my project?

In many examples you will find the icons/splash screens are declared inside a res folder. This res is a special Android folder in the output APK, but it does not mean you have to use a res folder in your project.

You can put your icon anywhere, but the path you use must be relative to the root of the project, and not www so take care! This is documented, but not clearly because all the examples are using res and you don't know where this folder is :(

I mean if you put the icon in www/icon.png you absolutly must include www in your path.

Edit Mars 2016: after upgrading my versions, now it seems that icons are relative to www folder but documentation has not been changed (issue)

Does <icon src="icon.png"/> work?

No it does not!.

On Android, it seems it used to work before (when the density attribute was not supported yet?) but not anymore. See this Cordova issue

On iOS, it seems using this global declaration may override more specific declarations so take care and build with --verbose to ensure everything works as expected.

Can I use the same icon/splash screen file for all the densities.

Yes you can. You can even use the same file for both the icon, and splash screen (just to test!). I have used a "big" icon file of 65kb without any problem.

What's the difference when using the platform tag vs the platform attribute

<icon src="icon.png" platform="android" density="ldpi" />

is the same as

<platform name="android">
    <icon src="www/stample_icon.png" density="ldpi" />
</platform>

Should I use the gap: namespace if using Phonegap?

In my experience new versions of Phonegap or Cordova are both able to understand icon declarations without using any gap: xml namespace.

However I'm still waiting for a valid answer here: cordova/phonegap plugin add VS config.xml

As far as I understand, some features with the gap: namespace may be available earlier in PhonegapBuild, then in Phonegap and then being ported to Cordova (?)

Is <preference name="SplashScreen" value="screen" /> required?

At least for Android yes it is. I opened an issue with additional explainations.

Does icon declaration order matters?

Yes it does! It may not have any impact on Android but it has on iOS according to my tests. This is unexpected and undocumented behavior so I opened another issue.

Do I need cordova-plugin-splashscreen?

Yes this is absolutly required if you want the splash screen to work. The documentation is not clear (issue) and let us think that the plugin is required only to offer a splash screen javascript API.

How can I resize the images for all width/height/densities fastly

There are tools to help you do that. The best one for me is http://makeappicon.com/ but it requires to provide an email address.

Other possible solutions are:

Can you give me an example config?

Yes. Here's my real config.xml

<?xml version='1.0' encoding='utf-8'?>
<widget id="co.x" version="0.2.6" xmlns="http://www.w3.org/ns/widgets" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:gap="http://phonegap.com/ns/1.0">
    <name>x</name>
    <description>
        x
    </description>
    <author email="[email protected]" href="https://x.co">
        x
    </author>
    <content src="index.html" />
    <preference name="permissions"                  value="none" />
    <preference name="webviewbounce"                value="false" />
    <preference name="StatusBarOverlaysWebView"     value="false" />
    <preference name="StatusBarBackgroundColor"     value="#0177C6" />
    <preference name="detect-data-types"            value="true" />
    <preference name="stay-in-webview"              value="false" />
    <preference name="android-minSdkVersion"        value="14" />
    <preference name="android-targetSdkVersion"     value="22" />
    <preference name="phonegap-version"             value="cli-5.1.1" />

    <preference name="SplashScreenDelay"            value="10000" />
    <preference name="SplashScreen"                 value="screen" />


    <plugin name="cordova-plugin-device"                spec="1.0.1" />
    <plugin name="cordova-plugin-console"               spec="1.0.1" />
    <plugin name="cordova-plugin-whitelist"             spec="1.1.0" />
    <plugin name="cordova-plugin-crosswalk-webview"     spec="1.2.0" />
    <plugin name="cordova-plugin-statusbar"             spec="1.0.1" />
    <plugin name="cordova-plugin-screen-orientation"    spec="1.3.6" />
    <plugin name="cordova-plugin-splashscreen"          spec="2.1.0" />

    <access origin="http://*" />
    <access origin="https://*" />

    <access launch-external="yes" origin="tel:*" />
    <access launch-external="yes" origin="geo:*" />
    <access launch-external="yes" origin="mailto:*" />
    <access launch-external="yes" origin="sms:*" />
    <access launch-external="yes" origin="market:*" />

    <platform name="android">
        <icon src="www/stample_icon.png" density="ldpi" />
        <icon src="www/stample_icon.png" density="mdpi" />
        <icon src="www/stample_icon.png" density="hdpi" />
        <icon src="www/stample_icon.png" density="xhdpi" />
        <icon src="www/stample_icon.png" density="xxhdpi" />
        <icon src="www/stample_icon.png" density="xxxhdpi" />
        <splash src="www/stample_splash.png" density="land-hdpi"/>
        <splash src="www/stample_splash.png" density="land-ldpi"/>
        <splash src="www/stample_splash.png" density="land-mdpi"/>
        <splash src="www/stample_splash.png" density="land-xhdpi"/>
        <splash src="www/stample_splash.png" density="land-xhdpi"/>
        <splash src="www/stample_splash.png" density="land-xhdpi"/>
        <splash src="www/stample_splash.png" density="port-hdpi"/>
        <splash src="www/stample_splash.png" density="port-ldpi"/>
        <splash src="www/stample_splash.png" density="port-mdpi"/>
        <splash src="www/stample_splash.png" density="port-xhdpi"/>
        <splash src="www/stample_splash.png" density="port-xxhdpi"/>
        <splash src="www/stample_splash.png" density="port-xxxhdpi"/>
    </platform>

    <platform name="ios">
        <icon src="www/stample_icon.png" width="180" height="180" />
        <icon src="www/stample_icon.png" width="60" height="60" />
        <icon src="www/stample_icon.png" width="120" height="120" />
        <icon src="www/stample_icon.png" width="76" height="76" />
        <icon src="www/stample_icon.png" width="152" height="152" />
        <icon src="www/stample_icon.png" width="40" height="40" />
        <icon src="www/stample_icon.png" width="80" height="80" />
        <icon src="www/stample_icon.png" width="57" height="57" />
        <icon src="www/stample_icon.png" width="114" height="114" />
        <icon src="www/stample_icon.png" width="72" height="72" />
        <icon src="www/stample_icon.png" width="144" height="144" />
        <icon src="www/stample_icon.png" width="29" height="29" />
        <icon src="www/stample_icon.png" width="58" height="58" />
        <icon src="www/stample_icon.png" width="50" height="50" />
        <icon src="www/stample_icon.png" width="100" height="100" />
        <splash src="www/stample_splash.png" width="320" height="480"/>
        <splash src="www/stample_splash.png" width="640" height="960"/>
        <splash src="www/stample_splash.png" width="768" height="1024"/>
        <splash src="www/stample_splash.png" width="1536" height="2048"/>
        <splash src="www/stample_splash.png" width="1024" height="768"/>
        <splash src="www/stample_splash.png" width="2048" height="1536"/>
        <splash src="www/stample_splash.png" width="640" height="1136"/>
        <splash src="www/stample_splash.png" width="750" height="1334"/>
        <splash src="www/stample_splash.png" width="1242" height="2208"/>
        <splash src="www/stample_splash.png" width="2208" height="1242"/>
    </platform>

    <allow-intent href="*" />
    <engine name="browser" spec="^3.6.0" />
    <engine name="android" spec="^4.0.2" />
</widget>

A good source of examples are starter kits. Like phonegap-start or Ionic starter

Gradle - Could not find or load main class

I fixed this by running a clean of by gradle build (or delete the gradle build folder mannually)

This occurs if you move the main class to a new package and the old main class is still referenced in the claspath

Using HTML data-attribute to set CSS background-image url

How about using some Sass? Here's what I did to achieve something like this (although note that you have to create a Sass list for each of the data-attributes).

/*
  Iterate over list and use "data-social" to put in the appropriate background-image.
*/
$social: "fb", "twitter", "youtube";

@each $i in $social {
  [data-social="#{$i}"] {
    background: url('#{$image-path}/icons/#{$i}.svg') no-repeat 0 0;
    background-size: cover; // Only seems to work if placed below background property
  }
}

Essentially, you list all of your data attribute values. Then use Sass @each to iterate through and select all the data-attributes in the HTML. Then, bring in the iterator variable and have it match up to a filename.

Anyway, as I said, you have to list all of the values, then make sure that your filenames incorporate the values in your list.

How to round each item in a list of floats to 2 decimal places?

If you really want an iterator-free solution, you can use numpy and its array round function.

import numpy as np
myList = list(np.around(np.array(myList),2))

Rebase array keys after unsetting elements

Got another interesting method:

$array = array('a', 'b', 'c', 'd'); 
unset($array[2]); 

$array = array_merge($array); 

Now the $array keys are reset.

Getting the location from an IP address

I like the free GeoLite City from Maxmind which works for most applications and from which you can upgrade to a paying version if it's not precise enough. There is a PHP API included, as well as for other languages. And if you are running Lighttpd as a webserver, you can even use a module to get the information in the SERVER variable for every visitor if that's what you need.

I should add there is also a free Geolite Country (which would be faster if you don't need to pinpoint the city the IP is from) and Geolite ASN (if you want to know who owns the IP) and that finally all these are downloadable on your own server, are updated every month and are pretty quick to lookup with the provided APIs as they state "thousands of lookups per second".

How do I select the "last child" with a specific class name in CSS?

You can't target the last instance of the class name in your list without JS.

However, you may not be entirely out-of-css-luck, depending on what you are wanting to achieve. For example, by using the next sibling selector, I have added a visual divider after the last of your .list elements here: http://jsbin.com/vejixisudo/edit?html,css,output

Reactive forms - disabled attribute

disabling of mat form fields is exempted if you are using form validation,so do make sure that your form field does not have any validations like(validators.required),this worked for me. for ex:

editUserPhone: new FormControl({value:' ',disabled:true})

this makes the phone numbers of user to be non editable.

Using an array from Observable Object with ngFor and Async Pipe Angular 2

If you don't have an array but you are trying to use your observable like an array even though it's a stream of objects, this won't work natively. I show how to fix this below assuming you only care about adding objects to the observable, not deleting them.

If you are trying to use an observable whose source is of type BehaviorSubject, change it to ReplaySubject then in your component subscribe to it like this:

Component

this.messages$ = this.chatService.messages$.pipe(scan((acc, val) => [...acc, val], []));

Html

<div class="message-list" *ngFor="let item of messages$ | async">

Adding files to a GitHub repository

Open github app. Then, add the Folder of files into the github repo file onto your computer (You WILL need to copy the repo onto your computer. Most repo files are located in the following directory: C:\Users\USERNAME\Documents\GitHub\REPONAME) Then, in the github app, check our your repo. You can easily commit from there.

Expected initializer before function name

You are missing a semicolon at the end of your 'struct' definition.

Also,

*sotrudnik

needs to be

sotrudnik*

TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data

Non-numpy functions like math.abs() or math.log10() don't play nicely with numpy arrays. Just replace the line raising an error with:

m = np.log10(np.abs(x))

Apart from that the np.polyfit() call will not work because it is missing a parameter (and you are not assigning the result for further use anyway).

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

How do I count unique values inside a list

For ndarray there is a numpy method called unique:

np.unique(array_name)

Examples:

>>> np.unique([1, 1, 2, 2, 3, 3])
array([1, 2, 3])
>>> a = np.array([[1, 1], [2, 3]])
>>> np.unique(a)
array([1, 2, 3])

For a Series there is a function call value_counts():

Series_name.value_counts()

jQuery: how to scroll to certain anchor/div on page load?

I have tried some hours now and the easiest way to stop browsers to jump to the anchor instead of scrolling to it is: Using another anchor (an id you do not use on the site). So instead of linking to "http://#YourActualID" you link to "http://#NoIDonYourSite". Poof, browsers won’t jump anymore.

Then just check if an anchor is set (with the script provided below, that is pulled out of the other thread!). And set your actual id you want to scroll to.

$(document).ready(function(){


  $(window).load(function(){
    // Remove the # from the hash, as different browsers may or may not include it
    var hash = location.hash.replace('#','');

    if(hash != ''){

       // Clear the hash in the URL
       // location.hash = '';   // delete front "//" if you want to change the address bar
        $('html, body').animate({ scrollTop: $('#YourIDtoScrollTo').offset().top}, 1000);

       }
   });
});

See https://lightningsoul.com/media/article/coding/30/YOUTUBE-SOCKREAD-SCRIPT-FOR-MIRC#content for a working example.

Two Radio Buttons ASP.NET C#

In order to make it work, you have to set property GroupName of both radio buttons to the same value:

<asp:RadioButton id="rbMetric" runat="server" GroupName="measurementSystem"></asp:RadioButton>
<asp:RadioButton id="rbUS" runat="server" GroupName="measurementSystem"></asp:RadioButton>

Personally, I prefer to use a RadioButtonList:

<asp:RadioButtonList ID="rblMeasurementSystem" runat="server">
    <asp:ListItem Text="Metric" Value="metric" />
    <asp:ListItem Text="US" Value="us" />
</asp:RadioButtonList>

ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

I've put together what I hope is a pretty robust solution, including some of the techniques in other answers. It is a new class derived from ObservableCollection<>, which I'm calling FullyObservableCollection<>

It has the following features:

  • It adds a new event, ItemPropertyChanged. I've deliberately kept this separate from the existing CollectionChanged:
    • To aid backward compatibility.
    • So more relevant detail can be given in the new ItemPropertyChangedEventArgs that accompanies it: the original PropertyChangedEventArgs and the index within the collection.
  • It replicates all the constructors from ObservableCollection<>.
  • It correctly handles the list being reset (ObservableCollection<>.Clear()), avoiding a possible memory leak.
  • It overrides the base class's OnCollectionChanged(), rather than a more resource-intensive subscription to the CollectionChanged event.

Code

The complete .cs file follows. Note that a few features of C# 6 have been used, but it should be fairly simple to backport it:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel;

namespace Utilities
{
    public class FullyObservableCollection<T> : ObservableCollection<T>
        where T : INotifyPropertyChanged
    {
        /// <summary>
        /// Occurs when a property is changed within an item.
        /// </summary>
        public event EventHandler<ItemPropertyChangedEventArgs> ItemPropertyChanged;

        public FullyObservableCollection() : base()
        { }

        public FullyObservableCollection(List<T> list) : base(list)
        {
            ObserveAll();
        }

        public FullyObservableCollection(IEnumerable<T> enumerable) : base(enumerable)
        {
            ObserveAll();
        }

        protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Remove ||
                e.Action == NotifyCollectionChangedAction.Replace)
            {
                foreach (T item in e.OldItems)
                    item.PropertyChanged -= ChildPropertyChanged;
            }

            if (e.Action == NotifyCollectionChangedAction.Add ||
                e.Action == NotifyCollectionChangedAction.Replace)
            {
                foreach (T item in e.NewItems)
                    item.PropertyChanged += ChildPropertyChanged;
            }

            base.OnCollectionChanged(e);
        }

        protected void OnItemPropertyChanged(ItemPropertyChangedEventArgs e)
        {
            ItemPropertyChanged?.Invoke(this, e);
        }

        protected void OnItemPropertyChanged(int index, PropertyChangedEventArgs e)
        {
            OnItemPropertyChanged(new ItemPropertyChangedEventArgs(index, e));
        }

        protected override void ClearItems()
        {
            foreach (T item in Items)
                item.PropertyChanged -= ChildPropertyChanged;

            base.ClearItems();
        }

        private void ObserveAll()
        {
            foreach (T item in Items)
                item.PropertyChanged += ChildPropertyChanged;
        }

        private void ChildPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            T typedSender = (T)sender;
            int i = Items.IndexOf(typedSender);

            if (i < 0)
                throw new ArgumentException("Received property notification from item not in collection");

            OnItemPropertyChanged(i, e);
        }
    }

    /// <summary>
    /// Provides data for the <see cref="FullyObservableCollection{T}.ItemPropertyChanged"/> event.
    /// </summary>
    public class ItemPropertyChangedEventArgs : PropertyChangedEventArgs
    {
        /// <summary>
        /// Gets the index in the collection for which the property change has occurred.
        /// </summary>
        /// <value>
        /// Index in parent collection.
        /// </value>
        public int CollectionIndex { get; }

        /// <summary>
        /// Initializes a new instance of the <see cref="ItemPropertyChangedEventArgs"/> class.
        /// </summary>
        /// <param name="index">The index in the collection of changed item.</param>
        /// <param name="name">The name of the property that changed.</param>
        public ItemPropertyChangedEventArgs(int index, string name) : base(name)
        {
            CollectionIndex = index;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="ItemPropertyChangedEventArgs"/> class.
        /// </summary>
        /// <param name="index">The index.</param>
        /// <param name="args">The <see cref="PropertyChangedEventArgs"/> instance containing the event data.</param>
        public ItemPropertyChangedEventArgs(int index, PropertyChangedEventArgs args) : this(index, args.PropertyName)
        { }
    }
}

NUnit Tests

So you can check changes you might make (and see what I tested in the first place!), I've also included my NUnit test class. Obviously, the following code is not necessary just to use FullyObservableCollection<T> in your project.

NB The test class uses BindableBase from PRISM to implement INotifyPropertyChanged. There is no dependency on PRISM from the main code.

using NUnit.Framework;
using Utilities;
using Microsoft.Practices.Prism.Mvvm;
using System.Collections.Specialized;
using System.Collections.Generic;

namespace Test_Utilities
{
    [TestFixture]
    public class Test_FullyObservableCollection : AssertionHelper
    {
        public class NotifyingTestClass : BindableBase
        {
            public int Id
            {
                get { return _Id; }
                set { SetProperty(ref _Id, value); }
            }
            private int _Id;

            public string Name
            {
                get { return _Name; }
                set { SetProperty(ref _Name, value); }
            }
            private string _Name;

        }

        FullyObservableCollection<NotifyingTestClass> TestCollection;
        NotifyingTestClass Fred;
        NotifyingTestClass Betty;
        List<NotifyCollectionChangedEventArgs> CollectionEventList;
        List<ItemPropertyChangedEventArgs> ItemEventList;

        [SetUp]
        public void Init()
        {
            Fred = new NotifyingTestClass() { Id = 1, Name = "Fred" };
            Betty = new NotifyingTestClass() { Id = 4, Name = "Betty" };

            TestCollection = new FullyObservableCollection<NotifyingTestClass>()
                {
                    Fred,
                    new NotifyingTestClass() {Id = 2, Name = "Barney" },
                    new NotifyingTestClass() {Id = 3, Name = "Wilma" }
                };

            CollectionEventList = new List<NotifyCollectionChangedEventArgs>();
            ItemEventList = new List<ItemPropertyChangedEventArgs>();
            TestCollection.CollectionChanged += (o, e) => CollectionEventList.Add(e);
            TestCollection.ItemPropertyChanged += (o, e) => ItemEventList.Add(e);
        }

        // Change existing member property: just ItemPropertyChanged(IPC) should fire
        [Test]
        public void DetectMemberPropertyChange()
        {
            TestCollection[0].Id = 7;

            Expect(CollectionEventList.Count, Is.EqualTo(0));

            Expect(ItemEventList.Count, Is.EqualTo(1), "IPC count");
            Expect(ItemEventList[0].PropertyName, Is.EqualTo(nameof(Fred.Id)), "Field Name");
            Expect(ItemEventList[0].CollectionIndex, Is.EqualTo(0), "Collection Index");
        }


        // Add new member, change property: CollectionPropertyChanged (CPC) and IPC should fire
        [Test]
        public void DetectNewMemberPropertyChange()
        {
            TestCollection.Add(Betty);

            Expect(TestCollection.Count, Is.EqualTo(4));
            Expect(TestCollection[3].Name, Is.EqualTo("Betty"));

            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count");

            Expect(CollectionEventList.Count, Is.EqualTo(1), "Collection Event count");
            Expect(CollectionEventList[0].Action, Is.EqualTo(NotifyCollectionChangedAction.Add), "Action (add)");
            Expect(CollectionEventList[0].OldItems, Is.Null, "OldItems count");
            Expect(CollectionEventList[0].NewItems.Count, Is.EqualTo(1), "NewItems count");
            Expect(CollectionEventList[0].NewItems[0], Is.EqualTo(Betty), "NewItems[0] dereference");

            CollectionEventList.Clear();      // Empty for next operation
            ItemEventList.Clear();

            TestCollection[3].Id = 7;
            Expect(CollectionEventList.Count, Is.EqualTo(0), "Collection Event count");

            Expect(ItemEventList.Count, Is.EqualTo(1), "Item Event count");
            Expect(TestCollection[ItemEventList[0].CollectionIndex], Is.EqualTo(Betty), "Collection Index dereference");
        }


        // Remove member, change property: CPC should fire for removel, neither CPC nor IPC should fire for change
        [Test]
        public void CeaseListentingWhenMemberRemoved()
        {
            TestCollection.Remove(Fred);

            Expect(TestCollection.Count, Is.EqualTo(2));
            Expect(TestCollection.IndexOf(Fred), Is.Negative);

            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count (pre change)");

            Expect(CollectionEventList.Count, Is.EqualTo(1), "Collection Event count (pre change)");
            Expect(CollectionEventList[0].Action, Is.EqualTo(NotifyCollectionChangedAction.Remove), "Action (remove)");
            Expect(CollectionEventList[0].OldItems.Count, Is.EqualTo(1), "OldItems count");
            Expect(CollectionEventList[0].NewItems, Is.Null, "NewItems count");
            Expect(CollectionEventList[0].OldItems[0], Is.EqualTo(Fred), "OldItems[0] dereference");

            CollectionEventList.Clear();      // Empty for next operation
            ItemEventList.Clear();

            Fred.Id = 7;
            Expect(CollectionEventList.Count, Is.EqualTo(0), "Collection Event count (post change)");
            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count (post change)");
        }


        // Move member in list, change property: CPC should fire for move, IPC should fire for change
        [Test]
        public void MoveMember()
        {
            TestCollection.Move(0, 1);

            Expect(TestCollection.Count, Is.EqualTo(3));
            Expect(TestCollection.IndexOf(Fred), Is.GreaterThan(0));

            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count (pre change)");

            Expect(CollectionEventList.Count, Is.EqualTo(1), "Collection Event count (pre change)");
            Expect(CollectionEventList[0].Action, Is.EqualTo(NotifyCollectionChangedAction.Move), "Action (move)");
            Expect(CollectionEventList[0].OldItems.Count, Is.EqualTo(1), "OldItems count");
            Expect(CollectionEventList[0].NewItems.Count, Is.EqualTo(1), "NewItems count");
            Expect(CollectionEventList[0].OldItems[0], Is.EqualTo(Fred), "OldItems[0] dereference");
            Expect(CollectionEventList[0].NewItems[0], Is.EqualTo(Fred), "NewItems[0] dereference");

            CollectionEventList.Clear();      // Empty for next operation
            ItemEventList.Clear();

            Fred.Id = 7;
            Expect(CollectionEventList.Count, Is.EqualTo(0), "Collection Event count (post change)");

            Expect(ItemEventList.Count, Is.EqualTo(1), "Item Event count (post change)");
            Expect(TestCollection[ItemEventList[0].CollectionIndex], Is.EqualTo(Fred), "Collection Index dereference");
        }


        // Clear list, chnage property: only CPC should fire for clear and neither for property change
        [Test]
        public void ClearList()
        {
            TestCollection.Clear();

            Expect(TestCollection.Count, Is.EqualTo(0));

            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count (pre change)");

            Expect(CollectionEventList.Count, Is.EqualTo(1), "Collection Event count (pre change)");
            Expect(CollectionEventList[0].Action, Is.EqualTo(NotifyCollectionChangedAction.Reset), "Action (reset)");
            Expect(CollectionEventList[0].OldItems, Is.Null, "OldItems count");
            Expect(CollectionEventList[0].NewItems, Is.Null, "NewItems count");

            CollectionEventList.Clear();      // Empty for next operation
            ItemEventList.Clear();

            Fred.Id = 7;
            Expect(CollectionEventList.Count, Is.EqualTo(0), "Collection Event count (post change)");
            Expect(ItemEventList.Count, Is.EqualTo(0), "Item Event count (post change)");
        }
    }
}

Delete from a table based on date

or an ORACLE version:

delete
  from table_name
 where trunc(table_name.date) > to_date('01/01/2009','mm/dd/yyyy') 

c++ array - expression must have a constant value

one could also use a fixed lengths vector and access it with indexing

int Lcs(string a, string b) 
{
    int x = a.size() + 1;
    int y = b.size() + 1;

    vector<vector<int>> L(x, vector<int>(y));

    for (int i = 1; i < x; i++)
    {
        for (int j = 1; j < y; j++)
        {
            L[i][j] = a[i - 1] == b[j - 1] ?
                L[i - 1][j - 1] + 1 :
                max(L[i - 1][j], L[i][j - 1]);
        }
    }

    return L[a.size()][b.size()];
}

Setting default checkbox value in Objective-C?

Documentation on UISwitch says:

[mySwitch setOn:NO]; 

In Interface Builder, select your switch and in the Attributes inspector you'll find State which can be set to on or off.

Convert JSON string to dict using Python

json.loads()

import json

d = json.loads(j)
print d['glossary']['title']

How can I create a unique constraint on my column (SQL Server 2008 R2)?

One thing not clearly covered is that microsoft sql is creating in the background an unique index for the added constraint

create table Customer ( id int primary key identity (1,1) , name nvarchar(128) ) 

--Commands completed successfully.

sp_help Customer

---> index
--index_name    index_description   index_keys
--PK__Customer__3213E83FCC4A1DFA    clustered, unique, primary key located on PRIMARY   id

---> constraint
--constraint_type   constraint_name delete_action   update_action   status_enabled  status_for_replication  constraint_keys
--PRIMARY KEY (clustered)   PK__Customer__3213E83FCC4A1DFA  (n/a)   (n/a)   (n/a)   (n/a)   id


---- now adding the unique constraint

ALTER TABLE Customer ADD CONSTRAINT U_Name UNIQUE(Name)

-- Commands completed successfully.

sp_help Customer

---> index
---index_name   index_description   index_keys
---PK__Customer__3213E83FCC4A1DFA   clustered, unique, primary key located on PRIMARY   id
---U_Name   nonclustered, unique, unique key located on PRIMARY name

---> constraint
---constraint_type  constraint_name delete_action   update_action   status_enabled  status_for_replication  constraint_keys
---PRIMARY KEY (clustered)  PK__Customer__3213E83FCC4A1DFA  (n/a)   (n/a)   (n/a)   (n/a)   id
---UNIQUE (non-clustered)   U_Name  (n/a)   (n/a)   (n/a)   (n/a)   name

as you can see , there is a new constraint and a new index U_Name

How to retrieve absolute path given relative

In case of find, it's probably easiest to just give the absolute path for it to search in, e.g.:

find /etc
find `pwd`/subdir_of_current_dir/ -type f

How to iterate over a JavaScript object?

If you have a simple object you can iterate through it using the following code:

_x000D_
_x000D_
let myObj = {
  abc: '...',
  bca: '...',
  zzz: '...',
  xxx: '...',
  ccc: '...',
  // ...
};

let objKeys = Object.keys(myObj);

//Now we can use objKeys to iterate over myObj

for (item of objKeys) {
  //this will print out the keys
  console.log('key:', item);
  
  //this will print out the values 
  console.log('value:', myObj[item]);
}
_x000D_
_x000D_
_x000D_

If you have a nested object you can iterate through it using the following code:

_x000D_
_x000D_
let b = {
  one: {
    a: 1,
    b: 2,
    c: 3
  },
  two: {
    a: 4,
    b: 5,
    c: 6
  },
  three: {
    a: 7,
    b: 8,
    c: 9
  }
};

let myKeys = Object.keys(b);

for (item of myKeys) {
  //print the key
  console.log('Key', item)
  
  //print the value (which will be another object)
  console.log('Value', b[item])
  
  //print the nested value
  console.log('Nested value', b[item]['a'])
}
_x000D_
_x000D_
_x000D_

If you have array of objects you can iterate through it using the following code:

_x000D_
_x000D_
let c = [
{
  a: 1,
  b: 2
},
{
  a: 3,
  b: 4
}
];

for(item of c){
//print the whole object individually 
console.log('object', item);

//print the value inside the object
console.log('value', item['a']);
}
_x000D_
_x000D_
_x000D_

How can I search an array in VB.NET?

This would do the trick, returning the values at indeces 0, 2 and 3.

Array.FindAll(arr, Function(s) s.ToLower().StartsWith("ra"))

Restore the mysql database from .frm files

Yes! It is possible

Long approach but you can get all the data's using just .frm files. Of course you need other files in the mysql/data directory.

My Problem

One day my harddisk crashed and got the booting blue screen error. I try connecting with multiple machine and it didn't work. Since it is a booting error i was concered about the files. and i tryed with the secondary harddisk and try to recover the folders and files. I also backed up the full xampp folder c:/xampp just in case, Because I had no back of the recent databases i got really worried how to retrieve the database. we have lot of clients project management and personal doc in the database.

None of the method listed on the stackoverflow comment works, at-least for me. It took me 2 full days googling for the answer to get the data's from the .frm files. Came across multiple approaches from many people but everything was frustration and getting some error or another when implementing. If most of them get it working (based on their comment) then what am i missing.

Because i was so desperate I even reinstall windows which result in loosing all my softwares and tried again. But still the same error

THANKS to Dustin Davis

i found the solution in his blog and i managed to get it working exactly the same way he did. Let me give the credit to this guy, Dustin Davis (https://dustindavis.me/restoring-mysql-innodb-files-on-windows/). You could jump from here to his blog and try his method, pretty clear and easy to follow.

But there are something i discovered when trying his approach which he hasn't explained in his blog and i will try my best to explain how i did and what you need to look for.

Follow this exactly

IMPORTANT: Make sure you to install the same version of XAMPP. You cannot copy paste from older XAMPP to a new version. This will result in __config or __tracking errors.

How to check your XAMPP version

  1. Go to your xampp folder (your backed up xampp).
  2. Open the readme_en.txt file. which is in the root directory of the xampp.
  3. You should see the version on top. ###### ApacheFriends XAMPP Version X.X.XX ######

Files require to restore

xampp(old folder)/mysql/data/

ibdata1
ib_logfile0
ib_logfile1
<databasename>/*.frm
<databasename>/*.ibd

Step 1

  1. After installed the same version of xampp.
  2. Do not start the apache or myql

Step 2

  • Go to the mysql/data folder and replace the ibdata1, ib_logfile0, and ib_logfile1
  • Now copy paste your database folder from your old xampp backup to the newly installed xampp folder c:/xampp/mysql/data/ that contain .frm and .ibd files, If you are not sure try with one database.

Step 3

  • Go to c:/xampp/mysql/bin and look for my.cn.
  • Open the my.cn file and look for #skip-innodb and under that look for the line that says innodb_log_file_size=5M change it to 170M. innodb_log_file_size=170M. This is your log file size and if you are not sure just set it to 170

Step 4

  • Now open the file mysql_start.bat (Windows Batch file) that is in the c:/xampp/ directory.
  • Add –innodb_force_recovery=6 after the ... --console

    ....
    
    mysql\bin\mysqld --defaults-file=mysql\bin\my.ini --standalone --console
    –innodb_force_recovery=6
    if errorlevel 1 goto error
    goto finish
    

Step 5

  • Now Start your Apache and Mysql.
  • Go to your phpmyadmin and check for your database and its tables. if you do not get any errors you are on the right track.
  • Stop the Apache and Mysql and copy paste the rest of the databases.

Writing a dict to txt file and reading it back?

Your code is almost right! You are right, you are just missing one step. When you read in the file, you are reading it as a string; but you want to turn the string back into a dictionary.

The error message you saw was because self.whip was a string, not a dictionary.

I first wrote that you could just feed the string into dict() but that doesn't work! You need to do something else.

Example

Here is the simplest way: feed the string into eval(). Like so:

def reading(self):
    s = open('deed.txt', 'r').read()
    self.whip = eval(s)

You can do it in one line, but I think it looks messy this way:

def reading(self):
    self.whip = eval(open('deed.txt', 'r').read())

But eval() is sometimes not recommended. The problem is that eval() will evaluate any string, and if someone tricked you into running a really tricky string, something bad might happen. In this case, you are just running eval() on your own file, so it should be okay.

But because eval() is useful, someone made an alternative to it that is safer. This is called literal_eval and you get it from a Python module called ast.

import ast

def reading(self):
    s = open('deed.txt', 'r').read()
    self.whip = ast.literal_eval(s)

ast.literal_eval() will only evaluate strings that turn into the basic Python types, so there is no way that a tricky string can do something bad on your computer.

EDIT

Actually, best practice in Python is to use a with statement to make sure the file gets properly closed. Rewriting the above to use a with statement:

import ast

def reading(self):
    with open('deed.txt', 'r') as f:
        s = f.read()
        self.whip = ast.literal_eval(s)

In the most popular Python, known as "CPython", you usually don't need the with statement as the built-in "garbage collection" features will figure out that you are done with the file and will close it for you. But other Python implementations, like "Jython" (Python for the Java VM) or "PyPy" (a really cool experimental system with just-in-time code optimization) might not figure out to close the file for you. It's good to get in the habit of using with, and I think it makes the code pretty easy to understand.

Issue with background color and Google Chrome

I would try what Logan and 1mdm suggested, tho tweak the CSS, but I would really wait for a new Chrome version to come out with fixed bugs, before growing white hair.

IMHO the current Chrome version is still alpha version and was released so that it can spread while it is in development. I personally had issues with table widths, my code worked fine in EVERY browser but could not make it work in Chrome.

How to use a calculated column to calculate another column in the same view

In Sql Server

You can do this using cross apply

Select
  ColumnA,
  ColumnB,
  c.calccolumn1 As calccolumn1,
  c.calccolumn1 / ColumnC As calccolumn2
from t42
cross apply (select (ColumnA + ColumnB) as calccolumn1) as c

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

You need to start by understanding that the target of a symlink is a pathname. And it can be absolute or relative to the directory which contains the symlink

Assuming you have foo.conf in sites-available

Try

cd sites-enabled
sudo ln -s ../sites-available/foo.conf .
ls -l

Now you will have a symlink in sites-enabled called foo.conf which has a target ../sites-available/foo.conf

Just to be clear, the normal configuration for Apache is that the config files for potential sites live in sites-available and the symlinks for the enabled sites live in sites-enabled, pointing at targets in sites-available. That doesn't quite seem to be the case the way you describe your setup, but that is not your primary problem.

If you want a symlink to ALWAYS point at the same file, regardless of the where the symlink is located, then the target should be the full path.

ln -s /etc/apache2/sites-available/foo.conf mysimlink-whatever.conf

Here is (line 1 of) the output of my ls -l /etc/apache2/sites-enabled:

lrwxrwxrwx 1 root root  26 Jun 24 21:06 000-default -> ../sites-available/default

See how the target of the symlink is relative to the directory that contains the symlink (it starts with ".." meaning go up one directory).

Hardlinks are totally different because the target of a hardlink is not a directory entry but a filing system Inode.

How to scp in Python?

Hmmm, perhaps another option would be to use something like sshfs (there an sshfs for Mac too). Once your router is mounted you can just copy the files outright. I'm not sure if that works for your particular application but it's a nice solution to keep handy.

How to stop EditText from gaining focus at Activity startup in Android

add below line in Manifest file where you have mentioned your activity

android:windowSoftInputMode="stateAlwaysHidden"

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

It also might be that you haven't declared you Dependency Injected service, as a provider in the component that you injected it to. That was my case :)

jQuery: Get selected element tag name

This is yet another way:

$('selector')[0].tagName

Create a list with initial capacity in Python

Python lists have no built-in pre-allocation. If you really need to make a list, and need to avoid the overhead of appending (and you should verify that you do), you can do this:

l = [None] * 1000 # Make a list of 1000 None's
for i in xrange(1000):
    # baz
    l[i] = bar
    # qux

Perhaps you could avoid the list by using a generator instead:

def my_things():
    while foo:
        #baz
        yield bar
        #qux

for thing in my_things():
    # do something with thing

This way, the list isn't every stored all in memory at all, merely generated as needed.

How can I manually set an Angular form field as invalid?

Adding to Julia Passynkova's answer

To set validation error in component:

formData.form.controls['email'].setErrors({'incorrect': true});

To unset validation error in component:

formData.form.controls['email'].setErrors(null);

Be careful with unsetting the errors using null as this will overwrite all errors. If you want to keep some around you may have to check for the existence of other errors first:

if (isIncorrectOnlyError){
   formData.form.controls['email'].setErrors(null);
}

Run / Open VSCode from Mac Terminal

For Mac users:

One thing that made the accepted answer not work for me is that I didn't drag the vs code package into the applications folder

So you need to drag it to the applications folder then you run the command inside vs code (shown below) as per the official document

  • Launch VS Code.
  • Open the Command Palette (??P) and type 'shell command' to find the Shell Command: Install 'code' command in PATH command.

Difference between Big-O and Little-O Notation

I find that when I can't conceptually grasp something, thinking about why one would use X is helpful to understand X. (Not to say you haven't tried that, I'm just setting the stage.)

[stuff you know]A common way to classify algorithms is by runtime, and by citing the big-Oh complexity of an algorithm, you can get a pretty good estimation of which one is "better" -- whichever has the "smallest" function in the O! Even in the real world, O(N) is "better" than O(N²), barring silly things like super-massive constants and the like.[/stuff you know]

Let's say there's some algorithm that runs in O(N). Pretty good, huh? But let's say you (you brilliant person, you) come up with an algorithm that runs in O(NloglogloglogN). YAY! Its faster! But you'd feel silly writing that over and over again when you're writing your thesis. So you write it once, and you can say "In this paper, I have proven that algorithm X, previously computable in time O(N), is in fact computable in o(n)."

Thus, everyone knows that your algorithm is faster --- by how much is unclear, but they know its faster. Theoretically. :)

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

In addition to the above mentioned answers: I wanted to start a job with a simple parameter passed to a second pipeline and found the answer on http://web.archive.org/web/20160209062101/https://dzone.com/refcardz/continuous-delivery-with-jenkins-workflow

So i used:

stage ('Starting ART job') {
    build job: 'RunArtInTest', parameters: [[$class: 'StringParameterValue', name: 'systemname', value: systemname]]
}

What does "Content-type: application/json; charset=utf-8" really mean?

Note that IETF RFC4627 has been superseded by IETF RFC7158. In section [8.1] it retracts the text cited by @Drew earlier by saying:

Implementations MUST NOT add a byte order mark to the beginning of a JSON text.

SQL query for a carriage return in a string and ultimately removing carriage return

You can also use regular expressions:

SELECT * FROM Parameters WHERE Name REGEXP '\n';

sql use statement with variable

try this:

DECLARE @Query         varchar(1000)
DECLARE @DatabaseName  varchar(500)

SET @DatabaseName='xyz'
SET @Query='SELECT * FROM Server.'+@DatabaseName+'.Owner.Table1'
EXEC (@Query)

SET @DatabaseName='abc'
SET @Query='SELECT * FROM Server.'+@DatabaseName+'.Owner.Table2'
EXEC (@Query)

Append value to empty vector in R?

Appending to an object in a for loop causes the entire object to be copied on every iteration, which causes a lot of people to say "R is slow", or "R loops should be avoided".

As BrodieG mentioned in the comments: it is much better to pre-allocate a vector of the desired length, then set the element values in the loop.

Here are several ways to append values to a vector. All of them are discouraged.

Appending to a vector in a loop

# one way
for (i in 1:length(values))
  vector[i] <- values[i]
# another way
for (i in 1:length(values))
  vector <- c(vector, values[i])
# yet another way?!?
for (v in values)
  vector <- c(vector, v)
# ... more ways

help("append") would have answered your question and saved the time it took you to write this question (but would have caused you to develop bad habits). ;-)

Note that vector <- c() isn't an empty vector; it's NULL. If you want an empty character vector, use vector <- character().

Pre-allocate the vector before looping

If you absolutely must use a for loop, you should pre-allocate the entire vector before the loop. This will be much faster than appending for larger vectors.

set.seed(21)
values <- sample(letters, 1e4, TRUE)
vector <- character(0)
# slow
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
#   user  system elapsed 
#  0.340   0.000   0.343 
vector <- character(length(values))
# fast(er)
system.time( for (i in 1:length(values)) vector[i] <- values[i] )
#   user  system elapsed 
#  0.024   0.000   0.023 

Add button to navigationbar programmatically

How to add an add button to the navbar in swift:

self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "onAdd:")

onAdd:

func onAdd(sender: AnyObject) {
}

invalid use of non-static member function

The simplest fix is to make the comparator function be static:

static int comparator (const Bar & first, const Bar & second);
^^^^^^

When invoking it in Count, its name will be Foo::comparator.

The way you have it now, it does not make sense to be a non-static member function because it does not use any member variables of Foo.

Another option is to make it a non-member function, especially if it makes sense that this comparator might be used by other code besides just Foo.

Select Pandas rows based on list index

ind_list = [1, 3]
df.ix[ind_list]

should do the trick! When I index with data frames I always use the .ix() method. Its so much easier and more flexible...

UPDATE This is no longer the accepted method for indexing. The ix method is deprecated. Use .iloc for integer based indexing and .loc for label based indexing.

String concatenation of two pandas columns

df.astype(str).apply(lambda x: ' is '.join(x), axis=1)

0    1 is a
1    2 is b
2    3 is c
dtype: object

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

I had a co-worker with this exact problem last week. He fixed it by installing the x64 version of Eclipse and the x64 JDK.

Edit: he reused his old workspace after installing the necessary plugins, so that should not be much of an issue

What is the difference between declarations, providers, and import in NgModule?

  1. declarations: This property tells about the Components, Directives and Pipes that belong to this module.
  2. exports: The subset of declarations that should be visible and usable in the component templates of other NgModules.
  3. imports: Other modules whose exported classes are needed by component templates declared in this NgModule.
  4. providers: Creators of services that this NgModule contributes to the global collection of services; they become accessible in all parts of the app. (You can also specify providers at the component level, which is often preferred.)
  5. bootstrap: The main application view, called the root component, which hosts all other app views. Only the root NgModule should set the bootstrap property.

How to get current page URL in MVC 3

For me the issue was when I tried to access HTTPContext in the Controller's constructor while HTTPContext is not ready yet. When moved inside Index method it worked:

var uri = new Uri(Request.Url.AbsoluteUri);
url = uri.Scheme + "://" + uri.Host + "/";enter code here

How can I escape latex code received through user input?

Python’s raw strings are just a way to tell the Python interpreter that it should interpret backslashes as literal slashes. If you read strings entered by the user, they are already past the point where they could have been raw. Also, user input is most likely read in literally, i.e. “raw”.

This means the interpreting happens somewhere else. But if you know that it happens, why not escape the backslashes for whatever is interpreting it?

s = s.replace("\\", "\\\\")

(Note that you can't do r"\" as “a raw string cannot end in a single backslash”, but I could have used r"\\" as well for the second argument.)

If that doesn’t work, your user input is for some arcane reason interpreting the backslashes, so you’ll need a way to tell it to stop that.

How to explicitly obtain post data in Spring MVC?

If you are using one of the built-in controller instances, then one of the parameters to your controller method will be the Request object. You can call request.getParameter("value1") to get the POST (or PUT) data value.

If you are using Spring MVC annotations, you can add an annotated parameter to your method's parameters:

@RequestMapping(value = "/someUrl")
public String someMethod(@RequestParam("value1") String valueOne) {
 //do stuff with valueOne variable here
}

How do I get the IP address into a batch-file variable?

The following was all done in cygwin on a Windows XP box.

This will get your IP address. Note that there are backquotes around the hostname command, not single quotes.

ping -n 1 `hostname` | grep "Reply from " | cut -f 3 -d " " | cut -f 1 -d ":"

This will get your subnet.

ping -n 1 `hostname` | grep "Reply from " | cut -f 3 -d " " | cut -f "1 2 3" -d "."

The following will list all hosts on your local network (put it into a script called "netmap"). I had taken the subnet line above and put it into an executable called "getsubnet", which I then called from the following script.

MINADDR=0
MAXADDR=255
SUBNET=`getsubnet`

hostcnt=0

echo Pinging all addresses in ${SUBNET}.${MINADDR}-${MAXADDR}

for i in `seq $MINADDR $MAXADDR`; do
addr=${SUBNET}.$i
ping -n 1 -w 0 $addr > /dev/null

if [ $? -ne 1 ]    
then    
echo $addr UP    
hostcnt=$((hostcnt+1))    
fi

done

echo Found $hostcnt hosts on subnet ${SUBNET}.${MINADDR}-${MAXADDR}

How to set HTTP headers (for cache-control)?

OWASP recommends the following,

Whenever possible ensure the cache-control HTTP header is set with no-cache, no-store, must-revalidate, private; and that the pragma HTTP header is set with no-cache.

<IfModule mod_headers.c>
    Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
    Header set Pragma "no-cache"
</IfModule>

What is the difference between a "line feed" and a "carriage return"?

A line feed means moving one line forward. The code is \n.
A carriage return means moving the cursor to the beginning of the line. The code is \r.

Windows editors often still use the combination of both as \r\n in text files. Unix uses mostly only the \n.

The separation comes from typewriter times, when you turned the wheel to move the paper to change the line and moved the carriage to restart typing on the beginning of a line. This was two steps.

JavaScript string with new line - but not using \n

The query string that I used to to escape the new line character in JS : LOAD DATA LOCAL INFILE 'Data.csv' INTO TABLE DEMO FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 ROWS;

This involves new ES6 syntax - Template Literals `` and I tried changing '\n' to '\r\n' and worked perfectly in my case.

PS: This example is my query to upload CSV data into mysql DB.

How to check if a String contains any of some strings

var values = new [] {"abc", "def", "ghj"};
var str = "abcedasdkljre";
values.Any(str.Contains);

How to check if image exists with given url?

if it doesnt exist load default image or handle error

$('img[id$=imgurl]').load(imgurl, function(response, status, xhr) {
    if (status == "error") 
        $(this).attr('src', 'images/DEFAULT.JPG');
    else
        $(this).attr('src', imgurl);
    });

How to get response body using HttpURLConnection, when code other than 2xx is returned?

Wrong method was used for errors, here is the working code:

BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}

How to open a link in new tab using angular?

just use the full url as href like this:

<a href="https://www.example.com/" target="_blank">page link</a>

How to add fixed button to the bottom right of page

This will be helpful for the right bottom rounded button

HTML :

      <a class="fixedButton" href>
         <div class="roundedFixedBtn"><i class="fa fa-phone"></i></div>
      </a>
    

CSS:

       .fixedButton{
            position: fixed;
            bottom: 0px;
            right: 0px; 
            padding: 20px;
        }
        .roundedFixedBtn{
          height: 60px;
          line-height: 80px;  
          width: 60px;  
          font-size: 2em;
          font-weight: bold;
          border-radius: 50%;
          background-color: #4CAF50;
          color: white;
          text-align: center;
          cursor: pointer;
        }
    

Here is jsfiddle link http://jsfiddle.net/vpthcsx8/11/

file_get_contents() how to fix error "Failed to open stream", "No such file"

Why don't you use cURL ?

$yourkey="your api key";
$url="https://prod.api.pvp.net/api/lol/euw/v1.1/game/by-summoner/20986461/recent?api_key=$yourkey";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$auth = curl_exec($curl);
if($auth)
{
$json = json_decode($auth); 
print_r($json);
}
}

Set default option in mat-select

Read this if you are populating your mat-select asyncronously via an http request.

If you are using a service to make an api call to return the mat-select options values, you must set the 'selected value' on your form control as part of the 'complete' section of your service api call subscribe().

For example:

  this.customerService.getCustomers().subscribe(
  customers => this.customers = customers ,
  error => this.errorMessage = error as any,
  () => this.customerSelectControl.setValue(this.mySelectedValue));

convert a char* to std::string

Not sure why no one besides Erik mentioned this, but according to this page, the assignment operator works just fine. No need to use a constructor, .assign(), or .append().

std::string mystring;
mystring = "This is a test!";   // Assign C string to std:string directly
std::cout << mystring << '\n';

How set background drawable programmatically in Android

If your backgrounds are in the drawable folder right now try moving the images from drawable to drawable-nodpi folder in your project. This worked for me, seems that else the images are rescaled by them self..

How to export SQL Server 2005 query to CSV

You can use following Node.js module to do it with a breeze:

https://www.npmjs.com/package/mssql-to-csv

How to add dll in c# project

Have you added the dll into your project references list? If not right click on the project "References" folder and selecet "Add Reference" then use browse to locate your science.dll, select it and click ok.

edit

I can't see the image of your VS instance that some people are referring to and I note that you now say that it works in Net4.0 and VS2010.

VS2008 projects support NET 3.5 by default. I expect that is the problem as your DLL may be NET 4.0 compliant but not NET 3.5.

Convert timestamp to readable date/time PHP

echo 'Le '.date('d/m/Y', 1234567890).' &agrave; '.date('H:i:s', 1234567890);

Accurate way to measure execution times of php scripts

You can use the microtime function for this. From the documentation:

microtime — Return current Unix timestamp with microseconds


If get_as_float is set to TRUE, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.

Example usage:

$start = microtime(true);
while (...) {

}
$time_elapsed_secs = microtime(true) - $start;

Python - difference between two strings

You can look into the regex module (the fuzzy section). I don't know if you can get the actual differences, but at least you can specify allowed number of different types of changes like insert, delete, and substitutions:

import regex
sequence = 'afrykanerskojezyczny'
queries = [ 'afrykanerskojezycznym', 'afrykanerskojezyczni', 
            'nieafrykanerskojezyczni' ]
for q in queries:
    m = regex.search(r'(%s){e<=2}'%q, sequence)
    print 'match' if m else 'nomatch'

Can you style html form buttons with css?

Yeah, it's pretty simple:

input[type="submit"]{
  background: #fff;
  border: 1px solid #000;
  text-shadow: 1px 1px 1px #000;
}

I recommend giving it an ID or a class so that you can target it more easily.

Installing Python library from WHL file

From How do I install a Python package with a .whl file? [sic], How do I install a Python package USING a .whl file ?

For all Windows platforms:

1) Download the .WHL package install file.

2) Make Sure path [C:\Progra~1\Python27\Scripts] is in the system PATH string. This is for using both [pip.exe] and [easy-install.exe].

3) Make sure the latest version of pip.EXE is now installed. At this time of posting:

pip.EXE --version

  pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

4) Run pip.EXE in an Admin command shell.

 - Open an Admin privileged command shell.

 > easy_install.EXE --upgrade  pip

 - Check the pip.EXE version:
 > pip.EXE --version

 pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

 > pip.EXE install --use-wheel --no-index 
     --find-links="X:\path to wheel file\DownloadedWheelFile.whl"

Be sure to double-quote paths or path\filenames with embedded spaces in them ! Alternatively, use the MSW 'short' paths and filenames.

Error: " 'dict' object has no attribute 'iteritems' "

In Python2, dictionary.iteritems() is more efficient than dictionary.items() so in Python3, the functionality of dictionary.iteritems() has been migrated to dictionary.items() and iteritems() is removed. So you are getting this error.

Use dict.items() in Python3 which is same as dict.iteritems() of Python2.

ASP.NET MVC ActionLink and post method

My Solution to this issue is a fairly simple one. I have a page that does a customer search one by the whole email and the other by a partial, the partial pulls and displays a list the list has an action link that points to a actionresult called GetByID and passes in the id

the GetByID pulls the data for the selected customer then returns

return View("Index", model); 

which is the post method

How to use the switch statement in R functions?

those various ways of switch ...

# by index
switch(1, "one", "two")
## [1] "one"


# by index with complex expressions
switch(2, {"one"}, {"two"})
## [1] "two"


# by index with complex named expression
switch(1, foo={"one"}, bar={"two"})
## [1] "one"


# by name with complex named expression
switch("bar", foo={"one"}, bar={"two"})
## [1] "two"

Returning a value even if no result

You can use COALESCE

SELECT COALESCE(SUM(column),0)
FROM   table

Why use String.Format?

I can see a number of reasons:

Readability

string s = string.Format("Hey, {0} it is the {1}st day of {2}.  I feel {3}!", _name, _day, _month, _feeling);

vs:

string s = "Hey," + _name + " it is the " + _day + "st day of " + _month + ".  I feel " + feeling + "!";

Format Specifiers (and this includes the fact you can write custom formatters)

string s = string.Format("Invoice number: {0:0000}", _invoiceNum);

vs:

string s = "Invoice Number = " + ("0000" + _invoiceNum).Substr(..... /*can't even be bothered to type it*/)

String Template Persistence

What if I want to store string templates in the database? With string formatting:

_id         _translation
  1         Welcome {0} to {1}.  Today is {2}.
  2         You have {0} products in your basket.
  3         Thank-you for your order.  Your {0} will arrive in {1} working days.

vs:

_id         _translation
  1         Welcome
  2         to
  3         .  Today is
  4         . 
  5         You have
  6         products in your basket.
  7         Someone
  8         just shoot
  9         the developer.

keycloak Invalid parameter: redirect_uri

even I faced the same issue. I rectified it by going to the particular client under the realm respectively therein redirect URL add * after your complete URL.

THE PROBLEM WILL BE SOLVED

Example: redirect URI: http:localhost:3000/myapp/generator/*

Container is running beyond memory limits

You should also properly configure the maximum memory allocations for MapReduce. From this HortonWorks tutorial:

[...]

Each machine in our cluster has 48 GB of RAM. Some of this RAM should be >reserved for Operating System usage. On each node, we’ll assign 40 GB RAM for >YARN to use and keep 8 GB for the Operating System

For our example cluster, we have the minimum RAM for a Container (yarn.scheduler.minimum-allocation-mb) = 2 GB. We’ll thus assign 4 GB for Map task Containers, and 8 GB for Reduce tasks Containers.

In mapred-site.xml:

mapreduce.map.memory.mb: 4096

mapreduce.reduce.memory.mb: 8192

Each Container will run JVMs for the Map and Reduce tasks. The JVM heap size should be set to lower than the Map and Reduce memory defined above, so that they are within the bounds of the Container memory allocated by YARN.

In mapred-site.xml:

mapreduce.map.java.opts: -Xmx3072m

mapreduce.reduce.java.opts: -Xmx6144m

The above settings configure the upper limit of the physical RAM that Map and Reduce tasks will use.

To sum it up:

  1. In YARN, you should use the mapreduce configs, not the mapred ones. EDIT: This comment is not applicable anymore now that you've edited your question.
  2. What you are configuring is actually how much you want to request, not what is the max to allocate.
  3. The max limits are configured with the java.opts settings listed above.

Finally, you may want to check this other SO question that describes a similar problem (and solution).

HashMap: One Key, multiple Values

Write a new class that holds all the values that you need and use the new class's object as the value in your HashMap

HashMap<String, MyObject>

class MyObject {
public String value1;
public int value2;
public List<String> value3;
}

Doing a join across two databases with different collations on SQL Server and getting an error

A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.

It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)

select
    sone_field collate DATABASE_DEFAULT
from
    table_1
    inner join
    table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever

How to upload (FTP) files to server in a bash script?

Below are two answers. First is a suggestion to use a more secure/flexible solution like ssh/scp/sftp. Second is an explanation of how to run ftp in batch mode.

A secure solution:

You really should use SSH/SCP/SFTP for this rather than FTP. SSH/SCP have the benefits of being more secure and working with public/private keys which allows it to run without a username or password.

You can send a single file:

scp <file to upload> <username>@<hostname>:<destination path>

Or a whole directory:

scp -r <directory to upload> <username>@<hostname>:<destination path>

For more details on setting up keys and moving files to the server with RSYNC, which is useful if you have a lot of files to move, or if you sometimes get just one new file among a set of random files, take a look at:

http://troy.jdmz.net/rsync/index.html

You can also execute a single command after sshing into a server:

From man ssh

ssh [...snipped...] hostname [command] If command is specified, it is executed on the remote host instead of a login shell.

So, an example command is:

ssh [email protected] bunzip file_just_sent.bz2

If you can use SFTP with keys to gain the benefit of a secured connection, there are two tricks I've used to execute commands.

First, you can pass commands using echo and pipe

echo "put files*.xml" | sftp -p -i ~/.ssh/key_name [email protected]

You can also use a batchfile with the -b parameter:

sftp -b batchfile.txt ~/.ssh/key_name [email protected]

An FTP solution, if you really need it:

If you understand that FTP is insecure and more limited and you really really want to script it...

There's a great article on this at http://www.stratigery.com/scripting.ftp.html

#!/bin/sh
HOST='ftp.example.com'
USER='yourid'
PASSWD='yourpw'
FILE='file.txt'

ftp -n $HOST <<END_SCRIPT
quote USER $USER
quote PASS $PASSWD
binary
put $FILE
quit
END_SCRIPT
exit 0

The -n to ftp ensures that the command won't try to get the password from the current terminal. The other fancy part is the use of a heredoc: the <<END_SCRIPT starts the heredoc and then that exact same END_SCRIPT on the beginning of the line by itself ends the heredoc. The binary command will set it to binary mode which helps if you are transferring something other than a text file.

Get the system date and split day, month and year

You should use DateTime.TryParseExcact if you know the format, or if not and want to use the system settings DateTime.TryParse. And to print the date,DateTime.ToString with the right format in the argument. To get the year, month or day you have DateTime.Year, DateTime.Month or DateTime.Day.

See DateTime Structures in MSDN for additional references.

How to set the project name/group/version, plus {source,target} compatibility in the same file?

I found the solution to a similar problem. I am using Gradle 1.11 (as April, 2014). The project name can be changed directly in settings.gradle file as following:

  rootProject.name='YourNewName'

This takes care of uploading to repository (Artifactory w/ its plugin for me) with the correct artifactId.

Specify the date format in XMLGregorianCalendar

There isn’t really an ideal conversion, but I would like to supply a couple of options.

java.time

First, you should use LocalDate from java.time, the modern Java date and time API, for parsing and holding your date. Avoid Date and SimpleDateFormat since they have design problems and also are long outdated. The latter in particular is notoriously troublesome.

    DateTimeFormatter originalDateFormatter = DateTimeFormatter.ofPattern("dd/MM/uuuu");

    String dateString = "13/06/1983";
    LocalDate date = LocalDate.parse(dateString, originalDateFormatter);
    System.out.println(date);

The output is:

1983-06-13

Do you need to go any further? LocalDate.toString() produces the format you asked about.

Format and parse

Assuming that you do require an XMLGregorianCalendar the first and easy option for converting is:

    XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar(date.toString());
    System.out.println(xmlDate);

1983-06-13

Formatting to a string and parsing it back feels like a waste to me, but as I said, it’s easy and I don’t think that there are any surprises about the result being as expected.

Pass year, month and day of month individually

    XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
            .newXMLGregorianCalendarDate(date.getYear(), date.getMonthValue(),
                    date.getDayOfMonth(), DatatypeConstants.FIELD_UNDEFINED);

The result is the same as before. We need to make explicit that we don’t want a time zone offset (this is what DatatypeConstants.FIELD_UNDEFINED specifies). In case someone is wondering, both LocalDate and XMLGregorianCalendar number months the way humans do, so there is no adding or subtracting 1.

Convert through GregorianCalendar

I only show you this option because I somehow consider it the official way: convert LocalDate to ZonedDateTime, then to GregorianCalendar and finally to XMLGregorianCalendar.

    ZonedDateTime dateTime = date.atStartOfDay(ZoneOffset.UTC);
    GregorianCalendar gregCal = GregorianCalendar.from(dateTime);
    XMLGregorianCalendar xmlDate = DatatypeFactory.newInstance()
            .newXMLGregorianCalendar(gregCal);
    xmlDate.setTime(DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED,
            DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED);
    xmlDate.setTimezone(DatatypeConstants.FIELD_UNDEFINED);

I like the conversion itself since we neither need to use strings nor need to pass individual fields (with care to do it in the right order). What I don’t like is that we have to pass a time of day and a time zone offset and then wipe out those fields manually afterwards.

convert streamed buffers to utf8-string

var fs = require("fs");

function readFileLineByLine(filename, processline) {
    var stream = fs.createReadStream(filename);
    var s = "";
    stream.on("data", function(data) {
        s += data.toString('utf8');
        var lines = s.split("\n");
        for (var i = 0; i < lines.length - 1; i++)
            processline(lines[i]);
        s = lines[lines.length - 1];
    });

    stream.on("end",function() {
        var lines = s.split("\n");
        for (var i = 0; i < lines.length; i++)
            processline(lines[i]);
    });
}

var linenumber = 0;
readFileLineByLine(filename, function(line) {
    console.log(++linenumber + " -- " + line);
});

How to send a header using a HTTP request through a curl call?

man curl:

   -H/--header <header>
          (HTTP)  Extra header to use when getting a web page. You may specify
          any number of extra headers. Note that if you should  add  a  custom
          header that has the same name as one of the internal ones curl would
          use, your externally set header will be used instead of the internal
          one.  This  allows  you  to make even trickier stuff than curl would
          normally do. You should not replace internally set  headers  without
          knowing  perfectly well what you're doing. Remove an internal header
          by giving a replacement without content on the  right  side  of  the
          colon, as in: -H "Host:".

          curl  will  make sure that each header you add/replace get sent with
          the proper end of line marker, you should thus not  add  that  as  a
          part  of the header content: do not add newlines or carriage returns
          they will only mess things up for you.

          See also the -A/--user-agent and -e/--referer options.

          This option can be used multiple times to add/replace/remove  multi-
          ple headers.

Example:

curl --header "X-MyHeader: 123" www.google.com

You can see the request that curl sent by adding the -v option.

Perform Button click event when user press Enter key in Textbox

You can do it with javascript/jquery:

<script>
    function runScript(e) {
        if (e.keyCode == 13) {
            $("#myButton").click(); //jquery
            document.getElementById("myButton").click(); //javascript
        }
    }
</script>

<asp:textbox id="txtUsername" runat="server" onkeypress="return runScript(event)" />

<asp:LinkButton id="myButton" text="Login" runat="server" />

How do you access the matched groups in a JavaScript regular expression?

Terminology used in this answer:

  • Match indicates the result of running your RegEx pattern against your string like so: someString.match(regexPattern).
  • Matched patterns indicate all matched portions of the input string, which all reside inside the match array. These are all instances of your pattern inside the input string.
  • Matched groups indicate all groups to catch, defined in the RegEx pattern. (The patterns inside parentheses, like so: /format_(.*?)/g, where (.*?) would be a matched group.) These reside within matched patterns.

Description

To get access to the matched groups, in each of the matched patterns, you need a function or something similar to iterate over the match. There are a number of ways you can do this, as many of the other answers show. Most other answers use a while loop to iterate over all matched patterns, but I think we all know the potential dangers with that approach. It is necessary to match against a new RegExp() instead of just the pattern itself, which only got mentioned in a comment. This is because the .exec() method behaves similar to a generator functionit stops every time there is a match, but keeps its .lastIndex to continue from there on the next .exec() call.

Code examples

Below is an example of a function searchString which returns an Array of all matched patterns, where each match is an Array with all the containing matched groups. Instead of using a while loop, I have provided examples using both the Array.prototype.map() function as well as a more performant way – using a plain for-loop.

Concise versions (less code, more syntactic sugar)

These are less performant since they basically implement a forEach-loop instead of the faster for-loop.

// Concise ES6/ES2015 syntax
const searchString = 
    (string, pattern) => 
        string
        .match(new RegExp(pattern.source, pattern.flags))
        .map(match => 
            new RegExp(pattern.source, pattern.flags)
            .exec(match));

// Or if you will, with ES5 syntax
function searchString(string, pattern) {
    return string
        .match(new RegExp(pattern.source, pattern.flags))
        .map(match =>
            new RegExp(pattern.source, pattern.flags)
            .exec(match));
}

let string = "something format_abc",
    pattern = /(?:^|\s)format_(.*?)(?:\s|$)/;

let result = searchString(string, pattern);
// [[" format_abc", "abc"], null]
// The trailing `null` disappears if you add the `global` flag

Performant versions (more code, less syntactic sugar)

// Performant ES6/ES2015 syntax
const searchString = (string, pattern) => {
    let result = [];

    const matches = string.match(new RegExp(pattern.source, pattern.flags));

    for (let i = 0; i < matches.length; i++) {
        result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
    }

    return result;
};

// Same thing, but with ES5 syntax
function searchString(string, pattern) {
    var result = [];

    var matches = string.match(new RegExp(pattern.source, pattern.flags));

    for (var i = 0; i < matches.length; i++) {
        result.push(new RegExp(pattern.source, pattern.flags).exec(matches[i]));
    }

    return result;
}

let string = "something format_abc",
    pattern = /(?:^|\s)format_(.*?)(?:\s|$)/;

let result = searchString(string, pattern);
// [[" format_abc", "abc"], null]
// The trailing `null` disappears if you add the `global` flag

I have yet to compare these alternatives to the ones previously mentioned in the other answers, but I doubt this approach is less performant and less fail-safe than the others.

How do you select the entire excel sheet with Range using VBA?

Maybe this might work:

Sh.Range("A1", Sh.Range("A" & Rows.Count).End(xlUp))

Webpack.config how to just copy the index.html to the dist folder

You could use the CopyWebpackPlugin. It's working just like this:

module.exports = {
  plugins: [
    new CopyWebpackPlugin([{
      from: './*.html'
    }])
  ]
}

How to update a value in a json file and save it through node.js

//change the value in the in-memory object
content.val1 = 42;
//Serialize as JSON and Write it to a file
fs.writeFileSync(filename, JSON.stringify(content));

Retrieve all values from HashMap keys in an ArrayList Java

Try it this way...

I am considering the HashMap with key and value of type String, HashMap<String,String>

HashMap<String,String> hmap = new HashMap<String,String>();

hmap.put("key1","Val1");
hmap.put("key2","Val2");

ArrayList<String> arList = new ArrayList<String>();

for(Map.Entry<String,String> map : hmap.entrySet()){

     arList.add(map.getValue());

}

HTML Form Redirect After Submit

Try this Javascript (jquery) code. Its an ajax request to an external URL. Use the callback function to fire any code:

<script type="text/javascript">
$(function() {
  $('form').submit(function(){
    $.post('http://example.com/upload', function() {
      window.location = 'http://google.com';
    });
    return false;
  });
});
</script>

Date minus 1 year?

Use strtotime() function:

  $time = strtotime("-1 year", time());
  $date = date("Y-m-d", $time);

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

Use HH for 24 hour hours format:

DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")

Or the tt format specifier for the AM/PM part:

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss tt")

Take a look at the custom Date and Time format strings documentation.

Make A List Item Clickable (HTML/CSS)

How about putting all content inside link?

<li><a href="#" onClick="..." ... >Backpack <img ... /></a></li>

Seems like the most natural thing to try.

How to perform a fade animation on Activity transition?

you can also use this code in your style.xml file so you don't need to write anything else in your activity.java

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="android:windowAnimationStyle">@style/AppTheme.WindowTransition</item>
</style>

<!-- Setting window animation -->
<style name="AppTheme.WindowTransition">
    <item name="android:windowEnterAnimation">@android:anim/fade_in</item>
    <item name="android:windowExitAnimation">@android:anim/fade_out</item>
</style>

When is the finalize() method called in Java?

The Java finalize() method is not a destructor and should not be used to handle logic that your application depends on. The Java spec states there is no guarantee that the finalize method is called at all during the livetime of the application.

What you problably want is a combination of finally and a cleanup method, as in:

MyClass myObj;

try {
    myObj = new MyClass();

    // ...
} finally {
    if (null != myObj) {
        myObj.cleanup();
    }
}

This will correctly handle the situation when the MyClass() constructor throws an exception.

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

In the SQL Server Management Studio, to find out details of the active transaction, execute following command

DBCC opentran()

You will get the detail of the active transaction, then from the SPID of the active transaction, get the detail about the SPID using following commands

exec sp_who2 <SPID>
exec sp_lock <SPID>

For example, if SPID is 69 then execute the command as

exec sp_who2 69
exec sp_lock 69

Now , you can kill that process using the following command

KILL 69

I hope this helps :)

How to concatenate two strings to build a complete path

#!/bin/bash

read -p "Enter a directory: " BASEPATH

SUBFOLD1=${BASEPATH%%/}/subFold1
SUBFOLD2=${BASEPATH%%/}/subFold2

echo "I will create $SUBFOLD1 and $SUBFOLD2"

# mkdir -p $SUBFOLD1
# mkdir -p $SUBFOLD2

And if you want to use readline so you get completion and all that, add a -e to the call to read:

read -e -p "Enter a directory: " BASEPATH

Best way to check if a drop down list contains a value?

ListItem item = ddlComputedliat1.Items.FindByText("Amt D");
if (item == null) {
    ddlComputedliat1.Items.Insert(1, lblnewamountamt.Text);
}

Powershell Get-ChildItem most recent file in directory

You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster

Manually map column names with class properties

An easy way to achieve this is to just use aliases on the columns in your query.

If your database column is PERSON_ID and your object's property is ID, you can just do

select PERSON_ID as Id ...

in your query and Dapper will pick it up as expected.

htaccess redirect to https://www

If you are using CloudFlare or a similar CDN you will get an infinite loop error with the %{HTTPS} solutions provided here. If you're a CloudFlare user you'll need to use this:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

How do I extract data from JSON with PHP?

Intro

First off you have a string. JSON is not an array, an object, or a data structure. JSON is a text-based serialization format - so a fancy string, but still just a string. Decode it in PHP by using json_decode().

 $data = json_decode($json);

Therein you might find:

These are the things that can be encoded in JSON. Or more accurately, these are PHP's versions of the things that can be encoded in JSON.

There's nothing special about them. They are not "JSON objects" or "JSON arrays." You've decoded the JSON - you now have basic everyday PHP types.

Objects will be instances of stdClass, a built-in class which is just a generic thing that's not important here.


Accessing object properties

You access the properties of one of these objects the same way you would for the public non-static properties of any other object, e.g. $object->property.

$json = '
{
    "type": "donut",
    "name": "Cake"
}';

$yummy = json_decode($json);

echo $yummy->type; //donut

Accessing array elements

You access the elements of one of these arrays the same way you would for any other array, e.g. $array[0].

$json = '
[
    "Glazed",
    "Chocolate with Sprinkles",
    "Maple"
]';

$toppings = json_decode($json);

echo $toppings[1]; //Chocolate with Sprinkles

Iterate over it with foreach.

foreach ($toppings as $topping) {
    echo $topping, "\n";
}

Glazed
Chocolate with Sprinkles
Maple

Or mess about with any of the bazillion built-in array functions.


Accessing nested items

The properties of objects and the elements of arrays might be more objects and/or arrays - you can simply continue to access their properties and members as usual, e.g. $object->array[0]->etc.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

echo $yummy->toppings[2]->id; //5004

Passing true as the second argument to json_decode()

When you do this, instead of objects you'll get associative arrays - arrays with strings for keys. Again you access the elements thereof as usual, e.g. $array['key'].

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json, true);

echo $yummy['toppings'][2]['type']; //Maple

Accessing associative array items

When decoding a JSON object to an associative PHP array, you can iterate both keys and values using the foreach (array_expression as $key => $value) syntax, eg

$json = '
{
    "foo": "foo value",
    "bar": "bar value",
    "baz": "baz value"
}';

$assoc = json_decode($json, true);
foreach ($assoc as $key => $value) {
    echo "The value of key '$key' is '$value'", PHP_EOL;
}

Prints

The value of key 'foo' is 'foo value'
The value of key 'bar' is 'bar value'
The value of key 'baz' is 'baz value'


Don't know how the data is structured

Read the documentation for whatever it is you're getting the JSON from.

Look at the JSON - where you see curly brackets {} expect an object, where you see square brackets [] expect an array.

Hit the decoded data with a print_r():

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": [
        { "id": "5002", "type": "Glazed" },
        { "id": "5006", "type": "Chocolate with Sprinkles" },
        { "id": "5004", "type": "Maple" }
    ]
}';

$yummy = json_decode($json);

print_r($yummy);

and check the output:

stdClass Object
(
    [type] => donut
    [name] => Cake
    [toppings] => Array
        (
            [0] => stdClass Object
                (
                    [id] => 5002
                    [type] => Glazed
                )

            [1] => stdClass Object
                (
                    [id] => 5006
                    [type] => Chocolate with Sprinkles
                )

            [2] => stdClass Object
                (
                    [id] => 5004
                    [type] => Maple
                )

        )

)

It'll tell you where you have objects, where you have arrays, along with the names and values of their members.

If you can only get so far into it before you get lost - go that far and hit that with print_r():

print_r($yummy->toppings[0]);
stdClass Object
(
    [id] => 5002
    [type] => Glazed
)

Take a look at it in this handy interactive JSON explorer.

Break the problem down into pieces that are easier to wrap your head around.


json_decode() returns null

This happens because either:

  1. The JSON consists entirely of just that, null.
  2. The JSON is invalid - check the result of json_last_error_msg or put it through something like JSONLint.
  3. It contains elements nested more than 512 levels deep. This default max depth can be overridden by passing an integer as the third argument to json_decode().

If you need to change the max depth you're probably solving the wrong problem. Find out why you're getting such deeply nested data (e.g. the service you're querying that's generating the JSON has a bug) and get that to not happen.


Object property name contains a special character

Sometimes you'll have an object property name that contains something like a hyphen - or at sign @ which can't be used in a literal identifier. Instead you can use a string literal within curly braces to address it.

$json = '{"@attributes":{"answer":42}}';
$thing = json_decode($json);

echo $thing->{'@attributes'}->answer; //42

If you have an integer as property see: How to access object properties with names like integers? as reference.


Someone put JSON in your JSON

It's ridiculous but it happens - there's JSON encoded as a string within your JSON. Decode, access the string as usual, decode that, and eventually get to what you need.

$json = '
{
    "type": "donut",
    "name": "Cake",
    "toppings": "[{ \"type\": \"Glazed\" }, { \"type\": \"Maple\" }]"
}';

$yummy = json_decode($json);
$toppings = json_decode($yummy->toppings);

echo $toppings[0]->type; //Glazed

Data doesn't fit in memory

If your JSON is too large for json_decode() to handle at once things start to get tricky. See:


How to sort it

See: Reference: all basic ways to sort arrays and data in PHP.

Invoke native date picker from web-app on iOS/Android

iOS5 has support for this (Reference). If you want to invoke the native date picker you might have a an option with PhoneGap (have not tested this myself).

Angular 2 'component' is not a known element

I know this is a long resolved problem, but in my case I had a different solution. It was actually a mistake I made that maybe you made as well and didn't fully notice. My mistake was that I accidentally placed a Module e.g., MatChipsModule, MatAutoCompleteModule, on the declarations section; the section that is composed only by components e.g., MainComponent, AboutComponent. This made all my other import unrecognizable.

How to put an image next to each other

Change div to span. And space the icons using &nbsp; HTML

 <div class="nav3" style="height:705px;">
 <span class="icons"><a href="http://www.facebook.com/"><img src="images/facebook.png"></a>
 </span>&nbsp;&nbsp;&nbsp;
 <span class="icons"><a href="https://twitter.com"><img src="images/twitter.png"></a>
 </span>
 </div>

CSS

.nav3 {
background-color: #E9E8C7;
height: auto;
width: 150px;
float: left;
padding-left: 20px;
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
color: #333333;
padding-top: 20px;
padding-right: 20px;
}

.icons{
display:inline-block;
width: 64px; 
height: 64px; 
}

 a.icons:hover {
 background: #C93;
 }

span does not break line, div does.

Create File If File Does Not Exist

For Example

    string rootPath = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System));
        rootPath += "MTN";
        if (!(File.Exists(rootPath)))
        {
            File.CreateText(rootPath);
        }

Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration

I had this problem and the suggestions above didn't help. What I found is that the add-migration reads the current state and creates a signature of the current model. You must modify your model before modifying. So the sequence is.

  1. Modify model
  2. run add-migration

I did the opposite and added the migration before modifying my model (which was empty, so I added the new columns) and then ran my code.

Hope this helps.

Sequel Pro Alternative for Windows

You say you've had problems with Navicat. For the record, I use Navicat and I haven't experienced the issue you describe. You might want to dig around, see if there's a reason for your problem and/or a solution, because given the question asked, my first recommendation would have been Navicat.

But if you want alternative suggestions, here are a few that I know of and have used:

MySQL has its own tool which you can download for free, called MySQL Workbench. Download it from here: http://wb.mysql.com/. My experience is that it's powerful, but I didn't really like the UI. But that's just my personal taste.

Another free program you might want to try is HeidiSQL. It's more similar to Navicat than MySQL Workbench. A colleague of mine loves it.

(interesting to note, by the way, that MariaDB (the forked version of MySQL) is currently shipped with HeidiSQL as its GUI tool)

Finally, if you're running a web server on your machine, there's always the option of a browser-based tool like PHPMyAdmin. It's actually a surprisingly powerful piece of software.

How to Resize a Bitmap in Android?

While the previous answers do scale the image and take care of the aspect ratio, the resampling itself should be done so that there is no aliasing. Taking care of scale is a matter of fixing arguments correctly. There are many comments about the quality of the output images from standard scaling call. to maintain quality of the image one should use the standard call:

Bitmap resizedBitmap = Bitmap.createScaledBitmap(originalBitmap, newWidth, newHeight, true);

with the last argument set to true because it will do the bilinear filtering for resampling to prevent aliasing. Read more about aliasing here: https://en.wikipedia.org/wiki/Aliasing

From android documentation:

https://developer.android.com/reference/android/graphics/Bitmap#createScaledBitmap(android.graphics.Bitmap,%20int,%20int,%20boolean)


public static Bitmap createScaledBitmap (Bitmap src, 
                int dstWidth, 
                int dstHeight, 
                boolean filter)

filter : boolean, Whether or not bilinear filtering should be used when scaling the bitmap. If this is true then bilinear filtering will be used when scaling which has better image quality at the cost of worse performance. If this is false then nearest-neighbor scaling is used instead which will have worse image quality but is faster. Recommended default is to set filter to 'true' as the cost of bilinear filtering is typically minimal and the improved image quality is significant.

Parse string to DateTime in C#

Try the following code

Month = Date = DateTime.Now.Month.ToString();   
Year = DateTime.Now.Year.ToString(); 
ViewBag.Today = System.Globalization.CultureInfo.InvariantCulture.DateTimeFormat.GetMonthName(Int32.Parse(Month)) + Year;

A regular expression to exclude a word/string

Here's yet another way (using a negative look-ahead):

^/(?!ignoreme|ignoreme2|ignoremeN)([a-z0-9]+)$ 

Note: There's only one capturing expression: ([a-z0-9]+).

Convert dd-mm-yyyy string to date

regular expression example:

new Date( "13-01-2011".replace( /(\d{2})-(\d{2})-(\d{4})/, "$2/$1/$3") );

Text file in VBA: Open/Find Replace/SaveAs/Close File

I have had the same problem and came acrosse this site.

the solution to just set another "filename" in the

... for output as ... command was very simple and useful.

in addition (beyond the Application.GetSaveAsFilename() Dialog)

it is very simple to set a** new filename** just using

the replace command, so you may change the filename/extension

eg. (as from the first post)

sFileName = "C:\filelocation"
iFileNum = FreeFile

Open sFileName For Input As iFileNum
content = (...edit the content) 

Close iFileNum

now just set:

newFilename = replace(sFilename, ".txt", ".csv") to change the extension

or

newFilename = replace(sFilename, ".", "_edit.") for a differrent filename

and then just as before

iFileNum = FreeFile
Open newFileName For Output As iFileNum

Print #iFileNum, content
Close iFileNum 

I surfed over an hour to find out how to rename a txt-file,

with many different solutions, but it could be sooo easy :)

How print out the contents of a HashMap<String, String> in ascending order based on its values?

You aren't going to be able to do this from the HashMap class alone.

I would take the Map<String, String> codes, construct a reverse map of TreeMap<String, String> reversedMap where you map the values of the codes Map to the keys (this would require your original Map to have a one-to-one mapping from key-to-value). Since the TreeMap provides Iterators which returns entries in ascending key order, this will give you the value/key combination of the first map in the order (sorted by values) you desire.

Map<String, String> reversedMap = new TreeMap<String, String>(codes);

//then you just access the reversedMap however you like...
for (Map.Entry entry : reversedMap.entrySet()) {
    System.out.println(entry.getKey() + ", " + entry.getValue());
}

There are several collections libraries (commons-collections, Google Collections, etc) which have similar bidirectional Map implementations.

Converting an int to a binary string representation in Java?

The simplest approach is to check whether or not the number is odd. If it is, by definition, its right-most binary number will be "1" (2^0). After we've determined this, we bit shift the number to the right and check the same value using recursion.

@Test
public void shouldPrintBinary() {
    StringBuilder sb = new StringBuilder();
    convert(1234, sb);
}

private void convert(int n, StringBuilder sb) {

    if (n > 0) {
        sb.append(n % 2);
        convert(n >> 1, sb);
    } else {
        System.out.println(sb.reverse().toString());
    }
}

How do I convert datetime.timedelta to minutes, hours in Python?

There is no need for custom helper functions if all we need is to print the string of the form [D day[s], ][H]H:MM:SS[.UUUUUU]. timedelta object supports str() operation that will do this. It works even in Python 2.6.

>>> from datetime import timedelta
>>> timedelta(seconds=90136)
datetime.timedelta(1, 3736)
>>> str(timedelta(seconds=90136))
'1 day, 1:02:16'

How do I find out what version of Sybase is running

Run this command:

select @@version

How do I assign ls to an array in Linux Bash?

It would be this

array=($(ls -d */))

EDIT: See Gordon Davisson's solution for a more general answer (i.e. if your filenames contain special characters). This answer is merely a syntax correction.

how to sort an ArrayList in ascending order using Collections and Comparator

Two ways to get this done:

Collections.sort(myArray)

given elements inside myArray implements Comparable

Second

Collections.sort(myArray, new MyArrayElementComparator());

where MyArrayElementComparator is Comparator for elements inside myArray

How to delete stuff printed to console by System.out.println()?

System.out is a PrintStream, and in itself does not provide any way to modify what gets output. Depending on what is backing that object, you may or may not be able to modify it. For example, if you are redirecting System.out to a log file, you may be able to modify that file after the fact. If it's going straight to a console, the text will disappear once it reaches the top of the console's buffer, but there's no way to mess with it programmatically.

I'm not sure exactly what you're hoping to accomplish, but you may want to consider creating a proxy PrintStream to filter messages as they get output, instead of trying to remove them after the fact.

How does tuple comparison work in Python?

The Python documentation does explain it.

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Download Microsoft Drivers for PHP for SQL Server. Extract the files and use one of:

File                             Thread Safe         VC Bulid
php_sqlsrv_53_nts_vc6.dll           No                  VC6
php_sqlsrv_53_nts_vc9.dll           No                  VC9
php_sqlsrv_53_ts_vc6.dll            Yes                 VC6
php_sqlsrv_53_ts_vc9.dll            Yes                 VC9

You can see the Thread Safety status in phpinfo().

Add the correct file to your ext directory and the following line to your php.ini:

extension=php_sqlsrv_53_*_vc*.dll

Use the filename of the file you used.

As Gordon already posted this is the new Extension from Microsoft and uses the sqlsrv_* API instead of mssql_*

Update:
On Linux you do not have the requisite drivers and neither the SQLSERV Extension.
Look at Connect to MS SQL Server from PHP on Linux? for a discussion on this.

In short you need to install FreeTDS and YES you need to use mssql_* functions on linux. see update 2

To simplify things in the long run I would recommend creating a wrapper class with requisite functions which use the appropriate API (sqlsrv_* or mssql_*) based on which extension is loaded.

Update 2: You do not need to use mssql_* functions on linux. You can connect to an ms sql server using PDO + ODBC + FreeTDS. On windows, the best performing method to connect is via PDO + ODBC + SQL Native Client since the PDO + SQLSRV driver can be incredibly slow.

select the TOP N rows from a table

you can also check this link

SELECT * FROM master_question WHERE 1 ORDER BY question_id ASC LIMIT 20

for more detail click here

What is the difference between int, Int16, Int32 and Int64?

Nothing. The sole difference between the types is their size (and, hence, the range of values they can represent).

javax vs java package

Some packages like javax.swing were not included in java standard library at first. Sun company decided to consider them official and included them into the early versions of java as standard libraries or standard extensions.

By convention, all the standard extensions start with an X while they can get promoted to first-class over time like what happened for javax.swing.

Swift performSelector:withObject:afterDelay: is unavailable

You could do this:

var timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: Selector("someSelector"), userInfo: nil, repeats: false)

func someSelector() {
    // Something after a delay
}

SWIFT 3

let timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(someSelector), userInfo: nil, repeats: false)

func someSelector() {
    // Something after a delay
}

Possible to perform cross-database queries with PostgreSQL?

see https://www.cybertec-postgresql.com/en/joining-data-from-multiple-postgres-databases/ [published 2017]

These days you also have the option to use https://prestodb.io/

You can run SQL on that PrestoDB node and it will distribute the SQL query as required. It can connect to the same node twice for different databases, or it might be connecting to different nodes on different hosts.

It does not support:

DELETE
ALTER TABLE
CREATE TABLE (CREATE TABLE AS is supported)
GRANT
REVOKE
SHOW GRANTS
SHOW ROLES
SHOW ROLE GRANTS

So you should only use it for SELECT and JOIN needs. Connect directly to each database for the above needs. (It looks like you can also INSERT or UPDATE which is nice)

Client applications connect to PrestoDB primarily using JDBC, but other types of connection are possible including a Tableu compatible web API

This is an open source tool governed by the Linux Foundation and Presto Foundation.

The founding members of the Presto Foundation are: Facebook, Uber, Twitter, and Alibaba.

The current members are: Facebook, Uber, Twitter, Alibaba, Alluxio, Ahana, Upsolver, and Intel.

Trying Gradle build - "Task 'build' not found in root project"

You didn't do what you're being asked to do.

What is asked:

I have to execute ../gradlew build

What you do

cd ..
gradlew build

That's not the same thing.

The first one will use the gradlew command found in the .. directory (mdeinum...), and look for the build file to execute in the current directory, which is (for example) chapter1-bookstore.

The second one will execute the gradlew command found in the current directory (mdeinum...), and look for the build file to execute in the current directory, which is mdeinum....

So the build file executed is not the same.

How to make HTTP Post request with JSON body in Swift

HTTP Post in Swift capturing the errors

let json = [ Activity.KEY_IDSUBJECT : activity.idSubject, Activity.KEY_RECORDMODE : "3", Activity.KEY_LOCATION_LONGITUDE : "0",Activity.KEY_LOCATION_LATITUDE : "0", Activity.KEY_CHECKIN : String(activity.dateCheckIn), Activity.KEY_CHECKOUT : String(activity.dateCheckOut) ]

do {
    let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)

    // create post request
    let url = NSURL(string: "https://...appspot.com/_ah/api/activityendpoint/v1/activity")!
    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"

    // insert json data to the request
    request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
    request.HTTPBody = jsonData


    let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
        if error != nil{
            print("Error -> \(error)")
            return
        }

        do {
            let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]

            print("Result -> \(result)")

        } catch {
            print("Error -> \(error)")
        }
    }

    task.resume()
    return task
} catch {
    print(error)
}

Convert double to Int, rounded down

double myDouble = 420.5;
//Type cast double to int
int i = (int)myDouble;
System.out.println(i);

The double value is 420.5 and the application prints out the integer value of 420

How to include view/partial specific styling in AngularJS

If you only need your CSS to be applied to one specific view, I'm using this handy snippet inside my controller:

$("body").addClass("mystate");

$scope.$on("$destroy", function() {
  $("body").removeClass("mystate"); 
});

This will add a class to my body tag when the state loads, and remove it when the state is destroyed (i.e. someone changes pages). This solves my related problem of only needing CSS to be applied to one state in my application.

The application was unable to start correctly (0xc000007b)

A load time dependency could not be resolved. The easiest way to debug this is to use Dependency Walker. Use the Profile option to get diagnostics output of the load process. This will identify the point of failure and should guide you to a solution.

The most common cause of this error is trying to load a 64 bit DLL into a 32 bit process, or vice versa.

Embed YouTube Video with No Ads

From the YouTube help:

You will automatically be opted into showing ads on embedded videos if you've associated your YouTube and AdSense accounts and have enabled your videos for embedding.

If you don't want to show overlay ads on your embedded videos, you can opt your videos out of showing overlay ads, though this will also disable overlay ads on your videos on YouTube.com. You may also disable your videos for embedding.

https://support.google.com/youtube/answer/132596?hl=en

Another technical solution could be to use a custom video player, and streamline the youtube video with that one. Have not tried but guess that the ads cannot be displayed in a custom player. However, could be forbidden.

Windows shell command to get the full path to the current directory?

Use cd with no arguments if you're using the shell directly, or %cd% if you want to use it in a batch file (it behaves like an environment variable).

Selectors in Objective-C?

NSString's method is lowercaseString (0 arguments), not lowercaseString: (1 argument).

How to fix the session_register() deprecated issue?

before PHP 5.3

session_register("name");

since PHP 5.3

$_SESSION['name'] = $name;

Why do I need to explicitly push a new branch?

At first check

Step-1: git remote -v
//if found git initialize then remove or skip step-2

Step-2: git remote rm origin
//Then configure your email address globally git

Step-3: git config --global user.email "[email protected]"

Step-4: git initial

Step-5: git commit -m "Initial Project"
//If already add project repo then skip step-6

Step-6: git remote add origin %repo link from bitbucket.org%

Step-7: git push -u origin master

How can I install MacVim on OS X?

That Macvim is obsolete. Use https://github.com/macvim-dev/macvim instead

See the FAQ (https://github.com/b4winckler/macvim/wiki/FAQ#how-can-i-open-files-from-terminal) for how to install the mvim script for launching from the command line

How to call another controller Action From a controller in Mvc

as @DLeh says Use rather

var controller = DependencyResolver.Current.GetService<ControllerB>();

But, giving the controller, a controlller context is important especially when you need to access the User object, Server object, or the HttpContext inside the 'child' controller.

I have added a line of code:

controller.ControllerContext = new ControllerContext(Request.RequestContext, controller);

or else you could have used System.Web to acces the current context too, to access Server or the early metioned objects

NB: i am targetting the framework version 4.6 (Mvc5)

What does "The APR based Apache Tomcat Native library was not found" mean?

My problem was in add some library from tomcat to eclipse class path i just going to eclipse click right to project and going to debug configuration -> classpath -> Add External JARs add all jars files from apache-tomcat-7.0.35\bin this was my problem and it's worked for me .
enter image description here

Using C# to read/write Excel files (.xls/.xlsx)

I use NPOI for all my Excel needs.

http://npoi.codeplex.com/

Comes with a solution of examples for many common Excel tasks.

Get file name from URI string in C#

I think this will do what you need:

var uri = new Uri(hreflink);
var filename = uri.Segments.Last();

VueJS conditionally add an attribute for an element

Simplest form:

<input :required="test">   // if true
<input :required="!test">  // if false
<input :required="!!test"> // test ? true : false

How to verify if a file exists in a batch file?

Here is a good example on how to do a command if a file does or does not exist:

if exist C:\myprogram\sync\data.handler echo Now Exiting && Exit
if not exist C:\myprogram\html\data.sql Exit

We will take those three files and put it in a temporary place. After deleting the folder, it will restore those three files.

xcopy "test" "C:\temp"
xcopy "test2" "C:\temp"
del C:\myprogram\sync\
xcopy "C:\temp" "test"
xcopy "C:\temp" "test2"
del "c:\temp"

Use the XCOPY command:

xcopy "C:\myprogram\html\data.sql"  /c /d /h /e /i /y  "C:\myprogram\sync\"

I will explain what the /c /d /h /e /i /y means:

  /C           Continues copying even if errors occur.
  /D:m-d-y     Copies files changed on or after the specified date.
               If no date is given, copies only those files whose
               source time is newer than the destination time.
  /H           Copies hidden and system files also.
  /E           Copies directories and subdirectories, including empty ones.
               Same as /S /E. May be used to modify /T.
  /T           Creates directory structure, but does not copy files. Does not
               include empty directories or subdirectories. /T /E includes
  /I           If destination does not exist and copying more than one file,
               assumes that destination must be a directory.
  /Y           Suppresses prompting to confirm you want to overwrite an
               existing destination file.

`To see all the commands type`xcopy /? in cmd

Call other batch file with option sync.bat myprogram.ini.

I am not sure what you mean by this, but if you just want to open both of these files you just put the path of the file like

Path/sync.bat
Path/myprogram.ini

If it was in the Bash environment it was easy for me, but I do not know how to test if a file or folder exists and if it is a file or folder.

You are using a batch file. You mentioned earlier you have to create a .bat file to use this:

I have to create a .BAT file that does this:

What is the best way to test for an empty string in Go?

Checking for length is a good answer, but you could also account for an "empty" string that is also only whitespace. Not "technically" empty, but if you care to check:

package main

import (
  "fmt"
  "strings"
)

func main() {
  stringOne := "merpflakes"
  stringTwo := "   "
  stringThree := ""

  if len(strings.TrimSpace(stringOne)) == 0 {
    fmt.Println("String is empty!")
  }

  if len(strings.TrimSpace(stringTwo)) == 0 {
    fmt.Println("String two is empty!")
  }

  if len(stringTwo) == 0 {
    fmt.Println("String two is still empty!")
  }

  if len(strings.TrimSpace(stringThree)) == 0 {
    fmt.Println("String three is empty!")
  }
}

How to hide/show div tags using JavaScript?

try yo write document.getElementById('id').style.visibility="hidden";

getaddrinfo: nodename nor servname provided, or not known

For me, I had to change a line of code in my local_env.yml to get the rspec tests to run.

I had originally had:

REDIS_HOST: 'redis'

and changed it to:

REDIS_HOST: 'localhost'

and the test ran fine.

Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

A comment from Tomasz Madeyski is what fixed my problem... he tells that exists a bug on SetDefaultCredential, him says:

"The issue is that in UseDefaultCredentials setter there is this code: this.transport.Credentials = value ? (ICredentialsByHost) CredentialCache.DefaultNetworkCredentials : (ICredentialsByHost) null; which overrides credentials set by Credentials setter. For me it looks like SmtpClient's bug"

if you put smtpClient.UseDefaultCredentials = false after set credentials... this line set to null those credentials...

Excel compare two columns and highlight duplicates

NOTE: You may want to remove duplicate items (eg duplicate entries in the same column) before doing these steps to prevent false positives.

  1. Select both columns
  2. click Conditional Formatting
  3. click Highlight Cells Rules
  4. click Duplicate Values (the defaults should be OK)
  5. Duplicates are now highlighted in red:

enter image description here

enter image description here

How do I capitalize first letter of first name and last name in C#?

I use my own method to get this fixed:

For example the phrase: "hello world. hello this is the stackoverflow world." will be "Hello World. Hello This Is The Stackoverflow World.". Regex \b (start of a word) \w (first charactor of the word) will do the trick.

/// <summary>
/// Makes each first letter of a word uppercase. The rest will be lowercase
/// </summary>
/// <param name="Phrase"></param>
/// <returns></returns>
public static string FormatWordsWithFirstCapital(string Phrase)
{
     MatchCollection Matches = Regex.Matches(Phrase, "\\b\\w");
     Phrase = Phrase.ToLower();
     foreach (Match Match in Matches)
         Phrase = Phrase.Remove(Match.Index, 1).Insert(Match.Index, Match.Value.ToUpper());

     return Phrase;
}

How to create and write to a txt file using VBA

To elaborate on Ben's answer:

If you add a reference to Microsoft Scripting Runtime and correctly type the variable fso you can take advantage of autocompletion (Intellisense) and discover the other great features of FileSystemObject.

Here is a complete example module:

Option Explicit

' Go to Tools -> References... and check "Microsoft Scripting Runtime" to be able to use
' the FileSystemObject which has many useful features for handling files and folders
Public Sub SaveTextToFile()

    Dim filePath As String
    filePath = "C:\temp\MyTestFile.txt"

    ' The advantage of correctly typing fso as FileSystemObject is to make autocompletion
    ' (Intellisense) work, which helps you avoid typos and lets you discover other useful
    ' methods of the FileSystemObject
    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    Dim fileStream As TextStream

    ' Here the actual file is created and opened for write access
    Set fileStream = fso.CreateTextFile(filePath)

    ' Write something to the file
    fileStream.WriteLine "something"

    ' Close it, so it is not locked anymore
    fileStream.Close

    ' Here is another great method of the FileSystemObject that checks if a file exists
    If fso.FileExists(filePath) Then
        MsgBox "Yay! The file was created! :D"
    End If

    ' Explicitly setting objects to Nothing should not be necessary in most cases, but if
    ' you're writing macros for Microsoft Access, you may want to uncomment the following
    ' two lines (see https://stackoverflow.com/a/517202/2822719 for details):
    'Set fileStream = Nothing
    'Set fso = Nothing

End Sub

Convert Map to JSON using Jackson

You can convert Map to JSON using Jackson as follows:

Map<String,String> payload = new HashMap<>();
payload.put("key1","value1");
payload.put("key2","value2");

String json = new ObjectMapper().writeValueAsString(payload);
System.out.println(json);

Why dividing two integers doesn't get a float?

Specifically, this is not rounding your result, it's truncating toward zero. So if you divide -3/2, you'll get -1 and not -2. Welcome to integral math! Back before CPUs could do floating point operations or the advent of math co-processors, we did everything with integral math. Even though there were libraries for floating point math, they were too expensive (in CPU instructions) for general purpose, so we used a 16 bit value for the whole portion of a number and another 16 value for the fraction.

EDIT: my answer makes me think of the classic old man saying "when I was your age..."