Programs & Examples On #Fish

The fish shell is an alternate shell for *nix systems (including Mac OS X). Its claims to fame include enhanced syntax highlighting, completion (with autosuggestions) and high performance.

Define an alias in fish shell

  1. if there is not config.fish in ~/.config/fish/, make it.
  2. there you can write your function .function name; command; end

How to set my default shell on Mac?

From Terminal:

  1. Add Fish to /etc/shells, which will require an administrative password:

    sudo echo /usr/local/bin/fish >> /etc/shells
    
  2. Make Fish your default shell with chsh:

    chsh -s /usr/local/bin/fish
    

From System Preferences:

  1. User and Groups ? ctrl-click on Current User ? Advanced Options...

  2. Change Login shell to /usr/local/bin/fish

    login shell

  3. Press OK, log out and in again

Page Redirect after X seconds wait using JavaScript

You can use this JavaScript function. Here you can display Redirection message to the user and redirected to the given URL.

<script type="text/javascript">   
    function Redirect() 
    {  
        window.location="http://www.newpage.com"; 
    } 
    document.write("You will be redirected to a new page in 5 seconds"); 
    setTimeout('Redirect()', 5000);   
</script>

Connect different Windows User in SQL Server Management Studio (2005 or later)

There are many places where someone might want to deploy this kind of scenario, but due to the way integrated authentication works, it is not possible.

As gbn mentioned, integrated authentication uses a special token that corresponds to your Windows identity. There are coding practices called "impersonation" (probably used by the Run As... command) that allow you to effectively perform an activity as another Windows user, but there is not really a way to arbitrarily act as a different user (à la Linux) in Windows applications aside from that.

If you really need to administer multiple servers across several domains, you might consider one of the following:

  1. Set up Domain Trust between your domains so that your account can access computers in the trusting domain
  2. Configure a SQL user (using mixed authentication) across all the servers you need to administer so that you can log in that way; obviously, this might introduce some security issues and create a maintenance nightmare if you have to change all the passwords at some point.

Hopefully this helps!

How to make gradient background in android

Following link may help you http://angrytools.com/gradient/ .This will create custom gradient background in android as like in photoshop.

Find index of a value in an array

If you want to find the word you can use

var word = words.Where(item => item.IsKey).First();

This gives you the first item for which IsKey is true (if there might be non you might want to use .FirstOrDefault()

To get both the item and the index you can use

KeyValuePair<WordType, int> word = words.Select((item, index) => new KeyValuePair<WordType, int>(item, index)).Where(item => item.Key.IsKey).First();

File is universal (three slices), but it does not contain a(n) ARMv7-s slice error for static libraries on iOS, anyway to bypass?

use menu Project -> Build Settings ->

then remove armv7s from the"valid architectures". If standard has been chosen then delete that and then add armv7.

Android: how to convert whole ImageView to Bitmap?

It works in Kotlin after buildDrawingCache() being deprecated

 // convert imageView to bitmap
val bitmap = (imageViewId.getDrawable() as BitmapDrawable).getBitmap()

Android Studio with Google Play Services

I copied the play libs files from the google-play-services_lib to my project libs directory:

  • google-play-services.jar
  • google-play-services.jar.properties.

Then selected them, right-click, "Add as libraries".

AttributeError: 'module' object has no attribute

All the above answers are great, but I'd like to chime in here. If you did not spot any issue mentioned above, try clear up your working environment. It worked for me.

Insert data into a view (SQL Server)

You just need to specify which columns you're inserting directly into:

INSERT INTO [dbo].[rLicenses] ([Name]) VALUES ('test')

Views can be picky like that.

HTML-Tooltip position relative to mouse pointer

We can achieve the same using "Directive" in Angularjs.

            //Bind mousemove event to the element which will show tooltip
            $("#tooltip").mousemove(function(e) {
                //find X & Y coodrinates
                x = e.clientX,
                y = e.clientY;

                //Set tooltip position according to mouse position
                tooltipSpan.style.top = (y + 20) + 'px';
                tooltipSpan.style.left = (x + 20) + 'px';
            });

You can check this post for further details. http://www.ufthelp.com/2014/12/Tooltip-Directive-AngularJS.html

aspx page to redirect to a new page

You could also do this is plain in html with a meta tag:

<html>
<head>
  <meta http-equiv="refresh" content="0;url=new.aspx" />
</head>
<body>
</body>
</html>

Dynamically updating css in Angular 2

You can dynamically change the style(width and height) of div by attaching dynamic value to inline [style.width] and [style.hiegh] property of div.

In your case you can bind width and height property of HomeComponent class with the div's inline style width and height property like this... As directed by Sasxa

<div class="home-component" 
     [style.width]="width + 'px'" 
     [style.height]="height + 'px'">Some stuff in this div
</div>

For the working demo take a look at this plunker(http://plnkr.co/edit/cUbbo2?p=preview)

   //our root app component
import {Component} from 'angular2/core';
import {FORM_DIRECTIVES,FormBuilder,AbstractControl,ControlGroup,} from "angular2/common";

@Component({
  selector: 'home',
  providers: [],
  template: `
     <div class="home-component" [style.width]="width+'px'" [style.height]="height+'px'">Some this div</div>
     <br/>
     <form [ngFormModel]="testForm">
        width:<input type="number" [ngFormControl]="txtWidth"/> <br>
        Height:<input type="number"[ngFormControl]="txtHeight" />
     </form>
  `,
  styles:[`

      .home-component{
        background-color: red;
        width: 50px;
        height: 50px;
    }

  `],
  directives: [FORM_DIRECTIVES]
})
export class App {
  testForm:ControlGroup;
  public width: Number;
  public height: Number;
  public txtWidth:AbstractControl;
  public txtHeight:AbstractControl;

  constructor(private _fb:FormBuilder) {
      this.testForm=_fb.group({
        'txtWidth':['50'],
        'txtHeight':['50']
      });

      this.txtWidth=this.testForm.controls['txtWidth'];
      this.txtHeight=this.testForm.controls['txtHeight'];

      this.txtWidth.valueChanges.subscribe(val=>this.width=val);
      this.txtHeight.valueChanges.subscribe(val=>this.height =val);
  }
}

IIS_IUSRS and IUSR permissions in IIS8

When I added IIS_IUSRS permission to site folder - resources, like js and css, still were unaccessible (error 401, forbidden). However, when I added IUSR - it became ok. So for sure "you CANNOT remove the permissions for IUSR without worrying", dear @Travis G@

How to mock void methods with Mockito

Take a look at the Mockito API docs. As the linked document mentions (Point # 12) you can use any of the doThrow(),doAnswer(),doNothing(),doReturn() family of methods from Mockito framework to mock void methods.

For example,

Mockito.doThrow(new Exception()).when(instance).methodName();

or if you want to combine it with follow-up behavior,

Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();

Presuming that you are looking at mocking the setter setState(String s) in the class World below is the code uses doAnswer method to mock the setState.

World mockWorld = mock(World.class); 
doAnswer(new Answer<Void>() {
    public Void answer(InvocationOnMock invocation) {
      Object[] args = invocation.getArguments();
      System.out.println("called with arguments: " + Arrays.toString(args));
      return null;
    }
}).when(mockWorld).setState(anyString());

Get real path from URI, Android KitKat new storage access framework

the answer below is written by https://stackoverflow.com/users/3082682/cvizv on a page which does not exist anymore, since he has not enough rep to answer a question, I am posting it. No credits by me.

public String getImagePath(Uri uri){
   Cursor cursor = getContentResolver().query(uri, null, null, null, null);
   cursor.moveToFirst();
   String document_id = cursor.getString(0);
   document_id = document_id.substring(document_id.lastIndexOf(":")+1);
   cursor.close();

   cursor = getContentResolver().query( 
   android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
   null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
   cursor.moveToFirst();
   String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
   cursor.close();

   return path;
}

Edit: There is a flow on the code; if device has more than one external storage (external sdcard, external usb etc.), above the code won't work non primary storages.

What is the purpose of flush() in Java streams?

From the docs of the flush method:

Flushes the output stream and forces any buffered output bytes to be written out. The general contract of flush is that calling it is an indication that, if any bytes previously written have been buffered by the implementation of the output stream, such bytes should immediately be written to their intended destination.

The buffering is mainly done to improve the I/O performance. More on this can be read from this article: Tuning Java I/O Performance.

How to logout and redirect to login page using Laravel 5.4?

It's better and safer to add to your LoginController.php the following code, that runs only after the standard logout:

use AuthenticatesUsers;

protected function loggedOut(Request $request)
    {
        return redirect('/new/redirect/you/want');
    }

Get 2 Digit Number For The Month

Try:

select right ('0'+convert(nvarchar(2), DATEPART(mm, getdate())),2 )

Escape curly brace '{' in String.Format

Use double braces {{ or }} so your code becomes:

sb.AppendLine(String.Format("public {0} {1} {{ get; private set; }}", 
prop.Type, prop.Name));

// For prop.Type of "Foo" and prop.Name of "Bar", the result would be:
// public Foo Bar { get; private set; }

Parsing JSON Object in Java

Thank you so much to @Code in another answer. I can read any JSON file thanks to your code. Now, I'm trying to organize all the elements by levels, for could use them!

I was working with Android reading a JSON from an URL and the only I had to change was the lines

Set<Object> set = jsonObject.keySet(); Iterator<Object> iterator = set.iterator();

for

Iterator<?> iterator = jsonObject.keys();

I share my implementation, to help someone:

public void parseJson(JSONObject jsonObject) throws ParseException, JSONException {

    Iterator<?> iterator = jsonObject.keys();
    while (iterator.hasNext()) {
        String obj = iterator.next().toString();

        if (jsonObject.get(obj) instanceof JSONArray) {
            //Toast.makeText(MainActivity.this, "Objeto: JSONArray", Toast.LENGTH_SHORT).show();
            //System.out.println(obj.toString());
            TextView txtView = new TextView(this);
            txtView.setText(obj.toString());
            layoutIzq.addView(txtView);
            getArray(jsonObject.get(obj));
        } else {
            if (jsonObject.get(obj) instanceof JSONObject) {
                //Toast.makeText(MainActivity.this, "Objeto: JSONObject", Toast.LENGTH_SHORT).show();
                parseJson((JSONObject) jsonObject.get(obj));
            } else {
                //Toast.makeText(MainActivity.this, "Objeto: Value", Toast.LENGTH_SHORT).show();
                //System.out.println(obj.toString() + "\t"+ jsonObject.get(obj));
                TextView txtView = new TextView(this);
                txtView.setText(obj.toString() + "\t"+ jsonObject.get(obj));
                layoutIzq.addView(txtView);
            }
        }
    }
}

How do I abort the execution of a Python script?

To exit a script you can use,

import sys
sys.exit()

You can also provide an exit status value, usually an integer.

import sys
sys.exit(0)

Exits with zero, which is generally interpreted as success. Non-zero codes are usually treated as errors. The default is to exit with zero.

import sys
sys.exit("aa! errors!")

Prints "aa! errors!" and exits with a status code of 1.

There is also an _exit() function in the os module. The sys.exit() function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute. The os._exit() version doesn't do this. It just ends the program without doing any cleanup or flushing output buffers, so it shouldn't normally be used.

The Python docs indicate that os._exit() is the normal way to end a child process created with a call to os.fork(), so it does have a use in certain circumstances.

Error: select command denied to user '<userid>'@'<ip-address>' for table '<table-name>'

database user does not have the permission to do select query.

you can grant the permission to the user if you have root access to mysql

http://dev.mysql.com/doc/refman/5.1/en/grant.html

Your second query is on different database on different table.

 String newSQL = "Select `Strike`,`LongShort`,`Current`,`TPLevel`,`SLLevel` from `json`.`tbl_Position` where `TradeID` = '" + i + "'";

And the user you are connecting with does not have permission to access data from this database or this particular table.

Have you consider this thing?

PHP Warning: PHP Startup: Unable to load dynamic library

In my case I got this error because I downloaded a thread-safe version of the dll (infixed with -ts-), but my php installation of php was a non-thread-safe (infixed with -nts-). Downloading the right version of the dll, exactly matching my php installation version fixed the issue.

How to play or open *.mp3 or *.wav sound file in c++ program?

If you want to play the *.mp3 or *.wav file, i think the easiest way would be to use SFML.

Find the most popular element in int[] array

If you don't want to use a map, then just follow these steps:

  1. Sort the array (using Arrays.sort())
  2. Use a variable to hold the most popular element (mostPopular), a variable to hold its number of occurrences in the array (mostPopularCount), and a variable to hold the number of occurrences of the current number in the iteration (currentCount)
  3. Iterate through the array. If the current element is the same as mostPopular, increment currentCount. If not, reset currentCount to 1. If currentCount is > mostPopularCount, set mostPopularCount to currentCount, and mostPopular to the current element.

How to use not contains() in xpath?

XPath queries are case sensitive. Having looked at your example (which, by the way, is awesome, nobody seems to provide examples anymore!), I can get the result you want just by changing "business", to "Business"

//production[not(contains(category,'Business'))]

I have tested this by opening the XML file in Chrome, and using the Developer tools to execute that XPath queries, and it gave me just the Film category back.

ArrayList initialization equivalent to array initialization

This is how it is done using the fluent interface of the op4j Java library (1.1. was released Dec '10) :-

List<String> names = Op.onListFor("Ryan", "Julie", "Bob").get();

It's a very cool library that saves you a tonne of time.

How do I clone a job in Jenkins?

Jenkins 2.9

  1. Jenkins > New Item

    Jenkins New Item

  2. Enter an item name - E.g. "MY_CLONE"

    Enter an item name

  3. Specify the source (Copy from) job > OK

    When you start typing the name, the existing values will be found. Notice that this is case sensitive.

    Copy from OK

  4. Click on Save if you want to keep the default values.

  5. Now both jobs are available in the same location:

    View jobs

How should I call 3 functions in order to execute them one after the other?

your functions should take a callback function, that gets called when it finishes.

function fone(callback){
...do something...
callback.apply(this,[]);

}

function ftwo(callback){
...do something...
callback.apply(this,[]);
}

then usage would be like:

fone(function(){
  ftwo(function(){
   ..ftwo done...
  })
});

Why is it bad practice to call System.gc()?

The reason everyone always says to avoid System.gc() is that it is a pretty good indicator of fundamentally broken code. Any code that depends on it for correctness is certainly broken; any that rely on it for performance are most likely broken.

You don't know what sort of garbage collector you are running under. There are certainly some that do not "stop the world" as you assert, but some JVMs aren't that smart or for various reasons (perhaps they are on a phone?) don't do it. You don't know what it's going to do.

Also, it's not guaranteed to do anything. The JVM may just entirely ignore your request.

The combination of "you don't know what it will do," "you don't know if it will even help," and "you shouldn't need to call it anyway" are why people are so forceful in saying that generally you shouldn't call it. I think it's a case of "if you need to ask whether you should be using this, you shouldn't"


EDIT to address a few concerns from the other thread:

After reading the thread you linked, there's a few more things I'd like to point out. First, someone suggested that calling gc() may return memory to the system. That's certainly not necessarily true - the Java heap itself grows independently of Java allocations.

As in, the JVM will hold memory (many tens of megabytes) and grow the heap as necessary. It doesn't necessarily return that memory to the system even when you free Java objects; it is perfectly free to hold on to the allocated memory to use for future Java allocations.

To show that it's possible that System.gc() does nothing, view:

http://bugs.sun.com/view_bug.do?bug_id=6668279

and in particular that there's a -XX:DisableExplicitGC VM option.

What permission do I need to access Internet from an Android application?

just put above line like below

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.avocats.activeavocats"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="9"
    android:targetSdkVersion="16" />

 <uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >


    <activity
        android:name="com.example.exp.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

For me, the below helped

Find org.apache.http.legacy.jar which is in Android/Sdk/platforms/android-23/optional, add it to your dependency.

Source

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

Android Device not recognized by adb

Find drivers for your device and install them That will be the end of your device not detected problems Windows have driver problems, sometimes messed by overriding the existing driver

You can also try uninstalling driver from Win7 and reinstalling

How to remove close button on the jQuery UI dialog?

Since I found I was doing this in several places in my app, I wrapped it in a plugin:

(function ($) {
   $.fn.dialogNoClose = function () {
      return this.each(function () {
         // hide the close button and prevent ESC key from closing
         $(this).closest(".ui-dialog").find(".ui-dialog-titlebar-close").hide();
         $(this).dialog("option", "closeOnEscape", false);
      });
   };
})(jQuery)

Usage Example:

$("#dialog").dialog({ /* lots of options */ }).dialogNoClose();

Change default icon

If you are using Forms you can use the icon setting in the properties pane. To do this select the form and scroll down in the properties pane till you see the icon setting. When you open the application it will have the icon wherever you have it in your application and in the task bar

Icon settings

Add a column to existing table and uniquely number them on MS SQL Server

for oracle you could do something like below

alter table mytable add (myfield integer);

update mytable set myfield = rownum;

Response to preflight request doesn't pass access control check

For those are using Lambda Integrated Proxy with API Gateway. You need configure your lambda function as if you are submitting your requests to it directly, meaning the function should set up the response headers properly. (If you are using custom lambda functions, this will be handled by the API Gateway.)

//In your lambda's index.handler():
exports.handler = (event, context, callback) => {
     //on success:
     callback(null, {
           statusCode: 200,
           headers: {
                "Access-Control-Allow-Origin" : "*"
           }
     }
}

How can I get current location from user in iOS

You can use this service I wrote to handle everything for you.

This service will request the permissions and handle dealing with the CLLocationManager so you don't have to.

Use like this:

LocationService.getCurrentLocationOnSuccess({ (latitude, longitude) -> () in
    //Do something with Latitude and Longitude

    }, onFailure: { (error) -> () in

      //See what went wrong
      print(error)
})

Setting dynamic scope variables in AngularJs - scope.<some_string>

Using Erik's answer, as a starting point. I found a simpler solution that worked for me.

In my ng-click function I have:

var the_string = 'lifeMeaning';
if ($scope[the_string] === undefined) {
   //Valid in my application for first usage
   $scope[the_string] = true;
} else {
   $scope[the_string] = !$scope[the_string];
}
//$scope.$apply

I've tested it with and without $scope.$apply. Works correctly without it!

How to convert java.lang.Object to ArrayList?

The conversion fails (java.lang.ClassCastException: java.lang.String cannot be cast to java.util.ArrayList) because you have surely some objects that are not ArrayList. verify the types of your different objects.

How to fix a locale setting warning from Perl

perl: warning: Falling back to the standard locale ("C").
locale: Cannot set LC_ALL to default locale: No such file or directory

Solution:

Try this (uk_UA.UTF-8 is my current locale. Write your locale, for example en_US.UTF-8 !)

sudo locale-gen uk_UA.UTF-8

and this.

sudo dpkg-reconfigure locales

Writing outputs to log file and console

Try this, it will do the work:

log_file=$curr_dir/log_file.txt
exec > >(tee -a ${log_file} )
exec 2> >(tee -a ${log_file} >&2)

Handle ModelState Validation in ASP.NET Web API

C#

    public class ValidateModelAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (actionContext.ModelState.IsValid == false)
            {
                actionContext.Response = actionContext.Request.CreateErrorResponse(
                    HttpStatusCode.BadRequest, actionContext.ModelState);
            }
        }
    }

...

    [ValidateModel]
    public HttpResponseMessage Post([FromBody]AnyModel model)
    {

Javascript

$.ajax({
        type: "POST",
        url: "/api/xxxxx",
        async: 'false',
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(data),
        error: function (xhr, status, err) {
            if (xhr.status == 400) {
                DisplayModelStateErrors(xhr.responseJSON.ModelState);
            }
        },
....


function DisplayModelStateErrors(modelState) {
    var message = "";
    var propStrings = Object.keys(modelState);

    $.each(propStrings, function (i, propString) {
        var propErrors = modelState[propString];
        $.each(propErrors, function (j, propError) {
            message += propError;
        });
        message += "\n";
    });

    alert(message);
};

How to properly use the "choices" field option in Django

The cleanest solution is to use the django-model-utils library:

from model_utils import Choices

class Article(models.Model):
    STATUS = Choices('draft', 'published')
    status = models.CharField(choices=STATUS, default=STATUS.draft, max_length=20)

https://django-model-utils.readthedocs.io/en/latest/utilities.html#choices

git stash blunder: git stash pop and ended up with merge conflicts

Note that Git 2.5 (Q2 2015) a future Git might try to make that scenario impossible.

See commit ed178ef by Jeff King (peff), 22 Apr 2015.
(Merged by Junio C Hamano -- gitster -- in commit 05c3967, 19 May 2015)

Note: This has been reverted. See below.

stash: require a clean index to apply/pop

Problem

If you have staged contents in your index and run "stash apply/pop", we may hit a conflict and put new entries into the index.
Recovering to your original state is difficult at that point, because tools like "git reset --keep" will blow away anything staged.

In other words:

"git stash pop/apply" forgot to make sure that not just the working tree is clean but also the index is clean.
The latter is important as a stash application can conflict and the index will be used for conflict resolution.

Solution

We can make this safer by refusing to apply when there are staged changes.

That means if there were merges before because of applying a stash on modified files (added but not committed), now they would not be any merges because the stash apply/pop would stop immediately with:

Cannot apply stash: Your index contains uncommitted changes.

Forcing you to commit the changes means that, in case of merges, you can easily restore the initial state( before git stash apply/pop) with a git reset --hard.


See commit 1937610 (15 Jun 2015), and commit ed178ef (22 Apr 2015) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit bfb539b, 24 Jun 2015)

That commit was an attempt to improve the safety of applying a stash, because the application process may create conflicted index entries, after which it is hard to restore the original index state.

Unfortunately, this hurts some common workflows around "git stash -k", like:

git add -p       ;# (1) stage set of proposed changes
git stash -k     ;# (2) get rid of everything else
make test        ;# (3) make sure proposal is reasonable
git stash apply  ;# (4) restore original working tree

If you "git commit" between steps (3) and (4), then this just works. However, if these steps are part of a pre-commit hook, you don't have that opportunity (you have to restore the original state regardless of whether the tests passed or failed).

What is the difference between connection and read timeout for sockets?

These are timeout values enforced by JVM for TCP connection establishment and waiting on reading data from socket.

If the value is set to infinity, you will not wait forever. It simply means JVM doesn't have timeout and OS will be responsible for all the timeouts. However, the timeouts on OS may be really long. On some slow network, I've seen timeouts as long as 6 minutes.

Even if you set the timeout value for socket, it may not work if the timeout happens in the native code. We can reproduce the problem on Linux by connecting to a host blocked by firewall or unplugging the cable on switch.

The only safe approach to handle TCP timeout is to run the connection code in a different thread and interrupt the thread when it takes too long.

How to pass an object from one activity to another on Android

public class MyClass implements Serializable{
    Here is your instance variable
}

Now you want to pass the object of this class in startActivity. Simply use this:

Bundle b = new Bundle();
b.putSerializable("name", myClassObject);
intent.putExtras(b);

This works here because MyClass implements Serializable.

How to format a numeric column as phone number in SQL

I'd generally recommend you leave the formatting up to your front-end code and just return the data as-is from SQL. However, to do it in SQL, I'd recommend you create a user-defined function to format it. Something like this:

CREATE FUNCTION [dbo].[fnFormatPhoneNumber](@PhoneNo VARCHAR(20))
RETURNS VARCHAR(25)
AS
BEGIN
DECLARE @Formatted VARCHAR(25)

IF (LEN(@PhoneNo) <> 10)
    SET @Formatted = @PhoneNo
ELSE
    SET @Formatted = LEFT(@PhoneNo, 3) + '-' + SUBSTRING(@PhoneNo, 4, 3) + '-' + SUBSTRING(@PhoneNo, 7, 4)

RETURN @Formatted
END
GO

Which you can then use like this:

SELECT [dbo].[fnFormatPhoneNumber](PhoneNumber) AS PhoneNumber
FROM SomeTable

It has a safeguard in, in case the phone number stored isn't the expected number of digits long, is blank, null etc - it won't error.

EDIT: Just clocked on you want to update your existing data. The main bit that's relevant from my answer then is that you need to protect against "dodgy"/incomplete data (i.e. what if some existing values are only 5 characters long)

SSIS Connection Manager Not Storing SQL Password

I use a variable to store the entire connection string and pass it into the ConnectionString expression. This overwrites all settings for the connection and allows you store the password.

MySQL Results as comma separated list

In my case i have to concatenate all the account number of a person who's mobile number is unique. So i have used the following query to achieve that.

SELECT GROUP_CONCAT(AccountsNo) as Accounts FROM `tblaccounts` GROUP BY MobileNumber

Query Result is below:

Accounts
93348001,97530801,93348001,97530801
89663501
62630701
6227895144840002
60070021
60070020
60070019
60070018
60070017
60070016
60070015

Using CSS for a fade-in effect on page load

Method 1:

If you are looking for a self-invoking transition then you should use CSS 3 Animations. They aren't supported either, but this is exactly the kind of thing they were made for.

CSS

#test p {
    margin-top: 25px;
    font-size: 21px;
    text-align: center;

    -webkit-animation: fadein 2s; /* Safari, Chrome and Opera > 12.1 */
       -moz-animation: fadein 2s; /* Firefox < 16 */
        -ms-animation: fadein 2s; /* Internet Explorer */
         -o-animation: fadein 2s; /* Opera < 12.1 */
            animation: fadein 2s;
}

@keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Firefox < 16 */
@-moz-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Safari, Chrome and Opera > 12.1 */
@-webkit-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Internet Explorer */
@-ms-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

/* Opera < 12.1 */
@-o-keyframes fadein {
    from { opacity: 0; }
    to   { opacity: 1; }
}

Demo

Browser Support

All modern browsers and Internet Explorer 10 (and later): http://caniuse.com/#feat=css-animation


Method 2:

Alternatively, you can use jQuery (or plain JavaScript; see the third code block) to change the class on load:

jQuery

$("#test p").addClass("load");?

CSS

#test p {
    opacity: 0;
    font-size: 21px;
    margin-top: 25px;
    text-align: center;

    -webkit-transition: opacity 2s ease-in;
       -moz-transition: opacity 2s ease-in;
        -ms-transition: opacity 2s ease-in;
         -o-transition: opacity 2s ease-in;
            transition: opacity 2s ease-in;
}

#test p.load {
    opacity: 1;
}

Plain JavaScript (not in the demo)

document.getElementById("test").children[0].className += " load";

Demo

Browser Support

All modern browsers and Internet Explorer 10 (and later): http://caniuse.com/#feat=css-transitions


Method 3:

Or, you can use the method that .Mail uses:

jQuery

$("#test p").delay(1000).animate({ opacity: 1 }, 700);?

CSS

#test p {
    opacity: 0;
    font-size: 21px;
    margin-top: 25px;
    text-align: center;
}

Demo

Browser Support

jQuery 1.x: All modern browsers and Internet Explorer 6 (and later): http://jquery.com/browser-support/
jQuery 2.x: All modern browsers and Internet Explorer 9 (and later): http://jquery.com/browser-support/

This method is the most cross-compatible as the target browser does not need to support CSS 3 transitions or animations.

How to kill a while loop with a keystroke?

This is the solution I found with threads and standard libraries

Loop keeps going on until one key is pressed
Returns the key pressed as a single character string

Works in Python 2.7 and 3

import thread
import sys

def getch():
    import termios
    import sys, tty
    def _getch():
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(fd)
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch
    return _getch()

def input_thread(char):
    char.append(getch())

def do_stuff():
    char = []
    thread.start_new_thread(input_thread, (char,))
    i = 0
    while not char :
        i += 1

    print "i = " + str(i) + " char : " + str(char[0])

do_stuff()

Show an image preview before upload

For background images, make sure to use url()

node.backgroundImage = 'url(' + e.target.result + ')';

How to calculate the sentence similarity using word2vec model of gensim with python

Gensim implements a model called Doc2Vec for paragraph embedding.

There are different tutorials presented as IPython notebooks:

Another method would rely on Word2Vec and Word Mover's Distance (WMD), as shown in this tutorial:

An alternative solution would be to rely on average vectors:

from gensim.models import KeyedVectors
from gensim.utils import simple_preprocess    

def tidy_sentence(sentence, vocabulary):
    return [word for word in simple_preprocess(sentence) if word in vocabulary]    

def compute_sentence_similarity(sentence_1, sentence_2, model_wv):
    vocabulary = set(model_wv.index2word)    
    tokens_1 = tidy_sentence(sentence_1, vocabulary)    
    tokens_2 = tidy_sentence(sentence_2, vocabulary)    
    return model_wv.n_similarity(tokens_1, tokens_2)

wv = KeyedVectors.load('model.wv', mmap='r')
sim = compute_sentence_similarity('this is a sentence', 'this is also a sentence', wv)
print(sim)

Finally, if you can run Tensorflow, you may try: https://tfhub.dev/google/universal-sentence-encoder/2

how to initialize a char array?

Absent a really good reason to do otherwise, I'd probably use:

std::vector<char> msg(65546, '\0');

Get the date of next monday, tuesday, etc

The question is tagged "php" so as Tom said, the way to do that would look like this:

date('Y-m-d', strtotime('next tuesday'));

Form Submission without page refresh

Just catch the submit event and prevent that, then do ajax

$(document).ready(function () {
    $('#myform').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            url : $(this).attr('action') || window.location.pathname,
            type: "GET",
            data: $(this).serialize(),
            success: function (data) {
                $("#form_output").html(data);
            },
            error: function (jXHR, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    });
});

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

I had this in VS 2012 where the "Section name" had been changed in a project, and I fixed it by deleting "app.config" in the project, then right-clicking on the project in the "Solution Explorer", selecting "Properties", then "Settings", then making a change to one of the settings, saving, and re-building. This created a new app.config with the correct information.

How do you create a yes/no boolean field in SQL server?

bit will be the simplest and also takes up the least space. Not very verbose compared to "Y/N" but I am fine with it.

How to replace ${} placeholders in a text file?

Create rendertemplate.sh:

#!/usr/bin/env bash

eval "echo \"$(cat $1)\""

And template.tmpl:

Hello, ${WORLD}
Goodbye, ${CHEESE}

Render the template:

$ export WORLD=Foo
$ CHEESE=Bar ./rendertemplate.sh template.tmpl 
Hello, Foo
Goodbye, Bar

Automatically size JPanel inside JFrame

As other posters have said, you need to change the LayoutManager being used. I always preferred using a GridLayout so your code would become:

MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new GridLayout());
mainFrame.pack();
mainFrame.setVisible(true);

GridLayout seems more conceptually correct to me when you want your panel to take up the entire screen.

Importing data from a JSON file into R

jsonlite will import the JSON into a data frame. It can optionally flatten nested objects. Nested arrays will be data frames.

> library(jsonlite)
> winners <- fromJSON("winners.json", flatten=TRUE)
> colnames(winners)
[1] "winner" "votes" "startPrice" "lastVote.timestamp" "lastVote.user.name" "lastVote.user.user_id"
> winners[,c("winner","startPrice","lastVote.user.name")]
    winner startPrice lastVote.user.name
1 68694999          0              Lamur
> winners[,c("votes")]
[[1]]
                            ts user.name user.user_id
1 Thu Mar 25 03:13:01 UTC 2010     Lamur     68694999
2 Thu Mar 25 03:13:08 UTC 2010     Lamur     68694999

Python urllib2 Basic Auth Problem

The problem could be that the Python libraries, per HTTP-Standard, first send an unauthenticated request, and then only if it's answered with a 401 retry, are the correct credentials sent. If the Foursquare servers don't do "totally standard authentication" then the libraries won't work.

Try using headers to do authentication:

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.b64encode('%s:%s' % (username, password))
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

Had the same problem as you and found the solution from this thread: http://forums.shopify.com/categories/9/posts/27662

Passing dynamic javascript values using Url.action()

The easiest way is:

  onClick= 'location.href="/controller/action/"+paramterValue'

Generate C# class from XML

I realise that this is a rather old post and you have probably moved on.

But I had the same problem as you so I decided to write my own program.

The problem with the "xml -> xsd -> classes" route for me was that it just generated a lump of code that was completely unmaintainable and I ended up turfing it.

It is in no way elegant but it did the job for me.

You can get it here: Please make suggestions if you like it.

SimpleXmlToCode

ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

I had the same problem but got round it by setting AutoPostBack to true and in an update panel set the trigger to the dropdownlist control id and event name to SelectedIndexChanged e.g.

    <asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always" enableViewState="true">
        <Triggers>
            <asp:AsyncPostBackTrigger ControlID="ddl1" EventName="SelectedIndexChanged" />
        </Triggers>
        <ContentTemplate>
            <asp:DropDownList ID="ddl1" runat="server" ClientIDMode="Static" OnSelectedIndexChanged="ddl1_SelectedIndexChanged" AutoPostBack="true" ViewStateMode="Enabled">
                <asp:ListItem Text="--Please select a item--" Value="0" />
            </asp:DropDownList>
        </ContentTemplate>
    </asp:UpdatePanel>

MVC Calling a view from a different controller

It is explained pretty well here: Display a view from another controller in ASP.NET MVC

To quote @Womp:
By default, ASP.NET MVC checks first in \Views\[Controller_Dir]\, but after that, if it doesn't find the view, it checks in \Views\Shared.

ASP MVC's idea is "convention over configuration" which means moving the view to the shared folder is the way to go in such cases.

Why is there no Char.Empty like String.Empty?

Not an answer to your question, but to denote a default char you can use just

default(char)

which is same as char.MinValue which in turn is same as \0. One shouldn't use if for something like an empty string though.

How to use relative paths without including the context root name?

If your actual concern is the dynamicness of the webapp context (the "AppName" part), then just retrieve it dynamically by HttpServletRequest#getContextPath().

<head>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/templates/style/main.css" />
    <script src="${pageContext.request.contextPath}/templates/js/main.js"></script>
    <script>var base = "${pageContext.request.contextPath}";</script>
</head>
<body>
    <a href="${pageContext.request.contextPath}/pages/foo.jsp">link</a>
</body>

If you want to set a base path for all relative links so that you don't need to repeat ${pageContext.request.contextPath} in every relative link, use the <base> tag. Here's an example with help of JSTL functions.

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<head>
    <c:set var="url">${pageContext.request.requestURL}</c:set>
    <base href="${fn:substring(url, 0, fn:length(url) - fn:length(pageContext.request.requestURI))}${pageContext.request.contextPath}/" />
    <link rel="stylesheet" href="templates/style/main.css" />
    <script src="templates/js/main.js"></script>
    <script>var base = document.getElementsByTagName("base")[0].href;</script>
</head>
<body>
    <a href="pages/foo.jsp">link</a>
</body>

This way every relative link (i.e. not starting with / or a scheme) will become relative to the <base>.

This is by the way not specifically related to Tomcat in any way. It's just related to HTTP/HTML basics. You would have the same problem in every other webserver.

See also:

Check file uploaded is in csv format

the mime type might not be text/csv some systems can read/save them different. (for example sometimes IE sends .csv files as application/vnd.ms-excel) so you best bet would be to build an array of allowed values and test against that, then find all possible values to test against.

$mimes = array('application/vnd.ms-excel','text/plain','text/csv','text/tsv');
if(in_array($_FILES['file']['type'],$mimes)){
  // do something
} else {
  die("Sorry, mime type not allowed");
}

if you wished you could add a further check if mime is returned as text/plain you could run a preg_match to make sure it has enough commas in it to be a csv.

How do I extract text that lies between parentheses (round brackets)?

A regex maybe? I think this would work...

\(([a-z]+?)\)

The imported project "C:\Microsoft.CSharp.targets" was not found

This is a global solution, not dependent on particular package or bin.

In my case, I removed Packages folder from my root directory.

Maybe it happens because of your packages are there but compiler is not finding it's reference. so remove older packages first and add new packages.

Steps to Add new packages

  • First remove, packages folder (it will be near by or one step up to your current project folder).
  • Then restart the project or solution.
  • Now, Rebuild solution file.
  • Project will get new references from nuGet package manager. And your issue will be resolved.

This is not proper solution, but I posted it here because I face same issue.

In my case, I wasn't even able to open my solution in visual studio and didn't get any help with other SO answers.

How do I vertically center text with CSS?

Try the following code:

display: table-cell;
vertical-align: middle;

_x000D_
_x000D_
div {_x000D_
  height: 80%;_x000D_
  width: 100%;_x000D_
  text-align: center;_x000D_
  display: table-cell;_x000D_
  vertical-align: middle;_x000D_
  background: #4CAF50;_x000D_
  color: #fff;_x000D_
  font-size: 50px;_x000D_
  font-style: italic;_x000D_
}
_x000D_
<div>_x000D_
  Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using Git with Visual Studio

In Jan 2013, Microsoft announced that they are adding full Git support into all their ALM products. They have published a plugin for Visual Studio 2012 that adds Git source control integration.

Alternatively, there is a project called Git Extensions that includes add-ins for Visual Studio 2005, 2008, 2010 and 2012, as well as Windows Explorer integration. It's regularly updated and having used it on a couple of projects, I've found it very useful.

Another option is Git Source Control Provider.

Difference between [routerLink] and routerLink

Assume that you have

const appRoutes: Routes = [
  {path: 'recipes', component: RecipesComponent }
];

<a routerLink ="recipes">Recipes</a>

It means that clicking Recipes hyperlink will jump to http://localhost:4200/recipes

Assume that the parameter is 1

<a [routerLink] = "['/recipes', parameter]"></a>

It means that passing dynamic parameter, 1 to the link, then you navigate to http://localhost:4200/recipes/1

Set folder browser dialog start location

fldrDialog.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)

"If the SelectedPath property is set before showing the dialog box, the folder with this path will be the selected folder, as long as SelectedPath is set to an absolute path that is a subfolder of RootFolder (or more accurately, points to a subfolder of the shell namespace represented by RootFolder)."

MSDN - SelectedPath

"The GetFolderPath method returns the locations associated with this enumeration. The locations of these folders can have different values on different operating systems, the user can change some of the locations, and the locations are localized."

Re: Desktop vs DesktopDirectory

Desktop

"The logical Desktop rather than the physical file system location."

DesktopDirectory:

"The directory used to physically store file objects on the desktop. Do not confuse this directory with the desktop folder itself, which is a virtual folder."

MSDN - Special Folder Enum

MSDN - GetFolderPath

Sql Server string to date conversion

Run this through your query processor. It formats dates and/or times like so and one of these should give you what you're looking for. It wont be hard to adapt:

Declare @d datetime
select @d = getdate()

select @d as OriginalDate,
convert(varchar,@d,100) as ConvertedDate,
100 as FormatValue,
'mon dd yyyy hh:miAM (or PM)' as OutputFormat
union all
select @d,convert(varchar,@d,101),101,'mm/dd/yy'
union all
select @d,convert(varchar,@d,102),102,'yy.mm.dd'
union all
select @d,convert(varchar,@d,103),103,'dd/mm/yy'
union all
select @d,convert(varchar,@d,104),104,'dd.mm.yy'
union all
select @d,convert(varchar,@d,105),105,'dd-mm-yy'
union all
select @d,convert(varchar,@d,106),106,'dd mon yy'
union all
select @d,convert(varchar,@d,107),107,'Mon dd, yy'
union all
select @d,convert(varchar,@d,108),108,'hh:mm:ss'
union all
select @d,convert(varchar,@d,109),109,'mon dd yyyy hh:mi:ss:mmmAM (or PM)'
union all
select @d,convert(varchar,@d,110),110,'mm-dd-yy'
union all
select @d,convert(varchar,@d,111),111,'yy/mm/dd'
union all
select @d,convert(varchar,@d,12),12,'yymmdd'
union all
select @d,convert(varchar,@d,112),112,'yyyymmdd'
union all
select @d,convert(varchar,@d,113),113,'dd mon yyyy hh:mm:ss:mmm(24h)'
union all
select @d,convert(varchar,@d,114),114,'hh:mi:ss:mmm(24h)'
union all
select @d,convert(varchar,@d,120),120,'yyyy-mm-dd hh:mi:ss(24h)'
union all
select @d,convert(varchar,@d,121),121,'yyyy-mm-dd hh:mi:ss.mmm(24h)'
union all
select @d,convert(varchar,@d,126),126,'yyyy-mm-dd Thh:mm:ss:mmm(no spaces)'

Create space at the beginning of a UITextField

To create padding view for UITextField in Swift 5

func txtPaddingVw(txt:UITextField) {
    let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 5, height: 5))
    txt.leftViewMode = .always
    txt.leftView = paddingView
}

Git asks for username every time I push

Changing the cloned repo works:

git remote set-url origin [email protected]:gitusername/projectname.git

Using cached credentials works, and setting the timeout period makes things less annoying. If you use the Windows credential helper, that should be the easiest method (especially if SSH is blocked).

What's the difference between ISO 8601 and RFC 3339 Date Formats?

RFC 3339 is mostly a profile of ISO 8601, but is actually inconsistent with it in borrowing the "-00:00" timezone specification from RFC 2822. This is described in the Wikipedia article.

How to restore SQL Server 2014 backup in SQL Server 2008

It is a pretty old post, but I just had to do it today. I just right-clicked database from SQL2014 and selected Export Data option and that helped me to move data to SQL2012.

$(document).click() not working correctly on iPhone. jquery

Change this:

$(document).click( function () {

To this

$(document).on('click touchstart', function () {

Maybe this solution don't fit on your work and like described on the replies this is not the best solution to apply. Please, check another fixes from another users.

Saving an Object (Data persistence)

I think it's a pretty strong assumption to assume that the object is a class. What if it's not a class? There's also the assumption that the object was not defined in the interpreter. What if it was defined in the interpreter? Also, what if the attributes were added dynamically? When some python objects have attributes added to their __dict__ after creation, pickle doesn't respect the addition of those attributes (i.e. it 'forgets' they were added -- because pickle serializes by reference to the object definition).

In all these cases, pickle and cPickle can fail you horribly.

If you are looking to save an object (arbitrarily created), where you have attributes (either added in the object definition, or afterward)… your best bet is to use dill, which can serialize almost anything in python.

We start with a class…

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> class Company:
...     pass
... 
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> with open('company.pkl', 'wb') as f:
...     pickle.dump(company1, f, pickle.HIGHEST_PROTOCOL)
... 
>>> 

Now shut down, and restart...

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('company.pkl', 'rb') as f:
...     company1 = pickle.load(f)
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1378, in load
    return Unpickler(file).load()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1090, in load_global
    klass = self.find_class(module, name)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1126, in find_class
    klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'Company'
>>> 

Oops… pickle can't handle it. Let's try dill. We'll throw in another object type (a lambda) for good measure.

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill       
>>> class Company:
...     pass
... 
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> 
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>> 
>>> with open('company_dill.pkl', 'wb') as f:
...     dill.dump(company1, f)
...     dill.dump(company2, f)
... 
>>> 

And now read the file.

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> with open('company_dill.pkl', 'rb') as f:
...     company1 = dill.load(f)
...     company2 = dill.load(f)
... 
>>> company1 
<__main__.Company instance at 0x107909128>
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>>    

It works. The reason pickle fails, and dill doesn't, is that dill treats __main__ like a module (for the most part), and also can pickle class definitions instead of pickling by reference (like pickle does). The reason dill can pickle a lambda is that it gives it a name… then pickling magic can happen.

Actually, there's an easier way to save all these objects, especially if you have a lot of objects you've created. Just dump the whole python session, and come back to it later.

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> class Company:
...     pass
... 
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> 
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>> 
>>> dill.dump_session('dill.pkl')
>>> 

Now shut down your computer, go enjoy an espresso or whatever, and come back later...

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> dill.load_session('dill.pkl')
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>> company2
<function <lambda> at 0x1065f2938>

The only major drawback is that dill is not part of the python standard library. So if you can't install a python package on your server, then you can't use it.

However, if you are able to install python packages on your system, you can get the latest dill with git+https://github.com/uqfoundation/dill.git@master#egg=dill. And you can get the latest released version with pip install dill.

What is the best practice for creating a favicon on a web site?

I used https://iconifier.net I uploaded my image, downloaded images zip file, added images to my server, followed the directions on the site including adding the links to my index.html and it worked. My favicon now shows on my iPhone in Safari when 'Add to home screen'

Using an array as needles in strpos

@Dave an updated snippet from http://www.php.net/manual/en/function.strpos.php#107351

function strposa($haystack, $needles=array(), $offset=0) {
        $chr = array();
        foreach($needles as $needle) {
                $res = strpos($haystack, $needle, $offset);
                if ($res !== false) $chr[$needle] = $res;
        }
        if(empty($chr)) return false;
        return min($chr);
}

How to use:

$string = 'Whis string contains word "cheese" and "tea".';
$array  = array('burger', 'melon', 'cheese', 'milk');

if (strposa($string, $array, 1)) {
    echo 'true';
} else {
    echo 'false';
}

will return true, because of array "cheese".

Update: Improved code with stop when the first of the needles is found:

function strposa($haystack, $needle, $offset=0) {
    if(!is_array($needle)) $needle = array($needle);
    foreach($needle as $query) {
        if(strpos($haystack, $query, $offset) !== false) return true; // stop on first true result
    }
    return false;
}
$string = 'Whis string contains word "cheese" and "tea".';
$array  = array('burger', 'melon', 'cheese', 'milk');
var_dump(strposa($string, $array)); // will return true, since "cheese" has been found

The meaning of NoInitialContextException error

make sure dependencies for jetty naming and jetty plus are included (not just provided scope). This fixed it for me.

How to store a command in a variable in a shell script?

I tried various different methods:

printexec() {
  printf -- "\033[1;37m$\033[0m"
  printf -- " %q" "$@"
  printf -- "\n"
  eval -- "$@"
  eval -- "$*"
  "$@"
  "$*"
}

Output:

$ printexec echo  -e "foo\n" bar
$ echo -e foo\\n bar
foon bar
foon bar
foo
 bar
bash: echo -e foo\n bar: command not found

As you can see, only the third one, "$@" gave the correct result.

Can an html element have multiple ids?

No, you should use nested DIVs if you want to head down that path. Besides, even if you could, imagine the confusion it would cause when you run document.getElementByID(). What ID is it going to grab if there are multiple ones?

On a slightly related topic, you can add multiple classes to a DIV. See Eric Myers discussion at,

http://meyerweb.com/eric/articles/webrev/199802a.html

Remove the last three characters from a string

myString.Remove(myString.Length-3);

Inline instantiation of a constant List

const is for compile-time constants. You could just make it static readonly, but that would only apply to the METRICS variable itself (which should typically be Metrics instead, by .NET naming conventions). It wouldn't make the list immutable - so someone could call METRICS.Add("shouldn't be here");

You may want to use a ReadOnlyCollection<T> to wrap it. For example:

public static readonly IList<String> Metrics = new ReadOnlyCollection<string>
    (new List<String> { 
         SourceFile.LoC, SourceFile.McCabe, SourceFile.NoM,
         SourceFile.NoA, SourceFile.FanOut, SourceFile.FanIn, 
         SourceFile.Par, SourceFile.Ndc, SourceFile.Calls });

ReadOnlyCollection<T> just wraps a potentially-mutable collection, but as nothing else will have access to the List<T> afterwards, you can regard the overall collection as immutable.

(The capitalization here is mostly guesswork - using fuller names would make them clearer, IMO.)

Whether you declare it as IList<string>, IEnumerable<string>, ReadOnlyCollection<string> or something else is up to you... if you expect that it should only be treated as a sequence, then IEnumerable<string> would probably be most appropriate. If the order matters and you want people to be able to access it by index, IList<T> may be appropriate. If you want to make the immutability apparent, declaring it as ReadOnlyCollection<T> could be handy - but inflexible.

Find Item in ObservableCollection without using a loop

Here comes Linq:

var listItem = list.Single(i => i.Title == title);

It throws an exception if there's no item matching the predicate. Alternatively, there's SingleOrDefault.

If you want a collection of items matching the title, there's:

var listItems = list.Where(i => i.Title ==  title);

Spark: Add column to dataframe conditionally

Try withColumn with the function when as follows:

val sqlContext = new SQLContext(sc)
import sqlContext.implicits._ // for `toDF` and $""
import org.apache.spark.sql.functions._ // for `when`

val df = sc.parallelize(Seq((4, "blah", 2), (2, "", 3), (56, "foo", 3), (100, null, 5)))
    .toDF("A", "B", "C")

val newDf = df.withColumn("D", when($"B".isNull or $"B" === "", 0).otherwise(1))

newDf.show() shows

+---+----+---+---+
|  A|   B|  C|  D|
+---+----+---+---+
|  4|blah|  2|  1|
|  2|    |  3|  0|
| 56| foo|  3|  1|
|100|null|  5|  0|
+---+----+---+---+

I added the (100, null, 5) row for testing the isNull case.

I tried this code with Spark 1.6.0 but as commented in the code of when, it works on the versions after 1.4.0.

Jquery insert new row into table at a certain index

Note:

$('#my_table > tbody:last').append(newRow); // this will add new row inside tbody

$("table#myTable tr").last().after(newRow);  // this will add new row outside tbody 
                                             //i.e. between thead and tbody
                                             //.before() will also work similar

How to get the server path to the web directory in Symfony2 from inside the controller?

To access the root directory from outside the controller you can simply inject %kernel.root_dir% as an argument in your services configuration.

service_name:
    class: Namespace\Bundle\etc
    arguments: ['%kernel.root_dir%']

Then you can get the web root in the class constructor:

public function __construct($rootDir)
{
    $this->webRoot = realpath($rootDir . '/../web');
}

Programmatically scroll a UIScrollView

scrollView.setContentOffset(CGPoint(x: y, y: x), animated: true)

Connection pooling options with JDBC: DBCP vs C3P0

c3p0 is good when we are using mutithreading projects. In our projects we used simultaneously multiple thread executions by using DBCP, then we got connection timeout if we used more thread executions. So we went with c3p0 configuration.

Why do I need to override the equals and hashCode methods in Java?

hashCode() :

If you only override the hash-code method nothing happens, because it always returns a new hashCode for each object as an Object class.

equals() :

If you only override the equals method, if a.equals(b) is true it means the hashCode of a and b must be the same but that does not happen since you did not override the hashCode method.

Note : hashCode() method of Object class always returns a new hashCode for each object.

So when you need to use your object in the hashing based collection, you must override both equals() and hashCode().

How to output loop.counter in python jinja template?

if you are using django use forloop.counter instead of loop.counter

<ul>
{% for user in userlist %}
  <li>
      {{ user }} {{forloop.counter}}
  </li>
      {% if forloop.counter == 1 %}
          This is the First user
      {% endif %}
{% endfor %}
</ul>

TypeError: window.initMap is not a function

I have been struggling for several days with this very popular in the last few months issue - "initMap is not a function".

Those two threads helped me:

  1. How to make a callback to Google Maps init in separate files of a web app

  2. Defer attribute doesn't work with Google Maps API?

Why does the map open sometimes and sometimes not. It depends on several factors like speed of connection, environment, etc. Because the initialization function sometimes runs after the google maps API kicks in, that's why the map is not displayed and the browser console throws an error. For me removing only the async attribute fixed the issue. The defer attribute stays.

If async is present: The script is executed asynchronously with the rest of the page (the script will be executed while the page continues the parsing) If async is not present and defer is present: The script is executed when the page has finished parsing If neither async or defer is present: The script is fetched and executed immediately, before the browser continues parsing the page Source - http://www.w3schools.com/tags/att_script_defer.asp

Hope that helps. Cheers.

How can I delete a service in Windows?

Use the SC command, like this (you need to be on a command prompt to execute the commands in this post):

SC STOP shortservicename
SC DELETE shortservicename

Note: You need to run the command prompt as an administrator, not just logged in as the administrator, but also with administrative rights. If you get errors above about not having the necessary access rights to stop and/or delete the service, run the command prompt as an administrator. You can do this by searching for the command prompt on your start menu and then right-clicking and selecting "Run as administrator". Note to PowerShell users: sc is aliased to set-content. So sc delete service will actually create a file called delete with the content service. To do this in Powershell, use sc.exe delete service instead


If you need to find the short service name of a service, use the following command to generate a text file containing a list of services and their statuses:

SC QUERY state= all >"C:\Service List.txt"

For a more concise list, execute this command:

SC QUERY state= all | FIND "_NAME"

The short service name will be listed just above the display name, like this:

SERVICE_NAME: MyService
DISPLAY_NAME: My Special Service

And thus to delete that service:

SC STOP MyService
SC DELETE MyService

Jquery, Clear / Empty all contents of tbody element?

Example for Remove table header or table body with jquery

_x000D_
_x000D_
function removeTableHeader(){_x000D_
  $('#myTableId thead').empty();_x000D_
}_x000D_
_x000D_
function removeTableBody(){_x000D_
    $('#myTableId tbody').empty();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table id='myTableId'  border="1">_x000D_
  <thead>_x000D_
    <th>1st heading</th>_x000D_
    <th>2nd heading</th>_x000D_
    <th>3rd heading</th>_x000D_
  </thead>  _x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>1st content</td>_x000D_
      <td>1st content</td>_x000D_
      <td>1st content</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>2nd content</td>_x000D_
      <td>2nd content</td>_x000D_
      <td>2nd content</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>3rd content</td>_x000D_
      <td>3rd content</td>_x000D_
      <td>3rd content</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
<br/>_x000D_
<form>_x000D_
  <input type='button' value='Remove Table Header' onclick='removeTableHeader()'/>_x000D_
  <input type='button' value='Remove Table Body' onclick='removeTableBody()'/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Formatting dates on X axis in ggplot2

Can you use date as a factor?

Yes, but you probably shouldn't.

...or should you use as.Date on a date column?

Yes.

Which leads us to this:

library(scales)
df$Month <- as.Date(df$Month)
ggplot(df, aes(x = Month, y = AvgVisits)) + 
  geom_bar(stat = "identity") +
  theme_bw() +
  labs(x = "Month", y = "Average Visits per User") +
  scale_x_date(labels = date_format("%m-%Y"))

enter image description here

in which I've added stat = "identity" to your geom_bar call.

In addition, the message about the binwidth wasn't an error. An error will actually say "Error" in it, and similarly a warning will always say "Warning" in it. Otherwise it's just a message.

Combining two lists and removing duplicates, without removing duplicates in original list

You can also combine RichieHindle's and Ned Batchelder's responses for an average-case O(m+n) algorithm that preserves order:

first_list = [1, 2, 2, 5]
second_list = [2, 5, 7, 9]

fs = set(first_list)
resulting_list = first_list + [x for x in second_list if x not in fs]

assert(resulting_list == [1, 2, 2, 5, 7, 9])

Note that x in s has a worst-case complexity of O(m), so the worst-case complexity of this code is still O(m*n).

How to redirect to action from JavaScript method?

Youcan either send a Ajax request to server or use window.location to that url.

If two cells match, return value from third

=IF(ISNA(INDEX(B:B,MATCH(C2,A:A,0))),"",INDEX(B:B,MATCH(C2,A:A,0)))

Will return the answer you want and also remove the #N/A result that would appear if you couldn't find a result due to it not appearing in your lookup list.

Ross

How to set top-left alignment for UILabel for iOS application?

you can also just change your UILabel to UITextView, because they basically do the same thing except the advantage of UITextView is that text is automatically aligned to the top left

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

Git - push current branch shortcut

The simplest way: run git push -u origin feature/123-sandbox-tests once. That pushes the branch the way you're used to doing it and also sets the upstream tracking info in your local config. After that, you can just git push to push tracked branches to their upstream remote(s).

You can also do this in the config yourself by setting branch.<branch name>.merge to the remote branch name (in your case the same as the local name) and optionally, branch.<branch name>.remote to the name of the remote you want to push to (defaults to origin). If you look in your config, there's most likely already one of these set for master, so you can follow that example.

Finally, make sure you consider the push.default setting. It defaults to "matching", which can have undesired and unexpected results. Most people I know find "upstream" more intuitive, which pushes only the current branch.

Details on each of these settings can be found in the git-config man page.

On second thought, on re-reading your question, I think you know all this. I think what you're actually looking for doesn't exist. How about a bash function something like (untested):

function pushCurrent {
  git config push.default upstream
  git push
  git config push.default matching
}

Doctrine 2: Update query with query builder

With a small change, it worked fine for me

$qb=$this->dm->createQueryBuilder('AppBundle:CSSDInstrument')
               ->update()
               ->field('status')->set($status)
               ->field('id')->equals($instrumentId)
               ->getQuery()
               ->execute();

How to see the values of a table variable at debug time in T-SQL?

I have come to the conclusion that this is not possible without any plugins.

Calling an API from SQL Server stored procedure

I think it would be easier using this CLR Stored procedure SQL-APIConsumer:

 exec [dbo].[APICaller_POST]
     @URL = 'http://localhost:5000/api/auth/login'
    ,@BodyJson = '{"Username":"gdiaz","Password":"password"}'

It has multiple procedures that allows you calling API that required a parameters and even passing multiples headers and tokens authentications.

enter image description here

enter image description here

Get domain name

I know this is old. I just wanted to dump this here for anyone that was looking for an answer to getting a domain name. This is in coordination with Peter's answer. There "is" a bug as stated by Rich. But, you can always make a simple workaround for that. The way I can tell if they are still on the domain or not is by pinging the domain name. If it responds, continue on with whatever it was that I needed the domain for. If it fails, I drop out and go into "offline" mode. Simple string method.

 string GetDomainName()
    {
        string _domain = IPGlobalProperties.GetIPGlobalProperties().DomainName;

        Ping ping = new Ping();

        try
        {
            PingReply reply = ping.Send(_domain);

            if (reply.Status == IPStatus.Success)
            {
                return _domain;
            }
            else
            {
                return reply.Status.ToString();
            }
        }
        catch (PingException pExp)
        {
            if (pExp.InnerException.ToString() == "No such host is known")
            {
                return "Network not detected!";
            }

            return "Ping Exception";
        }
    }

MySQL > Table doesn't exist. But it does (or it should)

Go to :xampp\mysql\data\dbname
inside dbname have tablename.frm and tablename.ibd file.
remove it and restart mysql and try again.

A transport-level error has occurred when receiving results from the server

I faced the same issue recently, but i was not able to get answer in google. So thought of sharing it here, so that it can help someone in future.

Error:

While executing query the query will provide few output then it will throw below error.

"Transport level error has occurred when receiving output from server(TCP:provider,error:0- specified network name is no longer available"

Solution:

  1. Check the provider of that linked server
  2. In that provider properties ,Enable "Allow inprocess" option for that particular provider to fix the issue.

Update .NET web service to use TLS 1.2

if you're using .Net earlier than 4.5 you wont have Tls12 in the enum so state is explicitly mentioned here

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

Do AJAX requests retain PHP Session info?

One thing to watch out for though, particularly if you are using a framework, is to check if the application is regenerating session ids between requests - anything that depends explicitly on the session id will run into problems, although obviously the rest of the data in the session will unaffected.

If the application is regenerating session ids like this then you can end up with a situation where an ajax request in effect invalidates / replaces the session id in the requesting page.

Getting values from query string in an url using AngularJS $location

If your $location.search() is not working, then make sure you have the following:

1) html5Mode(true) is configured in app's module config

appModule.config(['$locationProvider', function($locationProvider) {
   $locationProvider.html5Mode(true);
}]);

2) <base href="/"> is present in your HTML

<head>
  <base href="/">
  ...
</head>

References:

  1. base href="/"
  2. html5Mode

How to find out which processes are using swap space in Linux?

I suppose you could get a good guess by running top and looking for active processes using a lot of memory. Doing this programatically is harder---just look at the endless debates about the Linux OOM killer heuristics.

Swapping is a function of having more memory in active use than is installed, so it is usually hard to blame it on a single process. If it is an ongoing problem, the best solution is to install more memory, or make other systemic changes.

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

When I used policy before I set the default authentication scheme into it as well. I had modified the DefaultPolicy so it was slightly different. However the same should work for add policy as well.

services.AddAuthorization(options =>
        {
            options.AddPolicy(DefaultAuthorizedPolicy, policy =>
            {
                policy.Requirements.Add(new TokenAuthRequirement());
                policy.AuthenticationSchemes = new List<string>()
                                {
                                    CookieAuthenticationDefaults.AuthenticationScheme
                                }
            });
        });

Do take into consideration that by Default AuthenticationSchemes property uses a read only list. I think it would be better to implement that instead of List as well.

Encode/Decode URLs in C++

I know the question asks for a C++ method, but for those who might need it, I came up with a very short function in plain C to encode a string. It doesn't create a new string, rather it alters the existing one, meaning that it must have enough size to hold the new string. Very easy to keep up.

void urlEncode(char *string)
{
    char charToEncode;
    int posToEncode;
    while (((posToEncode=strspn(string,"1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_.~"))!=0) &&(posToEncode<strlen(string)))
    {
        charToEncode=string[posToEncode];
        memmove(string+posToEncode+3,string+posToEncode+1,strlen(string+posToEncode));
        string[posToEncode]='%';
        string[posToEncode+1]="0123456789ABCDEF"[charToEncode>>4];
        string[posToEncode+2]="0123456789ABCDEF"[charToEncode&0xf];
        string+=posToEncode+3;
    }
}

Body of Http.DELETE request in Angular2

In Angular 5, I had to use the request method instead of delete to send a body. The documentation for the delete method does not include body, but it is included in the request method.

import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';

this.http.request('DELETE', url, {
    headers: new HttpHeaders({
        'Content-Type': 'application/json',
    }),
    body: { foo: bar }
});

What is the maximum float in Python?

For all practical purposes, and with no import at all, one can use:

x = float("inf")

More detail on this related question: How can I represent an infinite number in Python?

C# Iterating through an enum? (Indexing a System.Array)

What about using a foreach loop, maybe you could work with that?

  int i = 0;
  foreach (var o in values)
  {
    print(names[i], o);
    i++;
  }

something like that perhaps?

Escape a string for a sed replace pattern

don't forget all the pleasure that occur with the shell limitation around " and '

so (in ksh)

Var=">New version of \"content' here <"
printf "%s" "${Var}" | sed "s/[&\/\\\\*\\"']/\\&/g' | read -r EscVar

echo "Here is your \"text\" to change" | sed "s/text/${EscVar}/g"

Excel - Button to go to a certain sheet

Alternately, if you are using a Macro Enabled workbook:

Add any control at all from the Developer -> Insert (Probably a button)

When it asks what Macro to assign, choose New. For the code for the generated module enter something like:

Thisworkbook.Sheets("Sheet Name").Activate

However, if you are not using Macros in your work book. Ooo's approach is definitely surperior as hyperlinks will work with no need to trust the document.

how to make a specific text on TextView BOLD

Your String resource

<resources>
   <string name="your_string_resource_name">This is normal text<![CDATA[<b> but this is bold </b>]]> and <![CDATA[<u> but this is underline text</u>]]></string>
</resources> 

your java class

yourtextView.setText(getString(R.string.your_string_resource_name));

How can I print message in Makefile?

$(info your_text) : Information. This doesn't stop the execution.

$(warning your_text) : Warning. This shows the text as a warning.

$(error your_text) : Fatal Error. This will stop the execution.

How to get selected value of a dropdown menu in ReactJS

As for front-end developer many time we are dealing with the forms in which we have to handle the dropdowns and we have to use the value of selected dropdown to perform some action or the send the value on the Server, it's very simple you have to write the simple dropdown in HTML just put the one onChange method for the selection in the dropdown whenever user change the value of dropdown set that value to state so you can easily access it in AvFeaturedPlayList 1 remember you will always get the result as option value and not the dropdown text which is displayed on the screen

import React, { Component } from "react";
import { Server } from "net";

class InlineStyle extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectValue: ""
    };

    this.handleDropdownChange = this.handleDropdownChange.bind(this);
  }

  handleDropdownChange(e) {
    this.setState({ selectValue: e.target.value });
  }

  render() {
    return (
      <div>
        <div>
          <div>
            <select id="dropdown" onChange={this.handleDropdownChange}>
              <option value="N/A">N/A</option>
              <option value="1">1</option>
              <option value="2">2</option>
              <option value="3">3</option>
              <option value="4">4</option>
            </select>
          </div>

          <div>Selected value is : {this.state.selectValue}</div>
        </div>
      </div>
    );
  }
}
export default InlineStyle;

Array[n] vs Array[10] - Initializing array with variable vs real number

In C++, variable length arrays are not legal. G++ allows this as an "extension" (because C allows it), so in G++ (without being -pedantic about following the C++ standard), you can do:

int n = 10;
double a[n]; // Legal in g++ (with extensions), illegal in proper C++

If you want a "variable length array" (better called a "dynamically sized array" in C++, since proper variable length arrays aren't allowed), you either have to dynamically allocate memory yourself:

int n = 10;
double* a = new double[n]; // Don't forget to delete [] a; when you're done!

Or, better yet, use a standard container:

int n = 10;
std::vector<double> a(n); // Don't forget to #include <vector>

If you still want a proper array, you can use a constant, not a variable, when creating it:

const int n = 10;
double a[n]; // now valid, since n isn't a variable (it's a compile time constant)

Similarly, if you want to get the size from a function in C++11, you can use a constexpr:

constexpr int n()
{
    return 10;
}

double a[n()]; // n() is a compile time constant expression

How do I drop table variables in SQL-Server? Should I even do this?

if somebody else comes across this... and you really need to drop it like while in a loop, you can just delete all from the table variable:

DELETE FROM @tableVariableName

How to use GROUP BY to concatenate strings in MySQL?

SELECT id, GROUP_CONCAT(CAST(name as CHAR)) FROM table GROUP BY id

Will give you a comma-delimited string

No 'Access-Control-Allow-Origin' header in Angular 2 app

I have spent lot of time for solution and got it worked finally by making changes in the server side.Check the website https://docs.microsoft.com/en-us/aspnet/core/security/cors

It worked for me when I enabled corse in the server side.We were using Asp.Net core in API and the below code worked

1) Added Addcors in ConfigureServices of Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors();
        services.AddMvc();
    }

2) Added UseCors in Configure method as below:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseCors(builder =>builder.AllowAnyOrigin());
        app.UseMvc();
    }

How do relative file paths work in Eclipse?

Paraphrasing from http://java.sun.com/javase/6/docs/api/java/io/File.html:

The classes under java.io resolve relative pathnames against the current user directory, which is typically the directory in which the virtual machine was started.

Eclipse sets the working directory to the top-level project folder.

How to create an array for JSON using PHP?

Best way that you should go every time for creating json in php is to first convert values in ASSOCIATIVE array.

After that just simply encode using json_encode($associativeArray). I think it is the best way to create json in php because whenever we are fetching result form sql query in php most of the time we got values using fetch_assoc function, which also return one associative array.

$associativeArray = array();
$associativeArray ['FirstValue'] = 'FirstValue';

... etc.

After that.

json_encode($associativeArray);

What do column flags mean in MySQL Workbench?

This exact question is answered on mySql workbench-faq:

Hover over an acronym to view a description, and see the Section 8.1.11.2, “The Columns Tab” and MySQL CREATE TABLE documentation for additional details.

That means hover over an acronym in the mySql Workbench table editor.

Section 8.1.11.2, “The Columns Tab”

How to set the style -webkit-transform dynamically using JavaScript?

Try using

img.style.webkitTransform = "rotate(60deg)"

Convert.ToDateTime: how to set format

DateTime doesn't have a format. the format only applies when you're turning a DateTime into a string, which happens implicitly you show the value on a form, web page, etc.

Look at where you're displaying the DateTime and set the format there (or amend your question if you need additional guidance).

Creating a Zoom Effect on an image on hover using CSS?

_x000D_
_x000D_
    .img-wrap:hover img {_x000D_
        transform: scale(0.8);_x000D_
    }_x000D_
    .img-wrap img {_x000D_
        display: block;_x000D_
        transition: all 0.3s ease 0s;_x000D_
        width: 100%;_x000D_
    }
_x000D_
    <div class="img-wrap">_x000D_
    <img src="http://www.sampleimages/images.jpg"/> // Your image_x000D_
    </div>
_x000D_
_x000D_
_x000D_

This code is only for zoom-out effect.Set the div "img-wrap" according to your styles and insert the above style results zoom-out effect.For zoom-in effect you must increase the scale value(eg: for zoom-in,use transform: scale(1.3);

Inserting the iframe into react component

If you don't want to use dangerouslySetInnerHTML then you can use the below mentioned solution

var Iframe = React.createClass({     
  render: function() {
    return(         
      <div>          
        <iframe src={this.props.src} height={this.props.height} width={this.props.width}/>         
      </div>
    )
  }
});

ReactDOM.render(
  <Iframe src="http://plnkr.co/" height="500" width="500"/>,
  document.getElementById('example')
);

here live demo is available Demo

Convert a dta file to csv without Stata software

For those who have Stata (even though the asker does not) you can use this:

outsheet produces a tab-delimited file so you need to specify the comma option like below

outsheet [varlist] using file.csv , comma

also, if you want to remove labels (which are included by default

outsheet [varlist] using file.csv, comma nolabel

hat tip to:

http://www.ats.ucla.edu/stat/stata/faq/outsheet.htm

How to create Windows EventLog source from command line?

Or just use the command line command:

Eventcreate

CSS: 100% font size - 100% of what?

Sorry if I'm late to the party, but in your edit you make a remark about font: 100% Georgia, which the other answers haven't responded to.

There is a difference between font: 100% Georgia and font-size:100%; font-family:'Georgia'. If that was all the shorthand method did, the font-size part would be meaningless. But it also sets a lot of properties to their default values: the line height becomes normal (or around 1.2), ditto for the style (non-italic) and weight (non-bold).

That's all. The other answers already mentioned everything else there was to mention.

How to keep a Python script output window open?

I had a similar problem. With Notepad++ I used to use the command : C:\Python27\python.exe "$(FULL_CURRENT_PATH)" which closed the cmd window immediately after the code terminated.
Now I am using cmd /k c:\Python27\python.exe "$(FULL_CURRENT_PATH)" which keeps the cmd window open.

What exactly does a jar file contain?

A .jar file contains compiled code (*.class files) and other data/resources related to that code. It enables you to bundle multiple files into a single archive file. It also contains metadata. Since it is a zip file it is capable of compressing the data that you put into it.

Couple of things i found useful.

http://www.skylit.com/javamethods/faqs/createjar.html

http://docs.oracle.com/javase/tutorial/deployment/jar/basicsindex.html

The book OSGi in practice defines JAR files as, "JARs are archive files based on the ZIP file format, allowing many files to be aggregated into a single file. Typically the files contained in the archive are a mixture of compiled Java class files and resource files such as images and documents. Additionally the specification defines a standard location within a JAR archive for metadata — the META-INF folder — and several standard file names and formats within that directly, most important of which is the MANIFEST.MF file."

How to deal with missing src/test/java source folder in Android/Maven project?

I realise this annoying thing too since latest m2e-android plugin upgrade (version 0.4.2), it happens in both new project creation and existing project import (if you don't use src/test/java).

It looks like m2e-android (or perhaps m2e) now always trying to add src/test/java as a source folder, regardless of whether it is actually existed in your project directory, in the .classpath file:

<classpathentry kind="src" output="bin/classes" path="src/test/java">
  <attributes>
    <attribute name="maven.pomderived" value="true"/>
  </attributes>
</classpathentry>

As it is already added in the project metadata file, so if you trying to add the source folder via Eclipse, Eclipse will complain that the classpathentry is already exist:

enter image description here

There are several ways to fix it, the easiest is manually create src/test/java directory in the file system, then refresh your project by press F5 and run Maven -> Update Project (Right click project, choose Maven -> Update Project...), this should fix the missing required source folder: 'src/test/java' error.

git push vs git push origin <branchname>

The first push should be a:

git push -u origin branchname

That would make sure:

Any future git push will, with that default policy, only push the current branch, and only if that branch has an upstream branch with the same name.
that avoid pushing all matching branches (previous default policy), where tons of test branches were pushed even though they aren't ready to be visible on the upstream repo.

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

Try:

Key = i.ToString("000000");

Personally, though, I'd see if you can't sort on the integer directly, rather than the string representation.

How can I catch all the exceptions that will be thrown through reading and writing a file?

If you want, you can add throws clauses to your methods. Then you don't have to catch checked methods right away. That way, you can catch the exceptions later (perhaps at the same time as other exceptions).

The code looks like:

public void someMethode() throws SomeCheckedException {

    //  code

}

Then later you can deal with the exceptions if you don't wanna deal with them in that method.

To catch all exceptions some block of code may throw you can do: (This will also catch Exceptions you wrote yourself)

try {

    // exceptional block of code ...

    // ...

} catch (Exception e){

    // Deal with e as you please.
    //e may be any type of exception at all.

}

The reason that works is because Exception is the base class for all exceptions. Thus any exception that may get thrown is an Exception (Uppercase 'E').

If you want to handle your own exceptions first simply add a catch block before the generic Exception one.

try{    
}catch(MyOwnException me){
}catch(Exception e){
}

Inline for loop

your list comphresnion will, work but will return list of None because append return None:

demo:

>>> a=[]
>>> [ a.append(x) for x in range(10) ]
[None, None, None, None, None, None, None, None, None, None]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

better way to use it like this:

>>> a= [ x for x in range(10) ]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Can you Run Xcode in Linux?

If you really want to use Xcode on linux you could get Virtual Box and install Hackintosh on a VM. Edit: Virtual Box Guest Additions is not supported with MacOS Movaje. You will want to use VMware

https://www.vmware.com/

https://hackintosh.com/

Why is "using namespace std;" considered bad practice?

Namespaces are to avoid naming conflicts. C++ is based on C and C has many problems with function and variable names because sometimes functions from different library clashes. So library developer started to prefix their functions with library names like the following:

foo/foo.h:

void libfoo_foo_foo_h_open(); // the name can be weird then even this one!

C++ introduced namespace to solve this problem in an easy way.

Assume you have two libraries named file and window which handles files and windows respectively and the following code:

#include <file.h>
#include <window.h>

using namespace file;
using namespace window;

void open() {
     ...
}

file.h:

namespace file {
    void open(); // What!
}

window.h:

namespace window {
    void open(); // Oh no!
}

The above code will surely and certainly fail to compile.

If you don't like type std:: (only 5 characters) you can always do this: (not a good idea in header files)

using s = std;

If you still want to use using namespace std; in your source file then you are inviting that problem and I have to ask you "What is the PURPOSE of a NAMESPACE?".

WebView and Cookies on Android

My problem is cookies are not working "within" the same session. –

Burak: I had the same problem. Enabling cookies fixed the issue.

CookieManager.getInstance().setAcceptCookie(true);

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

I liked galloglas's code, and I changed the main function so that it shows a sorted list of total size by application:

verbose = True
if __name__ == '__main__':
    mbdb = process_mbdb_file("Manifest.mbdb")
    mbdx = process_mbdx_file("Manifest.mbdx")
    sizes = {}
    for offset, fileinfo in mbdb.items():
        if offset in mbdx:
            fileinfo['fileID'] = mbdx[offset]
        else:
            fileinfo['fileID'] = "<nofileID>"
            print >> sys.stderr, "No fileID found for %s" % fileinfo_str(fileinfo)
        print fileinfo_str(fileinfo, verbose)
        if (fileinfo['mode'] & 0xE000) == 0x8000:
        sizes[fileinfo['domain']]= sizes.get(fileinfo['domain'],0) + fileinfo['filelen']
    for domain in sorted(sizes, key=sizes.get):
        print "%-60s %11d (%dMB)" % (domain, sizes[domain], int(sizes[domain]/1024/1024))

That way you can figure out what application is eating all that space.

How to create an infinite loop in Windows batch file?

A really infinite loop, counting from 1 to 10 with increment of 0.
You need infinite or more increments to reach the 10.

for /L %%n in (1,0,10) do (
  echo do stuff
  rem ** can't be leaved with a goto (hangs)
  rem ** can't be stopped with exit /b (hangs)
  rem ** can be stopped with exit
  rem ** can be stopped with a syntax error
  call :stop
)

:stop
call :__stop 2>nul

:__stop
() creates a syntax error, quits the batch

This could be useful if you need a really infinite loop, as it is much faster than a goto :loop version because a for-loop is cached completely once at startup.

Using the RUN instruction in a Dockerfile with 'source' does not work

If you're just trying to use pip to install something into the virtualenv, you can modify the PATH env to look in the virtualenv's bin folder first

ENV PATH="/path/to/venv/bin:${PATH}"

Then any pip install commands that follow in the Dockerfile will find /path/to/venv/bin/pip first and use that, which will install into that virtualenv and not the system python.

How to get values of selected items in CheckBoxList with foreach in ASP.NET C#?

string s= string.Empty

for (int i = 0; i < Chkboxlist.Items.Count; i++)

{

    if (Chkboxlist.Items[i].Selected)
    {
        s+= Chkboxlist.Items[i].Value + ";"; 
    }

}

Create Elasticsearch curl query for not null and not empty("")

You can use a bool combination query with must/must_not which gives great performance and returns all records where the field is not null and not empty.

bool must_not is like "NOT AND" which means field!="", bool must exist means its !=null.

so effectively enabling: where field1!=null and field1!=""

GET  IndexName/IndexType/_search
{
    "query": {
        "bool": {
            "must": [{
                "bool": {
                    "must_not": [{
                        "term": { "YourFieldName": ""}
                    }]
                }
            }, {
                "bool": {
                    "must": [{
                      "exists" : { "field" : "YourFieldName" }
                    }]
                }
            }]
        }   
    }
}

ElasticSearch Version:

  "version": {
    "number": "5.6.10",
    "lucene_version": "6.6.1"
  }

Setting WPF image source in code

Have you tried:

Assembly asm = Assembly.GetExecutingAssembly();
Stream iconStream = asm.GetManifestResourceStream("SomeImage.png");
BitmapImage bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = iconStream;
bitmap.EndInit();
_icon.Source = bitmap;

ORA-30926: unable to get a stable set of rows in the source tables

This is usually caused by duplicates in the query specified in USING clause. This probably means that TABLE_A is a parent table and the same ROWID is returned several times.

You could quickly solve the problem by using a DISTINCT in your query (in fact, if 'Y' is a constant value you don't even need to put it in the query).

Assuming your query is correct (don't know your tables) you could do something like this:

  MERGE INTO table_1 a
      USING 
      (SELECT distinct ta.ROWID row_id
              FROM table_1 a ,table_2 b ,table_3 c
              WHERE a.mbr = c.mbr
              AND b.head = c.head
              AND b.type_of_action <> '6') src
              ON ( a.ROWID = src.row_id )
  WHEN MATCHED THEN UPDATE SET in_correct = 'Y';

How do I delete unpushed git commits?

For your reference, I believe you can "hard cut" commits out of your current branch not only with git reset --hard, but also with the following command:

git checkout -B <branch-name> <SHA>

In fact, if you don't care about checking out, you can set the branch to whatever you want with:

git branch -f <branch-name> <SHA>

This would be a programmatic way to remove commits from a branch, for instance, in order to copy new commits to it (using rebase).

Suppose you have a branch that is disconnected from master because you have taken sources from some other location and dumped it into the branch.

You now have a branch in which you have applied changes, let's call it "topic".

You will now create a duplicate of your topic branch and then rebase it onto the source code dump that is sitting in branch "dump":

git branch topic_duplicate topic
git rebase --onto dump master topic_duplicate

Now your changes are reapplied in branch topic_duplicate based on the starting point of "dump" but only the commits that have happened since "master". So your changes since master are now reapplied on top of "dump" but the result ends up in "topic_duplicate".

You could then replace "dump" with "topic_duplicate" by doing:

git branch -f dump topic_duplicate
git branch -D topic_duplicate

Or with

git branch -M topic_duplicate dump

Or just by discarding the dump

git branch -D dump

Perhaps you could also just cherry-pick after clearing the current "topic_duplicate".

What I am trying to say is that if you want to update the current "duplicate" branch based off of a different ancestor you must first delete the previously "cherrypicked" commits by doing a git reset --hard <last-commit-to-retain> or git branch -f topic_duplicate <last-commit-to-retain> and then copying the other commits over (from the main topic branch) by either rebasing or cherry-picking.

Rebasing only works on a branch that already has the commits, so you need to duplicate your topic branch each time you want to do that.

Cherrypicking is much easier:

git cherry-pick master..topic

So the entire sequence will come down to:

git reset --hard <latest-commit-to-keep>
git cherry-pick master..topic

When your topic-duplicate branch has been checked out. That would remove previously-cherry-picked commits from the current duplicate, and just re-apply all of the changes happening in "topic" on top of your current "dump" (different ancestor). It seems a reasonably convenient way to base your development on the "real" upstream master while using a different "downstream" master to check whether your local changes also still apply to that. Alternatively you could just generate a diff and then apply it outside of any Git source tree. But in this way you can keep an up-to-date modified (patched) version that is based on your distribution's version while your actual development is against the real upstream master.

So just to demonstrate:

  • reset will make your branch point to a different commit (--hard also checks out the previous commit, --soft keeps added files in the index (that would be committed if you commit again) and the default (--mixed) will not check out the previous commit (wiping your local changes) but it will clear the index (nothing has been added for commit yet)
  • you can just force a branch to point to a different commit
  • you can do so while immediately checking out that commit as well
  • rebasing works on commits present in your current branch
  • cherry-picking means to copy over from a different branch

Hope this helps someone. I was meaning to rewrite this, but I cannot manage now. Regards.

Insert NULL value into INT column

Does the column allow null?

Seems to work. Just tested with phpMyAdmin, the column is of type int that allows nulls:

INSERT INTO `database`.`table` (`column`) VALUES (NULL);

What does auto do in margin:0 auto?

margin-top:0;
margin-bottom:0;
margin-left:auto;
margin-right:auto;

0 is for top-bottom and auto for left-right. The browser sets the margin.

How do I use su to execute the rest of the bash script as that user?

Inspired by the idea from @MarSoft but I changed the lines like the following:

USERNAME='desireduser'
COMMAND=$0
COMMANDARGS="$(printf " %q" "${@}")"
if [ $(whoami) != "$USERNAME" ]; then
  exec sudo -E su $USERNAME -c "/usr/bin/bash -l $COMMAND $COMMANDARGS"
  exit
fi

I have used sudo to allow a password less execution of the script. If you want to enter a password for the user, remove the sudo. If you do not need the environment variables, remove -E from sudo.

The /usr/bin/bash -l ensures, that the profile.d scripts are executed for an initialized environment.

Javascript split regex question

or just use for date strings 2015-05-20 or 2015.05.20

date.split(/\.|-/);

Sending email from Azure

I would never recommend SendGrid. I took up their free account offer and never managed to send a single email - all got blocked - I spent days trying to resolve it. When I enquired why they got blocked, they told me that free accounts share an ip address and if any account abuses that ip by sending spam - then everyone on the shared ip address gets blocked - totally useless. Also if you use them - do not store your email key in a git public repository as anyone can read the key from there (using a crawler) and use your chargeable account to send bulk emails.

A free email service which I've been using reliably with an Azure website is to use my Gmail (Google mail) account. That account has an option for using it with applications - once you enable that, then email can be sent from your azure website. Pasting in sample send code as the port to use (587) is not obvious.

  public static void SendMail(MailMessage Message)
    {
        SmtpClient client = new SmtpClient();
        client.Host = EnvironmentSecret.Instance.SmtpHost; // smtp.googlemail.com
        client.Port = 587;
        client.UseDefaultCredentials = false;
        client.DeliveryMethod = SmtpDeliveryMethod.Network;
        client.EnableSsl = true;
        client.Credentials = new NetworkCredential(
            EnvironmentSecret.Instance.NetworkCredentialUserName,
            EnvironmentSecret.Instance.NetworkCredentialPassword);
        client.Send(Message);
    }

How to get numeric position of alphabets in java?

just logic I can suggest take two arrays.

one is Char array

and another is int array.

convert ur input string to char array,get the position of char from char and int array.

dont expect source code here

Add space between cells (td) using css

Consider using cellspacing and cellpadding attributes for table tag or border-spacing css property.

How to 'insert if not exists' in MySQL?

Here is a PHP function that will insert a row only if all the specified columns values don't already exist in the table.

  • If one of the columns differ, the row will be added.

  • If the table is empty, the row will be added.

  • If a row exists where all the specified columns have the specified values, the row won't be added.

    function insert_unique($table, $vars)
    {
      if (count($vars)) {
        $table = mysql_real_escape_string($table);
        $vars = array_map('mysql_real_escape_string', $vars);
    
        $req = "INSERT INTO `$table` (`". join('`, `', array_keys($vars)) ."`) ";
        $req .= "SELECT '". join("', '", $vars) ."' FROM DUAL ";
        $req .= "WHERE NOT EXISTS (SELECT 1 FROM `$table` WHERE ";
    
        foreach ($vars AS $col => $val)
          $req .= "`$col`='$val' AND ";
    
        $req = substr($req, 0, -5) . ") LIMIT 1";
    
        $res = mysql_query($req) OR die();
        return mysql_insert_id();
      }
    
      return False;
    }
    

Example usage :

<?php
insert_unique('mytable', array(
  'mycolumn1' => 'myvalue1',
  'mycolumn2' => 'myvalue2',
  'mycolumn3' => 'myvalue3'
  )
);
?>

Image overlay on responsive sized images bootstrap

<div class="col-md-4 py-3 pic-card">
          <div class="card ">
          <div class="pic-overlay"></div>
          <img class="img-fluid " src="images/Site Images/Health & Fitness-01.png" alt="">
          <div class="centeredcard">
            <h3>
              <span class="card-headings">HEALTH & FITNESS</span>
            </h3>
            <div class="content-inner mt-5">
              <p class="lead  p-overlay">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae ipsam nemo quasi quo quae voluptate.</p>
            </div>
          </div>
          </div>
        </div>


.pic-card{
     position: relative;

 }
 .pic-overlay{

    top: 0;
    left: 0;
    right:0;
    bottom:0;
    width: 100%;
    height: 100%;
    position: absolute;
    transition: background-color 0.5s ease;

 }
 .content-inner{
    position: relative;
     display: none;
 }

 .pic-card:hover{
     .pic-overlay{
        background-color: $dark-overlay;

     }

     .content-inner{
         display: block;
         cursor: pointer;
     }

     .card-headings{
        font-size: 15px;
        padding: 0;
     }

     .card-headings::after{
        content: '';
        width: 80%;
        border-bottom: solid 2px  rgb(52, 178, 179);
        position: absolute;
        left: 5%;
        top: 25%;
        z-index: 1;
     }
     .p-overlay{
         font-size: 15px;
     }
 }



enter code here

How to set JAVA_HOME in Linux for all users

All operational steps(finding java, parent dir, editing file,...) one solution

zFileProfile="/etc/profile"
zJavaHomePath=$(readlink -ze $(which java) | xargs -0 dirname | xargs -0 dirname)
echo $zJavaHomePath

echo "export JAVA_HOME=\"${zJavaHomePath}\"" >> $zFileProfile
echo "export PATH=\$PATH:\$JAVA_HOME/bin" >> $zFileProfile

Result:

# tail -2 $zFileProfile
export JAVA_HOME="/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64"
export PATH=$PATH:$JAVA_HOME/bin

Explanation:

1) Let's break the full command into pieces

$(readlink -ze $(which java) | xargs -0 dirname | xargs -0 dirname)

2) Find java path from java command

# $(which java)
"/usr/bin/java"

3) Get relative path from symbolic path

# readlink -ze /usr/bin/java
"/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/java"

4) Get parent path of /usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/java

# readlink -ze /usr/bin/java | xargs -0 dirname
"/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin"

5) Get parent path of /usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64/bin/

# readlink -ze /usr/bin/java | xargs -0 dirname | xargs -0 dirname
"/usr/lib/jvm/java-11-openjdk-11.0.7.10-1.el8_1.x86_64"

PHPExcel how to set cell value dynamically

I asume you have connected to your database already.

$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);

$row = 1; // 1-based index
while($row_data = mysql_fetch_assoc($result)) {
    $col = 0;
    foreach($row_data as $key=>$value) {
        $objPHPExcel->getActiveSheet()->setCellValueByColumnAndRow($col, $row, $value);
        $col++;
    }
    $row++;
}

Difference between os.getenv and os.environ.get

In Python 2.7 with iPython:

>>> import os
>>> os.getenv??
Signature: os.getenv(key, default=None)
Source:
def getenv(key, default=None):
    """Get an environment variable, return None if it doesn't exist.
    The optional second argument can specify an alternate default."""
    return environ.get(key, default)
File:      ~/venv/lib/python2.7/os.py
Type:      function

So we can conclude os.getenv is just a simple wrapper around os.environ.get.

How to locate the php.ini file (xampp)

If you have been using different installers, you may well end up with more that one php.ini file on your hdd, which could affect your sanity after a while.

Search your hdd for 'php.ini' just in case there is more than one.

Another sanity-saving move is to remember to always restart your server (apache) after altering a value in php.ini.

Sys.WebForms.PageRequestManagerServerErrorException: An unknown error occurred while processing the request on the server."

This issue for me was caused by a database mapping error.

I attempted to use a select() call on a datasource with errors in the code behind. My controls were within an update panel and the actual cause was hidden.

Usually, if you can temporarily remove the update panel, asp.net will return a more useful error message.

Laravel stylesheets and javascript don't load for non-base routes

Suppose you have not renamed your public folder. Your css and js files are in css and js subfolders in public folder. Now your header will be :

<link rel="stylesheet" type="text/css" href="/public/css/icon.css"/>
<script type="text/javascript" src="/public/js/jquery.easyui.min.js"></script>

Java associative-array

Java equivalent of Perl's hash

HashMap<Integer, HashMap<String, String>> hash;

How to swap two variables in JavaScript

Since ES6, you can also swap variables more elegantly:

var a = 1,
    b = 2;

[a, b] = [b, a];

console.log('a:', a, 'b:', b); // a: 2 b: 1

What is the lifetime of a static variable in a C++ function?

The lifetime of function static variables begins the first time[0] the program flow encounters the declaration and it ends at program termination. This means that the run-time must perform some book keeping in order to destruct it only if it was actually constructed.

Additionally, since the standard says that the destructors of static objects must run in the reverse order of the completion of their construction[1], and the order of construction may depend on the specific program run, the order of construction must be taken into account.

Example

struct emitter {
    string str;
    emitter(const string& s) : str(s) { cout << "Created " << str << endl; }
    ~emitter() { cout << "Destroyed " << str << endl; }
};

void foo(bool skip_first) 
{
    if (!skip_first)
        static emitter a("in if");
    static emitter b("in foo");
}

int main(int argc, char*[])
{
    foo(argc != 2);
    if (argc == 3)
        foo(false);
}

Output:

C:>sample.exe
Created in foo
Destroyed in foo

C:>sample.exe 1
Created in if
Created in foo
Destroyed in foo
Destroyed in if

C:>sample.exe 1 2
Created in foo
Created in if
Destroyed in if
Destroyed in foo

[0] Since C++98[2] has no reference to multiple threads how this will be behave in a multi-threaded environment is unspecified, and can be problematic as Roddy mentions.

[1] C++98 section 3.6.3.1 [basic.start.term]

[2] In C++11 statics are initialized in a thread safe way, this is also known as Magic Statics.

How can I replace non-printable Unicode characters in Java?

methods in blow for your goal

public static String removeNonAscii(String str)
{
    return str.replaceAll("[^\\x00-\\x7F]", "");
}

public static String removeNonPrintable(String str) // All Control Char
{
    return str.replaceAll("[\\p{C}]", "");
}

public static String removeSomeControlChar(String str) // Some Control Char
{
    return str.replaceAll("[\\p{Cntrl}\\p{Cc}\\p{Cf}\\p{Co}\\p{Cn}]", "");
}

public static String removeFullControlChar(String str)
{
    return removeNonPrintable(str).replaceAll("[\\r\\n\\t]", "");
} 

Remove blank lines with grep

Do lines in the file have whitespace characters?

If so then

grep "\S" file.txt

Otherwise

grep . file.txt

Answer obtained from: https://serverfault.com/a/688789

How do I strip all spaces out of a string in PHP?

If you know the white space is only due to spaces, you can use:

$string = str_replace(' ','',$string); 

But if it could be due to space, tab...you can use:

$string = preg_replace('/\s+/','',$string);

Python and SQLite: insert into table

Adapted from http://docs.python.org/library/sqlite3.html:

# Larger example
for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
         ]:
    c.execute('insert into stocks values (?,?,?,?,?)', t)

Extract hostname name from string

I tried to use the Given solutions, the Chosen one was an overkill for my purpose and "Creating a element" one messes up for me.

It's not ready for Port in URL yet. I hope someone finds it useful

function parseURL(url){
    parsed_url = {}

    if ( url == null || url.length == 0 )
        return parsed_url;

    protocol_i = url.indexOf('://');
    parsed_url.protocol = url.substr(0,protocol_i);

    remaining_url = url.substr(protocol_i + 3, url.length);
    domain_i = remaining_url.indexOf('/');
    domain_i = domain_i == -1 ? remaining_url.length - 1 : domain_i;
    parsed_url.domain = remaining_url.substr(0, domain_i);
    parsed_url.path = domain_i == -1 || domain_i + 1 == remaining_url.length ? null : remaining_url.substr(domain_i + 1, remaining_url.length);

    domain_parts = parsed_url.domain.split('.');
    switch ( domain_parts.length ){
        case 2:
          parsed_url.subdomain = null;
          parsed_url.host = domain_parts[0];
          parsed_url.tld = domain_parts[1];
          break;
        case 3:
          parsed_url.subdomain = domain_parts[0];
          parsed_url.host = domain_parts[1];
          parsed_url.tld = domain_parts[2];
          break;
        case 4:
          parsed_url.subdomain = domain_parts[0];
          parsed_url.host = domain_parts[1];
          parsed_url.tld = domain_parts[2] + '.' + domain_parts[3];
          break;
    }

    parsed_url.parent_domain = parsed_url.host + '.' + parsed_url.tld;

    return parsed_url;
}

Running this:

parseURL('https://www.facebook.com/100003379429021_356001651189146');

Result:

Object {
    domain : "www.facebook.com",
    host : "facebook",
    path : "100003379429021_356001651189146",
    protocol : "https",
    subdomain : "www",
    tld : "com"
}

PermissionError: [WinError 5] Access is denied python using moviepy to write gif

I've run into this as well, solution is usually to be sure to run the program as an administrator (right click, run as administrator.)

Spring cannot find bean xml configuration file when it does exist

I also had a similar problem but because of a bit different cause so sharing here in case it can help anybody.

My file location

beans.xml file

How I was using

ClassPathXmlApplicationContext("beans.xml");

There are two solutions

  1. Take the beans.xml out of package and put in default package.
  2. Specify package name while using it viz.

ClassPathXmlApplicationContext("com/mypackage/beans.xml");

How to create and use resources in .NET

The above didn't actually work for me as I had expected with Visual Studio 2010. It wouldn't let me access Properties.Resources, said it was inaccessible due to permission issues. I ultimately had to change the Persistence settings in the properties of the resource and then I found how to access it via the Resources.Designer.cs file, where it had an automatic getter that let me access the icon, via MyNamespace.Properties.Resources.NameFromAddingTheResource. That returns an object of type Icon, ready to just use.

How to select an element by classname using jqLite?

angualr uses the lighter version of jquery called as jqlite which means it doesnt have all the features of jQuery. here is a reference in angularjs docs about what you can use from jquery. Angular Element docs

In your case you need to find a div with ID or class name. for class name you can use

var elems =$element.find('div') //returns all the div's in the $elements
    angular.forEach(elems,function(v,k)){
    if(angular.element(v).hasClass('class-name')){
     console.log(angular.element(v));
}}

or you can use much simpler way by query selector

angular.element(document.querySelector('#id'))

angular.element(elem.querySelector('.classname'))

it is not as flexible as jQuery but what

Sending HTTP POST with System.Net.WebClient

WebClient doesn't have a direct support for form data, but you can send a HTTP post by using the UploadString method:

Using client as new WebClient
    result = client.UploadString(someurl, "param1=somevalue&param2=othervalue")
End Using

GoogleTest: How to skip a test?

If more than one test are needed be skipped

--gtest_filter=-TestName.*:TestName.*TestCase

How to redirect a url in NGINX

Best way to do what you want is to add another server block:

server {
        #implemented by default, change if you need different ip or port
        #listen *:80 | *:8000;
        server_name test.com;
        return 301 $scheme://www.test.com$request_uri;
}

And edit your main server block server_name variable as following:

server_name  www.test.com;

Important: New server block is the right way to do this, if is evil. You must use locations and servers instead of if if it's possible. Rewrite is sometimes evil too, so replaced it with return.

How can I remove a trailing newline?

If your question is to clean up all the line breaks in a multiple line str object (oldstr), you can split it into a list according to the delimiter '\n' and then join this list into a new str(newstr).

newstr = "".join(oldstr.split('\n'))

Tkinter example code for multiple windows, why won't buttons load correctly?

#!/usr/bin/env python
import Tkinter as tk

from Tkinter import *

class windowclass():

        def __init__(self,master):
                self.master = master
                self.frame = tk.Frame(master)
                self.lbl = Label(master , text = "Label")
                self.lbl.pack()
                self.btn = Button(master , text = "Button" , command = self.command )
                self.btn.pack()
                self.frame.pack()

        def command(self):
                print 'Button is pressed!'

                self.newWindow = tk.Toplevel(self.master)
                self.app = windowclass1(self.newWindow)

class windowclass1():

        def __init__(self , master):
                self.master = master
                self.frame = tk.Frame(master)
                master.title("a")
                self.quitButton = tk.Button(self.frame, text = 'Quit', width = 25 , command = self.close_window)
                self.quitButton.pack()
                self.frame.pack()


        def close_window(self):
                self.master.destroy()


root = Tk()

root.title("window")

root.geometry("350x50")

cls = windowclass(root)

root.mainloop()

VB.NET - Click Submit Button on Webbrowser page

Just follow two steps for clicking a any button using code.

  1. focus the button or element which you want to click

    WebBrowser1.Document.GetElementById("place id here").Focus()

  2. simulate mouse click using this following code

    SendKeys.Send("{ENTER}")

Android AudioRecord example

Here I am posting you the some code example which record good quality of sound using AudioRecord API.

Note: If you use in emulator the sound quality will not much good because we are using sample rate 8k which only supports in emulator. In device use sample rate to 44.1k for better quality.

public class Audio_Record extends Activity {
    private static final int RECORDER_SAMPLERATE = 8000;
    private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_MONO;
    private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
    private AudioRecord recorder = null;
    private Thread recordingThread = null;
    private boolean isRecording = false;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        setButtonHandlers();
        enableButtons(false);

        int bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,
                RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING); 
    }

    private void setButtonHandlers() {
        ((Button) findViewById(R.id.btnStart)).setOnClickListener(btnClick);
        ((Button) findViewById(R.id.btnStop)).setOnClickListener(btnClick);
    }

    private void enableButton(int id, boolean isEnable) {
        ((Button) findViewById(id)).setEnabled(isEnable);
    }

    private void enableButtons(boolean isRecording) {
        enableButton(R.id.btnStart, !isRecording);
        enableButton(R.id.btnStop, isRecording);
    }

    int BufferElements2Rec = 1024; // want to play 2048 (2K) since 2 bytes we use only 1024
    int BytesPerElement = 2; // 2 bytes in 16bit format

    private void startRecording() {

        recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,
                RECORDER_SAMPLERATE, RECORDER_CHANNELS,
                RECORDER_AUDIO_ENCODING, BufferElements2Rec * BytesPerElement);

        recorder.startRecording();
        isRecording = true;
        recordingThread = new Thread(new Runnable() {
            public void run() {
                writeAudioDataToFile();
            }
        }, "AudioRecorder Thread");
        recordingThread.start();
    }

        //convert short to byte
    private byte[] short2byte(short[] sData) {
        int shortArrsize = sData.length;
        byte[] bytes = new byte[shortArrsize * 2];
        for (int i = 0; i < shortArrsize; i++) {
            bytes[i * 2] = (byte) (sData[i] & 0x00FF);
            bytes[(i * 2) + 1] = (byte) (sData[i] >> 8);
            sData[i] = 0;
        }
        return bytes;

    }

    private void writeAudioDataToFile() {
        // Write the output audio in byte

        String filePath = "/sdcard/voice8K16bitmono.pcm";
        short sData[] = new short[BufferElements2Rec];

        FileOutputStream os = null;
        try {
            os = new FileOutputStream(filePath);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        while (isRecording) {
            // gets the voice output from microphone to byte format

            recorder.read(sData, 0, BufferElements2Rec);
            System.out.println("Short writing to file" + sData.toString());
            try {
                // // writes the data to file from buffer
                // // stores the voice buffer
                byte bData[] = short2byte(sData);
                os.write(bData, 0, BufferElements2Rec * BytesPerElement);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void stopRecording() {
        // stops the recording activity
        if (null != recorder) {
            isRecording = false;
            recorder.stop();
            recorder.release();
            recorder = null;
            recordingThread = null;
        }
    }

    private View.OnClickListener btnClick = new View.OnClickListener() {
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.btnStart: {
                enableButtons(true);
                startRecording();
                break;
            }
            case R.id.btnStop: {
                enableButtons(false);
                stopRecording();
                break;
            }
            }
        }
    };

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }
}

For more detail try this AUDIORECORD BLOG.

Happy Coding !!

Difference between getContext() , getApplicationContext() , getBaseContext() and "this"

The question "what the Context is" is one of the most difficult questions in the Android universe.

Context defines methods that access system resources, retrieve application's static assets, check permissions, perform UI manipulations and many more. In essence, Context is an example of God Object anti-pattern in production.

When it comes to which kind of Context should we use, it becomes very complicated because except for being God Object, the hierarchy tree of Context subclasses violates Liskov Substitution Principle brutally.

This blog post (now from Wayback Machine) attempts to summarize Context classes applicability in different situations.

Let me copy the main table from that post for completeness:

+----------------------------+-------------+----------+---------+-----------------+-------------------+
|                            | Application | Activity | Service | ContentProvider | BroadcastReceiver |
+----------------------------+-------------+----------+---------+-----------------+-------------------+
| Show a Dialog              | NO          | YES      | NO      | NO              | NO                |
| Start an Activity          | NO¹         | YES      | NO¹     | NO¹             | NO¹               |
| Layout Inflation           | NO²         | YES      | NO²     | NO²             | NO²               |
| Start a Service            | YES         | YES      | YES     | YES             | YES               |
| Bind to a Service          | YES         | YES      | YES     | YES             | NO                |
| Send a Broadcast           | YES         | YES      | YES     | YES             | YES               |
| Register BroadcastReceiver | YES         | YES      | YES     | YES             | NO³               |
| Load Resource Values       | YES         | YES      | YES     | YES             | YES               |
+----------------------------+-------------+----------+---------+-----------------+-------------------+
  1. An application CAN start an Activity from here, but it requires that a new task be created. This may fit specific use cases, but can create non-standard back stack behaviors in your application and is generally not recommended or considered good practice.
  2. This is legal, but inflation will be done with the default theme for the system on which you are running, not what’s defined in your application.
  3. Allowed if the receiver is null, which is used for obtaining the current value of a sticky broadcast, on Android 4.2 and above.

screenshot