Programs & Examples On #Directx 11

DirectX 11 is the 11th version of Microsoft's DirectX API, which is used to develop and handle tasks related to Multimedia, such as game programming, 3d visualizations and video on Microsoft platforms. DirectX 11 runs on Windows Vista, Windows 7, Windows 8, Windows 10, and Xbox One.

C# Wait until condition is true

You can use thread waiting handler

private readonly System.Threading.EventWaitHandle waitHandle = new System.Threading.AutoResetEvent(false);
private void btnOk_Click(object sender, EventArgs e)
{
    // Do some work
    Task<string> task = Task.Run(() => GreatBigMethod());
    string GreatBigMethod = await task;

    // Wait until condition is false
    waitHandle.WaitOne();
    Console.WriteLine("Excel is busy");
    waitHandle.Reset();

    // Do work
    Console.WriteLine("YAY");
 }

then some other job need to set your handler

void isExcelInteractive()
{
   /// Do your check
   waitHandle.Set()
}

Update: If you want use this solution, you have to call isExcelInteractive() continuously with specific interval:

var actions = new []{isExcelInteractive, () => Thread.Sleep(25)};
foreach (var action in actions)
{                                      
    action();
}

What steps are needed to stream RTSP from FFmpeg?

You can use FFserver to stream a video using RTSP.

Just change console syntax to something like this:

ffmpeg -i space.mp4 -vcodec libx264 -tune zerolatency -crf 18 http://localhost:1234/feed1.ffm

Create a ffserver.config file (sample) where you declare HTTPPort, RTSPPort and SDP stream. Your config file could look like this (some important stuff might be missing):

HTTPPort 1234
RTSPPort 1235

<Feed feed1.ffm>
        File /tmp/feed1.ffm
        FileMaxSize 2M
        ACL allow 127.0.0.1
</Feed>

<Stream test1.sdp>
    Feed feed1.ffm
    Format rtp
    Noaudio
    VideoCodec libx264
    AVOptionVideo flags +global_header
    AVOptionVideo me_range 16
    AVOptionVideo qdiff 4
    AVOptionVideo qmin 10
    AVOptionVideo qmax 51
    ACL allow 192.168.0.0 192.168.255.255
</Stream>

With such setup you can watch the stream with i.e. VLC by typing:

rtsp://192.168.0.xxx:1235/test1.sdp

Here is the FFserver documentation.

How can I check if a Perl array contains a particular value?

Best general purpose - Especially short arrays (1000 items or less) and coders that are unsure of what optimizations best suit their needs.

# $value can be any regex. be safe
if ( grep( /^$value$/, @array ) ) {
  print "found it";
}

It has been mentioned that grep passes through all values even if the first value in the array matches. This is true, however grep is still extremely fast for most cases. If you're talking about short arrays (less than 1000 items) then most algorithms are going to be pretty fast anyway. If you're talking about very long arrays (1,000,000 items) grep is acceptably quick regardless of whether the item is the first or the middle or last in the array.

Optimization Cases for longer arrays:

If your array is sorted, use a "binary search".

If the same array is repeatedly searched many times, copy it into a hash first and then check the hash. If memory is a concern, then move each item from the array into the hash. More memory efficient but destroys the original array.

If same values are searched repeatedly within the array, lazily build a cache. (as each item is searched, first check if the search result was stored in a persisted hash. if the search result is not found in the hash, then search the array and put the result in the persisted hash so that next time we'll find it in the hash and skip the search).

Note: these optimizations will only be faster when dealing with long arrays. Don't over optimize.

How to use Monitor (DDMS) tool to debug application

Could it be a problem with past preview versions of Android Studio ? nowadays "beta" has replaced the "preview". I try it out step by step debugging while using Memory Monitor at same time by Android Studio (Beta) 0.8.11 on OSX 10.9.5 without any problems.

The tutorial Debugging with Android Studio also helps, specially this paragraph :

To track memory allocation of objects:

  1. Start your app as described in Run Your App in Debug Mode.
  2. Click Android to open the Android DDMS tool window.
  3. On the Android DDMS tool window, select the Devices | logcat tab.
  4. Select your device from the dropdown list.
  5. Select your app by its package name from the list of running apps.
  6. Click Start Allocation Tracking Interact with your app on the device. Click Stop Allocation Tracking

Here a couple of screenshot while debugging step by step on a breakpoint a monitoring the memory on the emulator:
breakpointmemory monitor

Concatenate a vector of strings/character

Another way would be to use glue package:

glue_collapse(glue("{sdata}"))
paste(glue("{sdata}"), collapse = '')

VBA: Counting rows in a table (list object)

You can use this:

    Range("MyTable[#Data]").Rows.Count

You have to distinguish between a table which has either one row of data or no data, as the previous code will return "1" for both cases. Use this to test for an empty table:

    If WorksheetFunction.CountA(Range("MyTable[#Data]"))

jQuery Ajax POST example with PHP

Handling Ajax errors and loader before submit and after submitting success shows an alert boot box with an example:

var formData = formData;

$.ajax({
    type: "POST",
    url: url,
    async: false,
    data: formData, // Only input
    processData: false,
    contentType: false,
    xhr: function ()
    {
        $("#load_consulting").show();
        var xhr = new window.XMLHttpRequest();

        // Upload progress
        xhr.upload.addEventListener("progress", function (evt) {
            if (evt.lengthComputable) {
                var percentComplete = (evt.loaded / evt.total) * 100;
                $('#addLoad .progress-bar').css('width', percentComplete + '%');
            }
        }, false);

        // Download progress
        xhr.addEventListener("progress", function (evt) {
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
            }
        }, false);
        return xhr;
    },
    beforeSend: function (xhr) {
        qyuraLoader.startLoader();
    },
    success: function (response, textStatus, jqXHR) {
        qyuraLoader.stopLoader();
        try {
            $("#load_consulting").hide();

            var data = $.parseJSON(response);
            if (data.status == 0)
            {
                if (data.isAlive)
                {
                    $('#addLoad .progress-bar').css('width', '00%');
                    console.log(data.errors);
                    $.each(data.errors, function (index, value) {
                        if (typeof data.custom == 'undefined') {
                            $('#err_' + index).html(value);
                        }
                        else
                        {
                            $('#err_' + index).addClass('error');

                            if (index == 'TopError')
                            {
                                $('#er_' + index).html(value);
                            }
                            else {
                                $('#er_TopError').append('<p>' + value + '</p>');
                            }
                        }
                    });
                    if (data.errors.TopError) {
                        $('#er_TopError').show();
                        $('#er_TopError').html(data.errors.TopError);
                        setTimeout(function () {
                            $('#er_TopError').hide(5000);
                            $('#er_TopError').html('');
                        }, 5000);
                    }
                }
                else
                {
                    $('#headLogin').html(data.loginMod);
                }
            } else {
                //document.getElementById("setData").reset();
                $('#myModal').modal('hide');
                $('#successTop').show();
                $('#successTop').html(data.msg);
                if (data.msg != '' && data.msg != "undefined") {

                    bootbox.alert({closeButton: false, message: data.msg, callback: function () {
                            if (data.url) {
                                window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
                            } else {
                                location.reload(true);
                            }
                        }});
                } else {
                    bootbox.alert({closeButton: false, message: "Success", callback: function () {
                        if (data.url) {
                            window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
                        } else {
                            location.reload(true);
                        }
                    }});
                }

            }
        }
        catch (e) {
            if (e) {
                $('#er_TopError').show();
                $('#er_TopError').html(e);
                setTimeout(function () {
                    $('#er_TopError').hide(5000);
                    $('#er_TopError').html('');
                }, 5000);
            }
        }
    }
});

How to access to a child method from the parent in vue.js

You can use ref.

import ChildForm from './components/ChildForm'

new Vue({
  el: '#app',
  data: {
    item: {}
  },
  template: `
  <div>
     <ChildForm :item="item" ref="form" />
     <button type="submit" @click.prevent="submit">Post</button>
  </div>
  `,
  methods: {
    submit() {
      this.$refs.form.submit()
    }
  },
  components: { ChildForm },
})

If you dislike tight coupling, you can use Event Bus as shown by @Yosvel Quintero. Below is another example of using event bus by passing in the bus as props.

import ChildForm from './components/ChildForm'

new Vue({
  el: '#app',
  data: {
    item: {},
    bus: new Vue(),
  },
  template: `
  <div>
     <ChildForm :item="item" :bus="bus" ref="form" />
     <button type="submit" @click.prevent="submit">Post</button>
  </div>
  `,
  methods: {
    submit() {
      this.bus.$emit('submit')
    }
  },
  components: { ChildForm },
})

Code of component.

<template>
 ...
</template>

<script>
export default {
  name: 'NowForm',
  props: ['item', 'bus'],
  methods: {
    submit() {
        ...
    }
  },
  mounted() {
    this.bus.$on('submit', this.submit)
  },  
}
</script>

https://code.luasoftware.com/tutorials/vuejs/parent-call-child-component-method/

Create an array of integers property in Objective-C

C arrays are not one of the supported data types for properties. See "The Objective-C Programming Language" in Xcode documentation, in the Declared Properties page:

Supported Types

You can declare a property for any Objective-C class, Core Foundation data type, or “plain old data” (POD) type (see C++ Language Note: POD Types). For constraints on using Core Foundation types, however, see “Core Foundation.”

POD does not include C arrays. See http://www.fnal.gov/docs/working-groups/fpcltf/Pkg/ISOcxx/doc/POD.html

If you need an array, you should use NSArray or NSData.

The workarounds, as I see it, are like using (void *) to circumvent type checking. You can do it, but it makes your code less maintainable.

How to generate access token using refresh token through google drive API?

Just posting my answer in case it helps anyone as I spent an hour to figure it out :)

First of all two very helpful link related to google api and fetching data from any of google services:

https://developers.google.com/analytics/devguides/config/mgmt/v3/quickstart/web-php

https://developers.google.com/identity/protocols/OAuth2WebServer

Furthermore, when using the following method:

$client->setAccessToken($token)

The $token needs to be the full object returned by the google when making authorization request, not the only access_token which you get inside the object so if you get the object lets say:

{"access_token":"xyz","token_type":"Bearer","expires_in":3600,"refresh_token":"mno","created":1532363626}

then you need to give:

$client->setAccessToken('{"access_token":"xyz","token_type":"Bearer","expires_in":3600,"refresh_token":"mno","created":1532363626}')

Not

$client->setAccessToken('xyz')

And then even if your access_token is expired, google will refresh it itself by using the refresh_token in the access_token object.

Command line: search and replace in all filenames matched by grep

find . -type f -print0 | xargs -0 <sed/perl/ruby cmd> will process multiple space contained file names at once loading one interpreter per batch. Much faster.

Difference between Inheritance and Composition

Composition is just as it sounds - you create an object by plugging in parts.

EDIT the rest of this answer is erroneously based on the following premise.
This is accomplished with Interfaces.
For example, using the Car example above,

Car implements iDrivable, iUsesFuel, iProtectsOccupants
Motorbike implements iDrivable, iUsesFuel, iShortcutThroughTraffic
House implements iProtectsOccupants
Generator implements iUsesFuel

So with a few standard theoretical components you can build up your object. It's then your job to fill in how a House protects its occupants, and how a Car protects its occupants.

Inheritance is like the other way around. You start off with a complete (or semi-complete) object and you replace or Override the various bits you want to change.

For example, MotorVehicle may come with a Fuelable method and Drive method. You may leave the Fuel method as it is because it's the same to fill up a motorbike and a car, but you may override the Drive method because the Motorbike drives very differently to a Car.

With inheritance, some classes are completely implemented already, and others have methods that you are forced to override. With Composition nothing's given to you. (but you can Implement the interfaces by calling methods in other classes if you happen to have something laying around).

Composition is seen as more flexible, because if you have a method such as iUsesFuel, you can have a method somewhere else (another class, another project) that just worries about dealing with objects that can be fueled, regardless of whether it's a car, boat, stove, barbecue, etc. Interfaces mandate that classes that say they implement that interface actually have the methods that that interface is all about. For example,

iFuelable Interface:
   void AddSomeFuel()
   void UseSomeFuel()
   int  percentageFull()

then you can have a method somewhere else

private void FillHerUp(iFuelable : objectToFill) {

   Do while (objectToFill.percentageFull() <= 100)  {

        objectToFill.AddSomeFuel();
   }

Strange example, but it's shows that this method doesn't care what it's filling up, because the object implements iUsesFuel, it can be filled. End of story.

If you used Inheritance instead, you would need different FillHerUp methods to deal with MotorVehicles and Barbecues, unless you had some rather weird "ObjectThatUsesFuel" base object from which to inherit.

Best way to import Observable from rxjs

One thing I've learnt the hard way is being consistent

Watch out for mixing:

 import { BehaviorSubject } from "rxjs";

with

 import { BehaviorSubject } from "rxjs/BehaviorSubject";

This will probably work just fine UNTIL you try to pass the object to another class (where you did it the other way) and then this can fail

 (myBehaviorSubject instanceof Observable)

It fails because the prototype chain will be different and it will be false.

I can't pretend to understand exactly what is happening but sometimes I run into this and need to change to the longer format.

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

Alternative to commandline Solution:

Recently I was playing with Services in Mac OS X. I added a service to a folder or file so that I can open that folder or file in Visual Studio Code. I think this could be an alternative to using 'code .' command if you are using the Finder app. Here are the steps:

  • Open Automator App from Application. (Or you can use Spotlight).
  • Click on 'New Document' button to create a new script.
  • Choose 'Service' as a new type of document.
  • Select 'files and folders' in 'Service receives selected' dropdown.
  • Search for 'Open Finder Items' action item.
  • Drag that action item to the workflow area.
  • Select 'Visual Studio Code.app' application in the action 'Open with' dropdown.
  • Press 'command + s' to save the service. It will ask a name of service. Give it a name. I gave 'Open with VSCode'. Close the Automator app. Check the image below for more information.

enter image description here

Verify:

  • Open the Finder app.
  • Right-click on any folder.
  • In the context menu, look for 'Open with VSCode' menu option.
  • Click on the 'Open with VSCode' menu option.
  • The folder should get open in the Visual Studio Code application. Check image below for more info.

enter image description here

How can I pipe stderr, and not stdout?

This also works (and I find it a tiny bit easier to remember)

command 2> /dev/fd/1 | grep 'something'

More info about /dev/fd directory here

Using underscores in Java variables and method names

it's just your own style,nothing a bad style code,and nothing a good style code,just difference our code with the others.

Running Facebook application on localhost

Ok I'm not sure what's up with these answers but I'll let you know what worked for me as advised by a senior dev at my work. I'm working in Ruby on Rails and using Facebook's JavaScript code to get access tokens.

Problem: To do authentication, Facebook is taking the url from your address bar and comparing that with what they have on file. They don't allow you to use localhost:3000 for whatever reason. However, you can use a completely made-up domain name like yoursite.dev by running a local server and pointing yoursite.dev to 127.0.0.1:3000 or wherever your localhost was pointing to.

Step 1: Install or update Nginx

$ brew install nginx (install) or $ brew upgrade nginx (update)

Step 2: Open up your nginx config file

/usr/local/etc/nginx/nginx.conf (usually here)

/opt/boxen/config/nginx/nginx.conf(if you use Boxen)

Step 3 Add this bit of code into your http {} block

Replace proxy_pass with wherever you want to point yoursite.dev to. In my case it was replacing localhost:3000 or the equivalent 127.0.0.1:3000

server {
  listen       yoursite.dev:80;
  server_name  yoursite.dev;
  location / {
    proxy_pass http://127.0.0.1:3000;
  }
}

Step 4: Edit your hosts file, in /etc/hosts on Mac to include

127.0.0.1   yoursite.dev

This file directs domains to localhost. Nginx listens in on localhost and redirects if it matches a rule.

Step 5: Every time you use your dev environment going forward, you use the yoursite.dev in the address bar instead of localhost:3000 so Facebook logs you in correctly.

Test if string begins with a string?

The best methods are already given but why not look at a couple of other methods for fun? Warning: these are more expensive methods but do serve in other circumstances.

The expensive regex method and the css attribute selector with starts with ^ operator

Option Explicit

Public Sub test()

    Debug.Print StartWithSubString("ab", "abc,d")

End Sub

Regex:

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft VBScript Regular Expressions
    Dim re As VBScript_RegExp_55.RegExp
    Set re = New VBScript_RegExp_55.RegExp

    re.Pattern = "^" & substring

    StartWithSubString = re.test(testString)

End Function

Css attribute selector with starts with operator

Public Function StartWithSubString(ByVal substring As String, ByVal testString As String) As Boolean
    'required reference Microsoft HTML Object Library
    Dim html As MSHTML.HTMLDocument
    Set html = New MSHTML.HTMLDocument

    html.body.innerHTML = "<div test=""" & testString & """></div>"

    StartWithSubString = html.querySelectorAll("[test^=" & substring & "]").Length > 0

End Function

Initializing a two dimensional std::vector

The recommended approach is to use fill constructor to initialize a two-dimensional vector with a given default value :

std::vector<std::vector<int>> fog(M, std::vector<int>(N, default_value));

where, M and N are dimensions for your 2D vector.

How to pass multiple parameters in a querystring

Try like this.It should work

Response.Redirect(String.Format("yourpage.aspx?strId={0}&strName={1}&strDate{2}", Server.UrlEncode(strId), Server.UrlEncode(strName),Server.UrlEncode(strDate)));

How do I set a textbox's text to bold at run time?

Here is an example for toggling bold, underline, and italics.

   protected override bool ProcessCmdKey( ref Message msg, Keys keyData )
   {
      if ( ActiveControl is RichTextBox r )
      {
         if ( keyData == ( Keys.Control | Keys.B ) )
         {
            r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Bold ); // XOR will toggle
            return true;
         }
         if ( keyData == ( Keys.Control | Keys.U ) )
         {
            r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Underline ); // XOR will toggle
            return true;
         }
         if ( keyData == ( Keys.Control | Keys.I ) )
         {
            r.SelectionFont = new Font( r.SelectionFont, r.SelectionFont.Style ^ FontStyle.Italic ); // XOR will toggle
            return true;
         }
      }
      return base.ProcessCmdKey( ref msg, keyData );
   }

Error importing SQL dump into MySQL: Unknown database / Can't create database

This is a known bug at MySQL.

bug 42996
bug 40477

As you can see this has been a known issue since 2008 and they have not fixed it yet!!!

WORK AROUND
You first need to create the database to import. It doesn't need any tables. Then you can import your database.

  1. first start your MySQL command line (apply username and password if you need to)
    C:\>mysql -u user -p

  2. Create your database and exit

    mysql> DROP DATABASE database;  
    mysql> CREATE DATABASE database;  
    mysql> Exit  
    
  3. Import your selected database from the dump file
    C:\>mysql -u user -p -h localhost -D database -o < dumpfile.sql

You can replace localhost with an IP or domain for any MySQL server you want to import to. The reason for the DROP command in the mysql prompt is to be sure we start with an empty and clean database.

Redirect parent window from an iframe action

window.top.location.href = "http://www.example.com"; 

Will redirect the top most parent Iframe.

window.parent.location.href = "http://www.example.com"; 

Will redirect the parent iframe.

Jenkins not executing jobs (pending - waiting for next executor)

In my case it is similar to @Michael Easter: I got a problem in a job due to lack of disk space. I cleared some space, restarted Jenkins but still the problem persisted.

The solution was to go to Jenkins -> Manage Jenkins -> Manage Nodes and just Click on the button to update the status.

JSON Stringify changes time of date because of UTC

I tried this in angular 8 :

  1. create Model :

    export class Model { YourDate: string | Date; }
    
  2. in your component

    model : Model;
    model.YourDate = new Date();
    
  3. send Date to your API for saving

  4. When loading your data from API you will make this :

    model.YourDate = new Date(model.YourDate+"Z");

you will get your date correctly with your time zone.

How to calculate the sum of the datatable column in asp.net?

You can do like..

DataRow[] dr = dtbl.Select("SUM(Amount)");
txtTotalAmount.Text = Convert.ToString(dr[0]);

Referring to a Column Alias in a WHERE Clause

You could refer to column alias but you need to define it using CROSS/OUTER APPLY:

SELECT s.logcount, s.logUserID, s.maxlogtm, c.daysdiff
FROM statslogsummary s
CROSS APPLY (SELECT DATEDIFF(day, s.maxlogtm, GETDATE()) AS daysdiff) c
WHERE c.daysdiff > 120;

DBFiddle Demo

Pros:

  • single definition of expression(easier to maintain/no need of copying-paste)
  • no need for wrapping entire query with CTE/outerquery
  • possibility to refer in WHERE/GROUP BY/ORDER BY
  • possible better performance(single execution)

Java: method to get position of a match in a String?

//finding a particular word any where inthe string and printing its index and occurence  
class IndOc
{
    public static void main(String[] args) 
    {
        String s="this is hyderabad city and this is";
        System.out.println("the given string is ");
        System.out.println("----------"+s);
        char ch[]=s.toCharArray();
        System.out.println(" ----word is found at ");
        int j=0,noc=0;
        for(int i=0;i<ch.length;i++)
        {
            j=i;

            if(ch[i]=='i' && ch[j+1]=='s')
            {
                System.out.println(" index "+i);
            noc++;  
            }

        }
        System.out.println("----- no of occurences are "+noc);

    }
}

How can I check if a URL exists via PHP?

The best and simplest answer so far using get_headers() The best thing to check for string "200 ok". its far better than to check

$file_headers = @get_headers($file-path);
$file_headers[0];

because sometime the array key numbers varies. so best thing is to check for "200 ok". Any URL which is up will have "200 ok" anywhere in get_headers() response.

function url_exist($url) {
        $urlheaders = get_headers($url);
        //print_r($urlheaders);
        $urlmatches  = preg_grep('/200 ok/i', $urlheaders);
         if(!empty($urlmatches)){
           return true;
         }else{
           return false;
         }
}

now check the function if true or false

if(url_exist(php-url-variable-here)
  URL exist
}else{
  URL don't exist
}

How to convert an enum type variable to a string?

Personally, I would go for something simple and use an operator to do so.

Considering the following enum:

enum WeekDay { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };

We can create an operator to output the result in an std::ostream.

std::ostream &operator<<(std::ostream &stream, const WeekDay day) {
  switch (day) {
    case MONDAY:
      stream << "Monday";
      break;
    case TUESDAY:
      stream << "Tuesday";
      break;
    case WEDNESDAY:
      stream << "Wednesday";
      break;
    case THURSDAY:
      stream << "Thursday";
      break;
    case FRIDAY:
      stream << "Friday";
      break;
    case SATURDAY:
      stream << "Saturday";
      break;
    case SUNDAY:
      stream << "Sunday";
      break;
  }

  return stream;
}

The boilerplate code is indeed pretty big compared to some other methods presented in this thread. Still, it has the avantage of being pretty straightforward and easy to use.

std::cout << "First day of the week is " << WeekDay::Monday << std::endl;

submit form on click event using jquery

it's because the name of the submit button is named "submit", change it to anything but "submit", try "submitme" and retry it. It should then work.

TypeScript Objects as Dictionary types as in C#

You can use Record for this:

https://www.typescriptlang.org/docs/handbook/utility-types.html#recordkt

Example (A mapping between AppointmentStatus enum and some meta data):

  const iconMapping: Record<AppointmentStatus, Icon> = {
    [AppointmentStatus.Failed]: { Name: 'calendar times', Color: 'red' },
    [AppointmentStatus.Canceled]: { Name: 'calendar times outline', Color: 'red' },
    [AppointmentStatus.Confirmed]: { Name: 'calendar check outline', Color: 'green' },
    [AppointmentStatus.Requested]: { Name: 'calendar alternate outline', Color: 'orange' },
    [AppointmentStatus.None]: { Name: 'calendar outline', Color: 'blue' }
  }

Now with interface as value:

interface Icon { Name: string Color: string }

Usage:

const icon: SemanticIcon = iconMapping[appointment.Status]

How to get the indices list of all NaN value in numpy array?

Since x!=x returns the same boolean array with np.isnan(x) (because np.nan!=np.nan would return True), you could also write:

np.argwhere(x!=x)

However, I still recommend writing np.argwhere(np.isnan(x)) since it is more readable. I just try to provide another way to write the code in this answer.

How to check the Angular version?

ng version

You installed angular cli globally (-g in the command). This means that you can type ng version into your command prompt. It may be more precise to do this when your command prompt is not within a npm controlled directory (you should type this in within directory you typed ng new myapp).

A note to those who got here from Google: ng version will let you know which (coarse) version of Angular is referenced by the current directory. e.g. This directory appears to have angular 4.x (~4.3.0) installed.

@angular/cli: 1.2.1
node: 8.11.1
os: win32 x64
@angular/common: 4.3.0
@angular/compiler: 4.3.0
@angular/core: 4.3.0
@angular/forms: 4.3.0
@angular/http: 4.3.0
@angular/platform-browser: 4.3.0
@angular/platform-browser-dynamic: 4.3.0
@angular/router: 4.3.0
@angular/cli: 1.2.1
@angular/compiler-cli: 4.3.0

If you are not within a directory which has a packages.config, then you will get Angular: ....

Adding POST parameters before submit

PURE JavaScript:

Creating the XMLHttpRequest:

function getHTTPObject() {
    /* Crea el objeto AJAX. Esta funcion es generica para cualquier utilidad de este tipo, 
       por lo que se puede copiar tal como esta aqui */
    var xmlhttp = false;
    /* No mas soporte para Internet Explorer
    try { // Creacion del objeto AJAX para navegadores no IE
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    } catch(nIE) {
        try { // Creacion del objet AJAX para IE
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch(IE) {
            if (!xmlhttp && typeof XMLHttpRequest!='undefined') 
                xmlhttp = new XMLHttpRequest();
        }
    }
    */
    xmlhttp = new XMLHttpRequest();
    return xmlhttp; 
}

JavaScript function to Send the info via POST:

function sendInfo() {
    var URL = "somepage.html"; //depends on you
    var Params = encodeURI("var1="+val1+"var2="+val2+"var3="+val3);
    console.log(Params);
    var ajax = getHTTPObject();     
    ajax.open("POST", URL, true); //True:Sync - False:ASync
    ajax.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
    ajax.setRequestHeader("Content-length", Params.length);
    ajax.setRequestHeader("Connection", "close");
    ajax.onreadystatechange = function() { 
        if (ajax.readyState == 4 && ajax.status == 200) {
            alert(ajax.responseText);
        } 
    }
    ajax.send(Params);
}

How to count how many values per level in a given factor?

Or using the dplyr library:

library(dplyr)
set.seed(1)
dat <- data.frame(ID = sample(letters,100,rep=TRUE))
dat %>% 
  group_by(ID) %>%
  summarise(no_rows = length(ID))

Note the use of %>%, which is similar to the use of pipes in bash. Effectively, the code above pipes dat into group_by, and the result of that operation is piped into summarise.

The result is:

Source: local data frame [26 x 2]

   ID no_rows
1   a       2
2   b       3
3   c       3
4   d       3
5   e       2
6   f       4
7   g       6
8   h       1
9   i       6
10  j       5
11  k       6
12  l       4
13  m       7
14  n       2
15  o       2
16  p       2
17  q       5
18  r       4
19  s       5
20  t       3
21  u       8
22  v       4
23  w       5
24  x       4
25  y       3
26  z       1

See the dplyr introduction for some more context, and the documentation for details regarding the individual functions.

What is log4j's default log file dumping path

To redirect your logs output to a file, you need to use the FileAppender and need to define other file details in your log4j.properties/xml file. Here is a sample properties file for the same:

# Root logger option
log4j.rootLogger=INFO, file

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\loging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Follow this tutorial to learn more about log4j usage:

http://www.mkyong.com/logging/log4j-log4j-properties-examples/

Android Service Stops When App Is Closed

try this, it will keep the service running in the background.

BackServices.class

public class BackServices extends Service{

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      // Let it continue running until it is stopped.
      Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
      return START_STICKY;
   }
   @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
   }
}

in your MainActivity onCreate drop this line of code

startService(new Intent(getBaseContext(), BackServices.class));

Now the service will stay running in background.

ProgressDialog spinning circle

Put this XML to show only the wheel:

<ProgressBar
    android:indeterminate="true"
    android:id="@+id/marker_progress"
    style="?android:attr/progressBarStyle"
    android:layout_height="50dp" />

Run jQuery function onclick

You can bind the mouseenter and mouseleave events and jQuery will emulate those where they are not native.

$("div.system_box").on('mouseenter', function(){
    //enter
})
.on('mouseleave', function(){
    //leave
});

fiddle

note: do not use hover as that is deprecated

Attaching click event to a JQuery object not yet added to the DOM

Use this. You can replace body with any parent element that exists on dom ready

$('body').on('click', '#my-button', function () {
     console.log("yeahhhh!!! but this doesn't work for me :(");
});

Look here http://api.jquery.com/on/ for more info on how to use on() as it replaces live() as of 1.7+.

Below lists which version you should be using

$(selector).live(events, data, handler); // jQuery 1.3+

$(document).delegate(selector, events, data, handler); // jQuery 1.4.3+

$(document).on(events, selector, data, handler); // jQuery 1.7+

Check if a number has a decimal place/is a whole number

function isDecimal(n){
    if(n == "")
        return false;

    var strCheck = "0123456789";
    var i;

    for(i in n){
        if(strCheck.indexOf(n[i]) == -1)
            return false;
    }
    return true;
}

Convert Java Array to Iterable

just my 2 cents:

final int a[] = {1,2,3};

java.lang.Iterable<Integer> aIterable=new Iterable<Integer>() {

    public Iterator<Integer> iterator() {
       return new Iterator<Integer>() {
            private int pos=0;

            public boolean hasNext() {
               return a.length>pos;
            }

            public Integer next() {
               return a[pos++];
            }

            public void remove() {
                throw new UnsupportedOperationException("Cannot remove an element of an array.");
            }
        };
    }
};

React.js: onChange event for contentEditable

Edit: See Sebastien Lorber's answer which fixes a bug in my implementation.


Use the onInput event, and optionally onBlur as a fallback. You might want to save the previous contents to prevent sending extra events.

I'd personally have this as my render function.

var handleChange = function(event){
    this.setState({html: event.target.value});
}.bind(this);

return (<ContentEditable html={this.state.html} onChange={handleChange} />);

jsbin

Which uses this simple wrapper around contentEditable.

var ContentEditable = React.createClass({
    render: function(){
        return <div 
            onInput={this.emitChange} 
            onBlur={this.emitChange}
            contentEditable
            dangerouslySetInnerHTML={{__html: this.props.html}}></div>;
    },
    shouldComponentUpdate: function(nextProps){
        return nextProps.html !== this.getDOMNode().innerHTML;
    },
    emitChange: function(){
        var html = this.getDOMNode().innerHTML;
        if (this.props.onChange && html !== this.lastHtml) {

            this.props.onChange({
                target: {
                    value: html
                }
            });
        }
        this.lastHtml = html;
    }
});

Get img thumbnails from Vimeo?

For somebody like me who's trying to figure this out recently,

https://i.vimeocdn.com/video/[video_id]_[dimension].webp works for me.

(where dimension = 200x150 | 640)

Converting a string to a date in DB2

Okay, seems like a bit of a hack. I have got it to work using a substring, so that only the part of the string with the date (not the time) gets passed into the DATE function...

DATE(substr(SETTLEMENTDATE.VALUE,7,4)||'-'|| substr(SETTLEMENTDATE.VALUE,4,2)||'-'|| substr(SETTLEMENTDATE.VALUE,1,2))

I will still accept any answers that are better than this one!

Your content must have a ListView whose id attribute is 'android.R.id.list'

You should have one listview in your mainlist.xml file with id as @android:id/list

<ListView
    android:id="@android:id/list"
    android:layout_height="wrap_content"
    android:layout_height="fill_parent"/>

How to convert a string to integer in C?

You can always roll your own!

#include <stdio.h>
#include <string.h>
#include <math.h>

int my_atoi(const char* snum)
{
    int idx, strIdx = 0, accum = 0, numIsNeg = 0;
    const unsigned int NUMLEN = (int)strlen(snum);

    /* Check if negative number and flag it. */
    if(snum[0] == 0x2d)
        numIsNeg = 1;

    for(idx = NUMLEN - 1; idx >= 0; idx--)
    {
        /* Only process numbers from 0 through 9. */
        if(snum[strIdx] >= 0x30 && snum[strIdx] <= 0x39)
            accum += (snum[strIdx] - 0x30) * pow(10, idx);

        strIdx++;
    }

    /* Check flag to see if originally passed -ve number and convert result if so. */
    if(!numIsNeg)
        return accum;
    else
        return accum * -1;
}

int main()
{
    /* Tests... */
    printf("Returned number is: %d\n", my_atoi("34574"));
    printf("Returned number is: %d\n", my_atoi("-23"));

    return 0;
}

This will do what you want without clutter.

Error while sending QUERY packet

Had such a problem when executing forking in php for command line. In my case from time to time the php killed the child process. To fix this, just wait for the process to complete using the command pcntl_wait($status);

here's a piece of code for a visual example:

    #!/bin/php -n
    <?php
    error_reporting(E_ALL & ~E_NOTICE);
    ini_set("log_errors", 1);
    ini_set('error_log', '/media/logs/php/fork.log');
    $ski = substr(str_shuffle(str_repeat("0123456789abcdefghijklmnopqrstuvwxyz", 5)), 0, 5);
    error_log(getmypid().' '.$ski.' start my php');

    $pid = pcntl_fork();
    if($pid) {
    error_log(getmypid().' '.$ski.' start 2');
    // Wait for children to return. Otherwise they 
    // would turn into "Zombie" processes
    // !!!!!! add this !!!!!!
    pcntl_wait($status);
    // !!!!!! add this !!!!!!
    } else {
    error_log(getmypid().' '.$ski.' start 3');
    //[03-Apr-2020 12:13:47 UTC] PHP Warning:  Error while sending QUERY packet. PID=18048 in /speed/sport/fortest.php on line 22457
    mysqli_query($con,$query,MYSQLI_ASYNC);
error_log(getmypid().' '.$ski.' sleep child');
  sleep(15);
    exit;
    } 

   error_log(getmypid().' '.$ski.'end my php');
    exit(0);
    ?>

How to get host name with port from a http or https request

I'm late to the party, but I had this same issue working with Java 8.

This is what worked for me, on the HttpServletRequest request object.

request.getHeader("origin");

and

request.getHeader("referer");

How I came to that conclusion:

I have a java app running on http://localhost:3000 making a Http Post to another java app I have running on http://localhost:8080.

From the Java code running on http://localhost:8080 I couldn't get the http://localhost:3000 from the HttpServletRequest using the answers above. For me using the getHeader method with the correct string input worked.

request.getHeader("origin") gave me "http://localhost:3000" which is what I wanted.

request.getHeader("referer") gave me "http://localhost:3000/xxxx" where xxxx is full URL I have from the requesting app.

Show popup after page load

When the DOM is finished loading you can add your code in the $(document).ready() function.

Remove the onclick from here:

<input type="submit" name="submit" value="Submit" onClick="PopUp()" />

Try this:

$(document).ready(function(){
   setTimeout(function(){
      PopUp();
   },5000); // 5000 to load it after 5 seconds from page load
});

@Html.DropDownListFor how to set default value

try this

 @Html.DropDownListFor(model => model.UserName, new List<SelectListItem> 
   { new SelectListItem{Text="Active", Value="True",Selected =true },
     new SelectListItem{Text="Deactive", Value="False"}})

sed whole word search and replace

Use \b for word boundaries:

sed -i 's/\boldtext\b/newtext/g' <file>

Module 'tensorflow' has no attribute 'contrib'

I used tensorflow 1.8 to train my model and there is no problem for now. Tensorflow 2.0 alpha is not suitable with object detection API

Days between two dates?

Assuming you’ve literally got two date objects, you can subtract one from the other and query the resulting timedelta object for the number of days:

>>> from datetime import date
>>> a = date(2011,11,24)
>>> b = date(2011,11,17)
>>> a-b
datetime.timedelta(7)
>>> (a-b).days
7

And it works with datetimes too — I think it rounds down to the nearest day:

>>> from datetime import datetime
>>> a = datetime(2011,11,24,0,0,0)
>>> b = datetime(2011,11,17,23,59,59)
>>> a-b
datetime.timedelta(6, 1)
>>> (a-b).days
6

How do I read a response from Python Requests?

If the response is in json you could do something like (python3):

import json
import requests as reqs

# Make the HTTP request.
response = reqs.get('http://demo.ckan.org/api/3/action/group_list')

# Use the json module to load CKAN's response into a dictionary.
response_dict = json.loads(response.text)

for i in response_dict:
    print("key: ", i, "val: ", response_dict[i])

To see everything in the response you can use .__dict__:

print(response.__dict__)

Object of class DateTime could not be converted to string

Try this:

$Date = $row['valdate']->format('d/m/Y'); // the result will 01/12/2015

NOTE: $row['valdate'] its a value date in the database

What's the difference between implementation and compile in Gradle?

Compile configuration was deprecated and should be replaced by implementation or api.

You can read the docs at https://docs.gradle.org/current/userguide/java_library_plugin.html#sec:java_library_separation.

The brief part being-

The key difference between the standard Java plugin and the Java Library plugin is that the latter introduces the concept of an API exposed to consumers. A library is a Java component meant to be consumed by other components. It's a very common use case in multi-project builds, but also as soon as you have external dependencies.

The plugin exposes two configurations that can be used to declare dependencies: api and implementation. The api configuration should be used to declare dependencies which are exported by the library API, whereas the implementation configuration should be used to declare dependencies which are internal to the component.

For further explanation refer to this image. Brief explanation

Object Dump JavaScript

Just use:

console.dir(object);

you will get a nice clickable object representation. Works in Chrome and Firefox

"Could not find bundler" error

The command is bundle update (there is no "r" in the "bundle").

To check if bundler is installed do : gem list bundler or even which bundle and the command will list either the bundler version or the path to it. If nothing is shown, then install bundler by typing gem install bundler.

How to get raw text from pdf file using java

You can use iText for do such things

//iText imports

import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;

for example:

try {     
    PdfReader reader = new PdfReader(INPUTFILE);
    int n = reader.getNumberOfPages(); 
    String str=PdfTextExtractor.getTextFromPage(reader, 2); //Extracting the content from a particular page.
    System.out.println(str);
    reader.close();
} catch (Exception e) {
    System.out.println(e);
}

another one

try {

    PdfReader reader = new PdfReader("c:/temp/test.pdf");
    System.out.println("This PDF has "+reader.getNumberOfPages()+" pages.");
    String page = PdfTextExtractor.getTextFromPage(reader, 2);
    System.out.println("Page Content:\n\n"+page+"\n\n");
    System.out.println("Is this document tampered: "+reader.isTampered());
    System.out.println("Is this document encrypted: "+reader.isEncrypted());
} catch (IOException e) {
    e.printStackTrace();
}

the above examples can only extract the text, but you need to do some more to remove hyperlinks, bullets, heading & numbers.

How to delete and update a record in Hive

As of Hive version 0.14.0: INSERT...VALUES, UPDATE, and DELETE are now available with full ACID support.

INSERT ... VALUES Syntax:

INSERT INTO TABLE tablename [PARTITION (partcol1[=val1], partcol2[=val2] ...)] VALUES values_row [, values_row ...]

Where values_row is: ( value [, value ...] ) where a value is either null or any valid SQL literal

UPDATE Syntax:

UPDATE tablename SET column = value [, column = value ...] [WHERE expression]

DELETE Syntax:

DELETE FROM tablename [WHERE expression]

Additionally, from the Hive Transactions doc:

If a table is to be used in ACID writes (insert, update, delete) then the table property "transactional" must be set on that table, starting with Hive 0.14.0. Without this value, inserts will be done in the old style; updates and deletes will be prohibited.

Hive DML reference:
https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DML
Hive Transactions reference:
https://cwiki.apache.org/confluence/display/Hive/Hive+Transactions

Set value of hidden field in a form using jQuery's ".val()" doesn't work

Using val() didn't work for me. I had to use .attr() everywhere. Also I had different types of inputs and had to be pretty explicit in the case of check boxes and select menus.

Update textfield

$('#model_name').attr('value',nameVal);

Update image next to file input

$('#img-avatar').attr('src', avatarThumbUrl);

Update boolean

if (isActive) {
    $('#model_active').attr('checked',"checked");
} else {
    $('#model_active').attr('checked', null) ;
}

Update select (with number or string)

$('#model_framerate').children().each(function(i, el){
    var v = $(el).val();
    if (v === String(framerateVal)) { 
        $(el).attr('selected','selected');
    } else {
        $(el).attr('selected',null);
    }
}

www-data permissions?

As stated in an article by Slicehost:

User setup

So let's start by adding the main user to the Apache user group:

sudo usermod -a -G www-data demo

That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.

You will need to log out and log back in again to enable the group change.

Check the groups now:

groups
...
# demo www-data

So now I am a member of two groups: My own (demo) and the Apache group (www-data).

Folder setup

Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).

Let's set that up:

sudo chgrp -R www-data /home/demo/public_html

As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.

If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.

Setgid

Good so far, but remember the command we just gave only affects existing folders. What about anything new?

We can set the ownership so anything new is also in the 'www-data' group.

The first command will change the permissions for the public_html directory to include the "setgid" bit:

sudo chmod 2750 /home/demo/public_html

That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.

If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:

sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads

The permissions only need to be set once as new files will automatically be assigned the correct ownership.

Using :before and :after CSS selector to insert Html

content doesn't support HTML, only text. You should probably use javascript, jQuery or something like that.

Another problem with your code is " inside a " block. You should mix ' and " (class='headingDetail').

If content did support HTML you could end up in an infinite loop where content is added inside content.

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

It is common to use the MAC address is associated with the network card.

The address is available in Java 6 through through the following API:

Java 6 Docs for Hardware Address

I haven't used it in Java, but for other network identification applications it has been helpful.

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

PDO Prepared Inserts multiple rows in single query

what about something like this:

        if(count($types_of_values)>0){
         $uid = 1;
         $x = 0;
         $sql = "";
         $values = array();
          foreach($types_of_values as $k=>$v){
            $sql .= "(:id_$k,:kind_of_val_$k), ";
            $values[":id_$k"] = $uid;
            $values[":kind_of_val_$k"] = $v;
          }
         $sql = substr($sql,0,-2);
         $query = "INSERT INTO table (id,value_type) VALUES $sql";
         $res = $this->db->prepare($query);
         $res->execute($values);            
        }

The idea behind this is to cycle through your array values, adding "id numbers" to each loop for your prepared statement placeholders while at the same time, you add the values to your array for the binding parameters. If you don't like using the "key" index from the array, you could add $i=0, and $i++ inside the loop. Either works in this example, even if you have associative arrays with named keys, it would still work providing the keys were unique. With a little work it would be fine for nested arrays too..

**Note that substr strips the $sql variables last space and comma, if you don't have a space you'd need to change this to -1 rather than -2.

How to use local docker images with Minikube?

One approach is to build the image locally and then do:

docker save imageNameGoesHere | pv | (eval $(minikube docker-env) && docker load)

minikube docker-env might not return the correct info running under a different user / sudo. Instead you can run sudo -u yourUsername minikube docker-env.

It should return something like:

export DOCKER_TLS_VERIFY="1"
export DOCKER_HOST="tcp://192.168.99.100:2376"
export DOCKER_CERT_PATH="/home/chris/.minikube/certs"
export DOCKER_API_VERSION="1.23"
# Run this command to configure your shell:
# eval $(minikube docker-env)

Jupyter Notebook not saving: '_xsrf' argument missing from post

I also came across the same error. I just opened another non-running Juputer notebook and an error is automatically gone.

Programmatically add custom event in the iPhone Calendar

Update for swift 4 for Dashrath answer

import UIKit
import EventKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let eventStore = EKEventStore()

        eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in

            if (granted) && (error == nil) {


                let event = EKEvent(eventStore: eventStore)

                event.title = "My Event"
                event.startDate = Date(timeIntervalSinceNow: TimeInterval())
                event.endDate = Date(timeIntervalSinceNow: TimeInterval())
                event.notes = "Yeah!!!"
                event.calendar = eventStore.defaultCalendarForNewEvents

                var event_id = ""
                do{
                    try eventStore.save(event, span: .thisEvent)
                    event_id = event.eventIdentifier
                }
                catch let error as NSError {
                    print("json error: \(error.localizedDescription)")
                }

                if(event_id != ""){
                    print("event added !")
                }
            }
        })
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

also don't forget to add permission for calendar usage image for privary setting

Can't connect to docker from docker-compose

try this:

sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose

Cannot install packages inside docker Ubuntu image

You need to update the package list in your Ubuntu:

$ sudo apt-get update
$ sudo apt-get install <package_name>

How to Install Font Awesome in Laravel Mix

the path you are using is not correct you could just open the node_module and find the path of font-awesome. use could use js or svg font but i prefer the css style.

at first use this command to install font-awesome-free npm install --save-dev @fortawesome/fontawesome-free

after that you can do this

@import "~@fortawesome/fontawesome-free/scss/fontawesome";
@import "~@fortawesome/fontawesome-free/scss/regular";
@import "~@fortawesome/fontawesome-free/scss/solid";
@import "~@fortawesome/fontawesome-free/scss/brands";

and I copy the font path like below this is optional

.copy('node_modules/@fortawesome/fontawesome-free/webfonts', 'public/fonts');

and finally just run the script npm run dev or npm run watch in laravel

Cast Object to Generic Type for returning

You have to use a Class instance because of the generic type erasure during compilation.

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
    try {
        return clazz.cast(o);
    } catch(ClassCastException e) {
        return null;
    }
}

The declaration of that method is:

public T cast(Object o)

This can also be used for array types. It would look like this:

final Class<int[]> intArrayType = int[].class;
final Object someObject = new int[]{1,2,3};
final int[] instance = convertInstanceOfObject(someObject, intArrayType);

Note that when someObject is passed to convertToInstanceOfObject it has the compile time type Object.

How to run a script file remotely using SSH

Make the script executable by the user "Kev" and then remove the try it running through the command sh kev@server1 /test/foo.sh

Changing MongoDB data store directory

Copy the contents of /var/lib/mongodb to /data/db. The files you should be looking for should have names like your_db_name.ns and your_dbname.n where n is a number starting with 0. If you do not see such files under /var/lib/mongodb, search for them on your filesystem.

Once copied over, use --dbpath=/data/db when starting MongoDB via the mongod command.

Why does the html input with type "number" allow the letter 'e' to be entered in the field?

We can make it So simple like below

_x000D_
_x000D_
<input type="number"  onkeydown="javascript: return event.keyCode == 69 ? false : true" />
_x000D_
_x000D_
_x000D_

Updated Answer

we can make it even more simple as @88 MPG suggests

_x000D_
_x000D_
<input type="number" onkeydown="return event.keyCode !== 69" />
_x000D_
_x000D_
_x000D_

Windows service with timer

First approach with Windows Service is not easy..

A long time ago, I wrote a C# service.

This is the logic of the Service class (tested, works fine):

namespace MyServiceApp
{
    public class MyService : ServiceBase
    {
        private System.Timers.Timer timer;

        protected override void OnStart(string[] args)
        {
            this.timer = new System.Timers.Timer(30000D);  // 30000 milliseconds = 30 seconds
            this.timer.AutoReset = true;
            this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);
            this.timer.Start();
        }

        protected override void OnStop()
        {
            this.timer.Stop();
            this.timer = null;
        }

        private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            MyServiceApp.ServiceWork.Main(); // my separate static method for do work
        }

        public MyService()
        {
            this.ServiceName = "MyService";
        }

        // service entry point
        static void Main()
        {
            System.ServiceProcess.ServiceBase.Run(new MyService());
        }
    }
}

I recommend you write your real service work in a separate static method (why not, in a console application...just add reference to it), to simplify debugging and clean service code.

Make sure the interval is enough, and write in log ONLY in OnStart and OnStop overrides.

Hope this helps!

Bootstrap col-md-offset-* not working

Kindly use offset-md-4 instead of col-md-offset-4 in bootstrap 4. It's little changes adopted in bootstrap 4.

For more info

finished with non zero exit value

I was also getting this issue.

  • I generally face this issue when I import some sample or already existing module into my project.
  • I just added latest v7 and v4 to my project from maven in android studio and got it fixed
  • Removed duplicate dependencies from project like wise if your library project and application project are using v7 or v4 or any other library , they should be of same version. or try to have it only in your library project

What is the single most influential book every programmer should read?

The TCP/IP Guide, by Charles M. Kozierok

Although it is described as an 'encyclopedic reference', it is incredibly readable as a narrative.

This author provides a very , very, very well written, comprehensive, introduction to networking and the infrastructure that underlies the web. Something all programmers ought to know.

For me it is the natural follow-on from Charles Petzold's 'Code'. If "Code" explains to the layman how computers work, 'The TCP/IP Guide' explains how they connect together.

If you gave a 12 year old geek a copy 'Code' and a copy of 'The TCP/IP Guide' - they'd be building the next Google by the age of 17.

In other words, if I could go back in time and tell myself to read a specific book at the beginning of my career as a developer, this (plus Code) is up there in the top of my list.

How does MySQL CASE work?

CASE in MySQL is both a statement and an expression, where each usage is slightly different.

As a statement, CASE works much like a switch statement and is useful in stored procedures, as shown in this example from the documentation (linked above):

DELIMITER |

CREATE PROCEDURE p()
  BEGIN
    DECLARE v INT DEFAULT 1;

    CASE v
      WHEN 2 THEN SELECT v;
      WHEN 3 THEN SELECT 0;
      ELSE
        BEGIN -- Do other stuff
        END;
    END CASE;
  END;
  |

However, as an expression it can be used in clauses:

SELECT *
  FROM employees
  ORDER BY
    CASE title
      WHEN "President" THEN 1
      WHEN "Manager" THEN 2
      ELSE 3
    END, surname

Additionally, both as a statement and as an expression, the first argument can be omitted and each WHEN must take a condition.

SELECT *
  FROM employees
  ORDER BY
    CASE 
      WHEN title = "President" THEN 1
      WHEN title = "Manager" THEN 2
      ELSE 3
    END, surname

I provided this answer because the other answer fails to mention that CASE can function both as a statement and as an expression. The major difference between them is that the statement form ends with END CASE and the expression form ends with just END.

Changing the size of a column referenced by a schema-bound view in SQL Server

Check the column collation. This script might change the collation to the table default. Add the current collation to the script.

Using moment.js to convert date to string "MM/dd/yyyy"

Try this:

var momentObj = $("#start_ts").datepicker("getDate");

var yourDate = momentObj.format('L');

Enable & Disable a Div and its elements in Javascript

If you want to disable all the div's controls, you can try adding a transparent div on the div to disable, you gonna make it unclickable, also use fadeTo to create a disable appearance.

try this.

$('#DisableDiv').fadeTo('slow',.6);
$('#DisableDiv').append('<div style="position: absolute;top:0;left:0;width: 100%;height:100%;z-index:2;opacity:0.4;filter: alpha(opacity = 50)"></div>');

Using pickle.dump - TypeError: must be str, not bytes

The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

needs to be:

f = open('varstor.txt','wb')

Display PNG image as response to jQuery AJAX request

Method 1

You should not make an ajax call, just put the src of the img element as the url of the image.

This would be useful if you use GET instead of POST

<script type="text/javascript" > 

  $(document).ready( function() { 
      $('.div_imagetranscrits').html('<img src="get_image_probes_via_ajax.pl?id_project=xxx" />')
  } );

</script>

Method 2

If you want to POST to that image and do it the way you do (trying to parse the contents of the image on the client side, you could try something like this: http://en.wikipedia.org/wiki/Data_URI_scheme

You'll need to encode the data to base64, then you could put data:[<MIME-type>][;charset=<encoding>][;base64],<data> into the img src

as example:

<img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==" alt="Red dot img" />

To encode to base64:

how to refresh Select2 dropdown menu after ajax loading different content?

select2 has the placeholder parameter. Use that one

$("#state").select2({
   placeholder: "Choose a Country"
 });

Why is the console window closing immediately once displayed my output?

the issue here is that their Hello World Program is showing up then it would immediately close.
why is that?

Because it's finished. When console applications have completed executing and return from their main method, the associated console window automatically closes. This is expected behavior.

If you want to keep it open for debugging purposes, you'll need to instruct the computer to wait for a key press before ending the app and closing the window.

The Console.ReadLine method is one way of doing that. Adding this line to the end of your code (just before the return statement) will cause the application to wait for you to press a key before exiting.

Alternatively, you could start the application without the debugger attached by pressing Ctrl+F5 from within the Visual Studio environment, but this has the obvious disadvantage of preventing you from using the debugging features, which you probably want at your disposal when writing an application.

The best compromise is probably to call the Console.ReadLine method only when debugging the application by wrapping it in a preprocessor directive. Something like:

#if DEBUG
    Console.WriteLine("Press enter to close...");
    Console.ReadLine();
#endif

You might also want the window to stay open if an uncaught exception was thrown. To do that you can put the Console.ReadLine(); in a finally block:

#if DEBUG
    try
    {
        //...
    }
    finally
    {
        Console.WriteLine("Press enter to close...");
        Console.ReadLine();
    }
#endif

How do you import classes in JSP?

Use Page Directive to import a Class in JSP page. Page Directive Uses 11 Different types of Attributes , One of them is "import". Page Directive with import Attribute Allows you to Mention more than one package at the same place separated by Commas(,). Alternatively you can have multiple instances of page element each one with Different package .

For Example:

 <%@ page import = "java.io.*" %>
 <%@ page import = "java.io.*", "java.util.*"%>

Note : the import attribute should be placed before the element that calls the importd class .

How to perform runtime type checking in Dart?

Just to clarify a bit the difference between is and runtimeType. As someone said already (and this was tested with Dart V2+) the following code:

class Foo { 
  Type get runtimeType => String;
}
main() {
  var foo = new Foo();
  if (foo is Foo) {
    print("it's a foo!");
  }
  print("type is ${foo.runtimeType}");

}

will output:

it's a foo! 
type is String

Which is wrong. Now, I can't see the reason why one should do such a thing...

HTML5 Number Input - Always show 2 decimal places

Take a look at this:

 <input type="number" step="0.01" />

java: ArrayList - how can I check if an index exists?

You could check for the size of the array.

package sojava;
import java.util.ArrayList;

public class Main {
    public static Object get(ArrayList list, int index) {
        if (list.size() > index) { return list.get(index); }
        return null;
    }

    public static void main(String[] args) {
        ArrayList list = new ArrayList();
        list.add(""); list.add(""); list.add("");        
        System.out.println(get(list, 4));
        // prints 'null'
    }
}

generate days from date range

MSSQL Query

select datetable.Date 
from (
    select DATEADD(day,-(a.a + (10 * b.a) + (100 * c.a)),getdate()) AS Date
    from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4
     union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a

    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4
     union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b

    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4
     union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
) datetable
where datetable.Date between '2014-01-20' and '2014-01-24' 
order by datetable.Date DESC

Output

Date
-----
2014-01-23 12:35:25.250
2014-01-22 12:35:25.250
2014-01-21 12:35:25.250
2014-01-20 12:35:25.250

How can I process each letter of text using Javascript?

One more solution...

var strg= 'This is my string';
for(indx in strg){
  alert(strg[indx]);
}

Clearing all cookies with JavaScript

After testing almost ever method listed in multiple style of browsers on multiple styles of cookies, I found almost nothing here works even 50%.

Please help correct as needed, but I'm going to throw my 2 cents in here. The following method breaks everything down and basically builds the cookie value string based on both the settings pieces as well as including a step by step build of the path string, starting with / of course.

Hope this helps others and I hope any criticism may come in the form of perfecting this method. At first I wanted a simple 1-liner as some others sought, but JS cookies are one of those things not so easily dealt with.

;(function() {
    if (!window['deleteAllCookies'] && document['cookie']) {
        window.deleteAllCookies = function(showLog) {
            var arrCookies = document.cookie.split(';'),
                arrPaths = location.pathname.replace(/^\//, '').split('/'), //  remove leading '/' and split any existing paths
                arrTemplate = [ 'expires=Thu, 01-Jan-1970 00:00:01 GMT', 'path={path}', 'domain=' + window.location.host, 'secure=' ];  //  array of cookie settings in order tested and found most useful in establishing a "delete"
            for (var i in arrCookies) {
                var strCookie = arrCookies[i];
                if (typeof strCookie == 'string' && strCookie.indexOf('=') >= 0) {
                    var strName = strCookie.split('=')[0];  //  the cookie name
                    for (var j=1;j<=arrTemplate.length;j++) {
                        if (document.cookie.indexOf(strName) < 0) break; // if this is true, then the cookie no longer exist
                        else {
                            var strValue = strName + '=; ' + arrTemplate.slice(0, j).join('; ') + ';';  //  made using the temp array of settings, putting it together piece by piece as loop rolls on
                            if (j == 1) document.cookie = strValue;
                            else {
                                for (var k=0;k<=arrPaths.length;k++) {
                                    if (document.cookie.indexOf(strName) < 0) break; // if this is true, then the cookie no longer exist
                                    else {
                                        var strPath = arrPaths.slice(0, k).join('/') + '/'; //  builds path line 
                                        strValue = strValue.replace('{path}', strPath);
                                        document.cookie = strValue;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            showLog && window['console'] && console.info && console.info("\n\tCookies Have Been Deleted!\n\tdocument.cookie = \"" + document.cookie + "\"\n");
            return document.cookie;
        }
    }
})();

How do I prevent Conda from activating the base environment by default?

To disable auto activation of conda base environment in terminal:

conda config --set auto_activate_base false

To activate conda base environment:

conda activate

Android ImageButton with a selected state?

ToggleImageButton which implements Checkable interface and supports OnCheckedChangeListener and android:checked xml attribute:

public class ToggleImageButton extends ImageButton implements Checkable {
    private OnCheckedChangeListener onCheckedChangeListener;

    public ToggleImageButton(Context context) {
        super(context);
    }

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

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

    private void setChecked(AttributeSet attrs) {
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ToggleImageButton);
        setChecked(a.getBoolean(R.styleable.ToggleImageButton_android_checked, false));
        a.recycle();
    }

    @Override
    public boolean isChecked() {
        return isSelected();
    }

    @Override
    public void setChecked(boolean checked) {
        setSelected(checked);

        if (onCheckedChangeListener != null) {
            onCheckedChangeListener.onCheckedChanged(this, checked);
        }
    }

    @Override
    public void toggle() {
        setChecked(!isChecked());
    }

    @Override
    public boolean performClick() {
        toggle();
        return super.performClick();
    }

    public OnCheckedChangeListener getOnCheckedChangeListener() {
        return onCheckedChangeListener;
    }

    public void setOnCheckedChangeListener(OnCheckedChangeListener onCheckedChangeListener) {
        this.onCheckedChangeListener = onCheckedChangeListener;
    }

    public static interface OnCheckedChangeListener {
        public void onCheckedChanged(ToggleImageButton buttonView, boolean isChecked);
    }
}

res/values/attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="ToggleImageButton">
        <attr name="android:checked" />
    </declare-styleable>
</resources>

Image library for Python 3

The "friendly PIL fork" Pillow works on Python 2 and 3. Check out the Github project for support matrix and so on.

Redirect to external URL with return in laravel

Define the url you want to redirect in $url

Then just use

return Redirect::away($url);

If you want to redirect inside your views use

return Redirect::to($url);

Read more about Redirect here

Update 1 :

Here is the simple example

return Redirect::to('http://www.google.com');

Update 2 :

As the Questioner wants to return in the same page

$triggersms = file_get_contents('http://www.cloud.smsindiahub.in/vendorsms/pushsms.aspx?user=efg&password=abcd&msisdn=9197xxx2&sid=MYID&msg=Hello');
return $triggersms;

Intercept and override HTTP requests from WebView

It looks like API level 11 has support for what you need. See WebViewClient.shouldInterceptRequest().

How to allow download of .json file with ASP.NET

If you want to manually add support to your site, you can just add the following to your web.config in the system.webServer section:

<staticContent>
    <mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>

This will add a "local" configuration under IIS. This does not work in IIS6, but does work in IIS7 and newer.

How to avoid precompiled headers

Right click project solution

Properties -> Configuration Properties -> C/C++ -> Precompiled Headers

  1. Click on "Precompiled Headers" change to "Not Using Precompiled Headers".

  2. Erase the "pch.h"/"stdafx.h" field in "Precompiled Header File" for the EOF error at the end of the build for the project.

  3. Then you can feel free to delete the pch./stdafx. files in your project

Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I had same problem and despite having jstl

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

I had to add 'standard' as well:

<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

Also, as mentioned in previous post:

How to change MySQL data directory?

First , you should know where is your config file ? where is your config file ?

IF you installed with apt-get or yum install ?

config file may appear in

/etc/mysql/my.cnf

datafile may appear in

/var/lib/mysql

and what you should do is

  1. stop mysql
  2. change the mysql data to new dirctory
  3. change the config file
  4. reload the config file
  5. restart mysql

and then jobs done.

But if you didn't install it with apt or yum,the direcotry may not like this ,and you can find the mysql files with

whereis mysql

Delete dynamically-generated table row using jQuery

You need to use event delegation because those buttons don't exist on load:

http://jsfiddle.net/isherwood/Z7fG7/1/

 $(document).on('click', 'button.removebutton', function () { // <-- changes
     alert("aa");
     $(this).closest('tr').remove();
     return false;
 });

Get top 1 row of each group

;WITH cte AS
(
   SELECT *,
         ROW_NUMBER() OVER (PARTITION BY DocumentID ORDER BY DateCreated DESC) AS rn
   FROM DocumentStatusLogs
)
SELECT *
FROM cte
WHERE rn = 1

If you expect 2 entries per day, then this will arbitrarily pick one. To get both entries for a day, use DENSE_RANK instead

As for normalised or not, it depends if you want to:

  • maintain status in 2 places
  • preserve status history
  • ...

As it stands, you preserve status history. If you want latest status in the parent table too (which is denormalisation) you'd need a trigger to maintain "status" in the parent. or drop this status history table.

C: scanf to array

The %d conversion specifier will only convert one decimal integer. It doesn't know that you're passing an array, it can't modify its behavior based on that. The conversion specifier specifies the conversion.

There is no specifier for arrays, you have to do it explicitly. Here's an example with four conversions:

if(scanf("%d %d %d %d", &array[0], &array[1], &array[2], &array[3]) == 4)
  printf("got four numbers\n");

Note that this requires whitespace between the input numbers.

If the id is a single 11-digit number, it's best to treat as a string:

char id[12];

if(scanf("%11s", id) == 1)
{
  /* inspect the *character* in id[0], compare with '1' or '2' for instance. */
}

Checking for an empty field with MySQL

Yes, what you are doing is correct. You are checking to make sure the email field is not an empty string. NULL means the data is missing. An empty string "" is a blank string with the length of 0.

You can add the null check also

AND (email != "" OR email IS NOT NULL)

Removing object from array in Swift 3

For Swift 3, you can use index(where:) and include a closure that does the comparison of an object in the array ($0) with whatever you are looking for.

var array = ["alpha", "beta", "gamma"]
if let index = array.index(where: {$0 == "beta"}) {
  array.remove(at: index)
}

Convert multiple rows into one with comma as separator

You can use this query to do the above task:

DECLARE @test NVARCHAR(max)  
SELECT @test = COALESCE(@test + ',', '') + field2 FROM #test
SELECT field2 = @test 

For detail and step by step explanation visit the following link http://oops-solution.blogspot.com/2011/11/sql-server-convert-table-column-data.html

Using array map to filter results with if conditional

Here's some info if someone comes upon this in 2019.

I think reduce vs map + filter might be somewhat dependent on what you need to loop through. Not sure on this but reduce does seem to be slower.

One thing is for sure - if you're looking for performance improvements the way you write the code is extremely important!

Here a JS perf test that shows the massive improvements when typing out the code fully rather than checking for "falsey" values (e.g. if (string) {...}) or returning "falsey" values where a boolean is expected.

Hope this helps someone

not:first-child selector

div li~li {
    color: red;
}

Supports IE7

Set folder browser dialog start location

In my case, it was an accidental double escaping.

this works:

SelectedPath = @"C:\Program Files\My Company\My product";

this doesn't:

SelectedPath = @"C:\\Program Files\\My Company\\My product";

Send POST data via raw json with postman

Unlike jQuery in order to read raw JSON you will need to decode it in PHP.

print_r(json_decode(file_get_contents("php://input"), true));

php://input is a read-only stream that allows you to read raw data from the request body.

$_POST is form variables, you will need to switch to form radiobutton in postman then use:

foo=bar&foo2=bar2

To post raw json with jquery:

$.ajax({
    "url": "/rest/index.php",
    'data': JSON.stringify({foo:'bar'}),
    'type': 'POST',
    'contentType': 'application/json'
});

XML Carriage return encoding

A browser isn't going to show you white space reliably. I recommend the Linux 'od' command to see what's really in there. Comforming XML parsers will respect all of the methods you listed.

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

Edit: this information is for visualvm specifically, not for any other java app

As mentioned by others, you need to modify the visualvm.conf

For the latest version of JvisualVM 1.3.6 on Mac, the install directories have changed.

It is currently in /Applications/VisualVM.app/Contents/Resources/visualvm/etc/visualvm.conf.

However this may depend on where you have installed VisualVM. The easiest way to find where your VisualVM is to start it, and then look at the process using:

ps -ef | grep VisualVM

You will see something like:

... -Dnetbeans.dirs=/Applications/VisualVM.app/Contents/Resources/visualvm/visualvm...

You want to take the netbeans.dir property and look up a directory and you will find the etc folder.

Uncomment this line in the visualvm.conf and change the path to the jdk

visualvm_jdkhome="/path/to/jdk"

Additionally, if you are having slowness with your visualvm and you have a lot of memory, I would suggest greatly increasing the amount of memory available and running it in server mode:

visualvm_default_options="-J-XX:MaxPermSize=96m -J-Xmx2048m -J-Xms2048m -J-server -J-XX:+UseCompressedOops -J-XX:+UseConcMarkSweepGC -J-XX:+UseParNewGC -J-XX:NewRatio=2 -J-Dnetbeans.accept_license_class=com.sun.tools.visualvm.modules.startup.AcceptLicense -J-Dsun.jvmstat.perdata.syncWaitMs=10000 -J-Dsun.java2d.noddraw=true -J-Dsun.java2d.d3d=false"

Android Paint: .measureText() vs .getTextBounds()

The different between getTextBounds and measureText is described with the image below.

In short,

  1. getTextBounds is to get the RECT of the exact text. The measureText is the length of the text, including the extra gap on the left and right.

  2. If there are spaces between the text, it is measured in measureText but not including in the length of the TextBounds, although the coordinate get shifted.

  3. The text could be tilted (Skew) left. In this case, the bounding box left side would exceed outside the measurement of the measureText, and the overall length of the text bound would be bigger than measureText

  4. The text could be tilted (Skew) right. In this case, the bounding box right side would exceed outside the measurement of the measureText, and the overall length of the text bound would be bigger than measureText

enter image description here

Ansible: How to delete files and folders inside a directory?

Assuming you are always in Linux, try the find cmd.

- name: Clean everything inside {{ item }}
  shell: test -d {{ item }} && find {{ item }} -path '{{ item }}/*' -prune -exec rm -rf {} \;
  with_items: [/home/mydata/web]

This should wipe out files/folders/hidden under /home/mydata/web

Get bottom and right position of an element

You can use the .position() for this

var link = $(element);
var position = link.position(); //cache the position
var right = $(window).width() - position.left - link.width();
var bottom = $(window).height() - position.top - link.height();

Unable to copy a file from obj\Debug to bin\Debug

Well i have the same problem, my way to fix it was to stop and disable the "application experience" service in Windows.

Go to first line in a file in vim?

Type "gg" in command mode. This brings the cursor to the first line.

The role of #ifdef and #ifndef

"#if one" means that if "#define one" has been written "#if one" is executed otherwise "#ifndef one" is executed.

This is just the C Pre-Processor (CPP) Directive equivalent of the if, then, else branch statements in the C language.

i.e. if {#define one} then printf("one evaluates to a truth "); else printf("one is not defined "); so if there was no #define one statement then the else branch of the statement would be executed.

Show/Hide the console window of a C# console application

Here’s how:

using System.Runtime.InteropServices;

[DllImport("kernel32.dll")]
static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

const int SW_HIDE = 0;
const int SW_SHOW = 5;

var handle = GetConsoleWindow();

// Hide
ShowWindow(handle, SW_HIDE);

// Show
ShowWindow(handle, SW_SHOW);

Difference between objectForKey and valueForKey?

Here's a great reason to use objectForKey: wherever possible instead of valueForKey: - valueForKey: with an unknown key will throw NSUnknownKeyException saying "this class is not key value coding-compliant for the key ".

Lookup City and State by Zip Google Geocode Api

I found a couple of ways to do this with web based APIs. I think the US Postal Service would be the most accurate, since Zip codes are their thing, but Ziptastic looks much easier.

Using the US Postal Service HTTP/XML API

According to this page on the US Postal Service website which documents their XML based web API, specifically Section 4.0 (page 22) of this PDF document, they have a URL where you can send an XML request containing a 5 digit Zip Code and they will respond with an XML document containing the corresponding City and State.

According to their documentation, here's what you would send:

http://SERVERNAME/ShippingAPITest.dll?API=CityStateLookup&XML=<CityStateLookupRequest%20USERID="xxxxxxx"><ZipCode ID= "0"><Zip5>90210</Zip5></ZipCode></CityStateLookupRequest>

And here's what you would receive back:

<?xml version="1.0"?> 
<CityStateLookupResponse> 
    <ZipCode ID="0"> 
        <Zip5>90210</Zip5> 
        <City>BEVERLY HILLS</City> 
        <State>CA</State> 
    </ZipCode> 
</CityStateLookupResponse>

USPS does require that you register with them before you can use the API, but, as far as I could tell, there is no charge for access. By the way, their API has some other features: you can do Address Standardization and Zip Code Lookup, as well as the whole suite of tracking, shipping, labels, etc.

Using the Ziptastic HTTP/JSON API (no longer supported)

Update: As of August 13, 2017, Ziptastic is now a paid API and can be found here

This is a pretty new service, but according to their documentation, it looks like all you need to do is send a GET request to http://ziptasticapi.com, like so:

GET http://ziptasticapi.com/48867

And they will return a JSON object along the lines of:

{"country": "US", "state": "MI", "city": "OWOSSO"}

Indeed, it works. You can test this from a command line by doing something like:

curl http://ziptasticapi.com/48867 

jquery - How to determine if a div changes its height or any css attribute?

For future sake I'll post this. If you do not need to support < IE11 then you should use MutationObserver.

Here is a link to the caniuse js MutationObserver

Simple usage with powerful results.

    var observer = new MutationObserver(function (mutations) {
        //your action here
    });

    //set up your configuration
    //this will watch to see if you insert or remove any children
    var config = { subtree: true, childList: true };

    //start observing
    observer.observe(elementTarget, config);

When you don't need to observe any longer just disconnect.

    observer.disconnect();

Check out the MDN documentation for more information

Change the color of a checked menu item in a navigation drawer

Here's how you can do it in your Activity's onCreate method:

NavigationView navigationView = findViewById(R.id.nav_view);
ColorStateList csl = new ColorStateList(
    new int[][] {
        new int[] {-android.R.attr.state_checked}, // unchecked
        new int[] { android.R.attr.state_checked}  // checked
    },
    new int[] {
        Color.BLACK,
        Color.RED
    }
);
navigationView.setItemTextColor(csl);
navigationView.setItemIconTintList(csl);

What are the advantages of NumPy over regular Python lists?

Alex mentioned memory efficiency, and Roberto mentions convenience, and these are both good points. For a few more ideas, I'll mention speed and functionality.

Functionality: You get a lot built in with NumPy, FFTs, convolutions, fast searching, basic statistics, linear algebra, histograms, etc. And really, who can live without FFTs?

Speed: Here's a test on doing a sum over a list and a NumPy array, showing that the sum on the NumPy array is 10x faster (in this test -- mileage may vary).

from numpy import arange
from timeit import Timer

Nelements = 10000
Ntimeits = 10000

x = arange(Nelements)
y = range(Nelements)

t_numpy = Timer("x.sum()", "from __main__ import x")
t_list = Timer("sum(y)", "from __main__ import y")
print("numpy: %.3e" % (t_numpy.timeit(Ntimeits)/Ntimeits,))
print("list:  %.3e" % (t_list.timeit(Ntimeits)/Ntimeits,))

which on my systems (while I'm running a backup) gives:

numpy: 3.004e-05
list:  5.363e-04

how to print float value upto 2 decimal place without rounding off

i'd suggest shorter and faster approach:

printf("%.2f", ((signed long)(fVal * 100) * 0.01f));

this way you won't overflow int, plus multiplication by 100 shouldn't influence the significand/mantissa itself, because the only thing that really is changing is exponent.

Parse query string into an array

If you're having a problem converting a query string to an array because of encoded ampersands

&amp;

then be sure to use html_entity_decode

Example:

// Input string //
$input = 'pg_id=2&amp;parent_id=2&amp;document&amp;video';

// Parse //
parse_str(html_entity_decode($input), $out);

// Output of $out //
array(
  'pg_id' => 2,
  'parent_id' => 2,
  'document' => ,
  'video' =>
)

Invalid shorthand property initializer

Use : instead of =

see the example below that gives an error

app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
    // insert into db
    const mew = {
        name = filter.clean(req.body.name.toString()),
        content = filter.clean(req.body.content.toString()),
        created: new Date()
    };

That gives Syntex Error: invalid shorthand proprty initializer.

Then i replace = with : that's solve this error.

app.post('/mews', (req, res) => {
if (isValidMew(req.body)) {
    // insert into db
    const mew = {
        name: filter.clean(req.body.name.toString()),
        content: filter.clean(req.body.content.toString()),
        created: new Date()
    };

Shuffle an array with python, randomize array item order with python

The other answers are the easiest, however it's a bit annoying that the random.shuffle method doesn't actually return anything - it just sorts the given list. If you want to chain calls or just be able to declare a shuffled array in one line you can do:

    import random
    def my_shuffle(array):
        random.shuffle(array)
        return array

Then you can do lines like:

    for suit in my_shuffle(['hearts', 'spades', 'clubs', 'diamonds']):

Filtering a list based on a list of booleans

filtered_list = [list_a[i] for i in range(len(list_a)) if filter[i]]

Validation of file extension before uploading file

<script type="text/javascript">

        function file_upload() {
            var imgpath = document.getElementById("<%=FileUpload1.ClientID %>").value;
            if (imgpath == "") {
                alert("Upload your Photo...");
                document.file.word.focus();
                return false;
            }
            else {
                // code to get File Extension..

                var arr1 = new Array;
                arr1 = imgpath.split("\\");
                var len = arr1.length;
                var img1 = arr1[len - 1];
                var filext = img1.substring(img1.lastIndexOf(".") + 1);
                // Checking Extension
                if (filext == "bmp" || filext == "gif" || filext == "png" || filext == "jpg" || filext == "jpeg" ) {
                    alert("Successfully Uploaded...")
                    return false;
                }
                else {
                    alert("Upload Photo with Extension ' bmp , gif, png , jpg , jpeg '");
                    document.form.word.focus();
                    return false;
                }
            }
        }

        function Doc_upload() {
            var imgpath = document.getElementById("<%=FileUpload2.ClientID %>").value;
            if (imgpath == "") {
                alert("Upload Agreement...");
                document.file.word.focus();
                return false;
            }
            else {
                // code to get File Extension..

                var arr1 = new Array;
                arr1 = imgpath.split("\\");
                var len = arr1.length;
                var img1 = arr1[len - 1];
                var filext = img1.substring(img1.lastIndexOf(".") + 1);
                // Checking Extension
                if (filext == "txt" || filext == "pdf" || filext == "doc") {
                    alert("Successfully Uploaded...")
                    return false;
                }
                else {
                    alert("Upload File with Extension ' txt , pdf , doc '");
                    document.form.word.focus();
                    return false;
                }
            }
        }
</script>

Cannot simply use PostgreSQL table name ("relation does not exist")

Postgres process query different from other RDMS. Put schema name in double quote before your table name like this, "SCHEMA_NAME"."SF_Bands"

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

Same error i faced in eclipse version Oxygen.3a Release (4.7.3a) . There is issue in Maven Dependencies mismatch.To solve i have updated my Pom.xml with following dependecies.

http://maven.apache.org/xsd/maven-4.0.0.xsd"> 4.0.0 com.netapp.junitnmactiopractice JunitAndMactioPractice 0.0.1-SNAPSHOT

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <java.version>1.8</java.version>
    <junit.jupiter.version>5.1.1</junit.jupiter.version>
    <junit.platform.version>1.1.1</junit.platform.version>
</properties>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
    </plugins>
</build>

<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>${junit.jupiter.version}</version>
    </dependency>
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-runner</artifactId>
        <version>${junit.platform.version}</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Add / remove input field dynamically with jQuery

enter image description here You should be able to create and remove input field dynamically by using jquery using this method(https://www.adminspress.com/onex/view/uaomui), Even you can able to generate input fields in bulk and export to string.

How to implement a custom AlertDialog View

The simplest lines of code that works for me are are follows:

AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setView(R.layout.layout_resource_id);
builder.show();

Whatever the type of layout(LinearLayout, FrameLayout, RelativeLayout) will work by setView and will just differ in the appearance and behavior.

Getting date format m-d-Y H:i:s.u from milliseconds

For PHP 8.0+

The bug has been recently fixed and now you can use UNIX timestamps with a fractional part.

$milliseconds = 1375010774123;

$d = new DateTime( '@'. $milliseconds/1000 );
print $d->format("m-d-Y H:i:s.u");

Output:

07-28-2013 11:26:14.123000

For PHP < 8.0

You need to specify the format of your UNIX timestamp before you can use it in the DateTime object. As noted in other answers, you can simply work around this bug by using createFromFormat() and number_format()

$milliseconds = 1375010774123;

$d = DateTime::createFromFormat('U.v', number_format($milliseconds/1000, 3, '.', ''));
print $d->format("m-d-Y H:i:s.u");

Output:

07-28-2013 11:26:14.123000

For PHP < 7.3

If you are still using PHP older than 7.3 you can replace U.v with U.u. It will not make any difference, but the millisecond format identifier is present only since PHP 7.3.

$milliseconds = 1375010774123;
//                                 V - Use microseconds instead of milliseconds
$d = DateTime::createFromFormat('U.u', number_format($milliseconds/1000, 3, '.', ''));
print $d->format("m-d-Y H:i:s.u");

Output:

07-28-2013 11:26:14.123000

Detect changed input text box

WORKING:

$("#ContentPlaceHolder1_txtNombre").keyup(function () {
    var txt = $(this).val();
        $('.column').each(function () {
            $(this).show();
            if ($(this).text().toUpperCase().indexOf(txt.toUpperCase()) == -1) {
                $(this).hide();
            }
        });
    //}
});

Android Use Done button on Keyboard to click button

Use this class in your layout :

public class ActionEditText extends EditText
{
    public ActionEditText(Context context)
    {
        super(context);
    }

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

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

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs)
    {
        InputConnection conn = super.onCreateInputConnection(outAttrs);
        outAttrs.imeOptions &= ~EditorInfo.IME_FLAG_NO_ENTER_ACTION;
        return conn;
    }

}

In xml:

<com.test.custom.ActionEditText
                android:id="@+id/postED"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:background="@android:color/transparent"
                android:gravity="top|left"
                android:hint="@string/msg_type_message_here"
                android:imeOptions="actionSend"
                android:inputType="textMultiLine"
                android:maxLines="5"
                android:padding="5dip"
                android:scrollbarAlwaysDrawVerticalTrack="true"
                android:textColor="@color/white"
                android:textSize="20sp" />

OpenCV NoneType object has no attribute shape

I also face the same issue "OpenCV NoneType object has no attribute shape" and i solve this by changing the image location. I also use the PyCharm IDE. Currently my image location and class file in the same folder. enter image description here

How can I have Github on my own server?

There is GitHub Enterprise to satisfy your needs. And there is an open source "clone" of Github Enterprise.

PS: Now Github provides unlimited private repositories, bitbucket does the same. you can give a try to both. There are several other solutions as well.

How to create a pulse effect using -webkit-animation - outward rings

Or if you want a ripple pulse effect, you could use this:

http://jsfiddle.net/Fy8vD/3041/

.gps_ring {
     border: 2px solid #fff;
     -webkit-border-radius: 50%;
     height: 18px;
     width: 18px;
     position: absolute;
     left:20px;
    top:214px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    opacity: 0.0;
}
.gps_ring:before {
    content:"";
    display:block;
    border: 2px solid #fff;
    -webkit-border-radius: 50%;
    height: 30px;
    width: 30px;
    position: absolute;
    left:-8px;
    top:-8px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-delay: 0.1s;
    opacity: 0.0;
}
.gps_ring:after {
    content:"";
    display:block;
    border:2px solid #fff;
    -webkit-border-radius: 50%;
    height: 50px;
    width: 50px;
    position: absolute;
    left:-18px;
    top:-18px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-delay: 0.2s;
    opacity: 0.0;
}
@-webkit-keyframes pulsate {
    0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
    50% {opacity: 1.0;}
    100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}

Why is the use of alloca() not considered good practice?

I don't think that anybody has mentioned this, but alloca also has some serious security issues not necessarily present with malloc (though these issues also arise with any stack based arrays, dynamic or not). Since the memory is allocated on the stack, buffer overflows/underflows have much more serious consequences than with just malloc.

In particular, the return address for a function is stored on the stack. If this value gets corrupted, your code could be made to go to any executable region of memory. Compilers go to great lengths to make this difficult (in particular by randomizing address layout). However, this is clearly worse than just a stack overflow since the best case is a SEGFAULT if the return value is corrupted, but it could also start executing a random piece of memory or in the worst case some region of memory which compromises your program's security.

Javascript format date / time

I don't think that can be done RELIABLY with built in methods on the native Date object. The toLocaleString method gets close, but if I am remembering correctly, it won't work correctly in IE < 10. If you are able to use a library for this task, MomentJS is a really amazing library; and it makes working with dates and times easy. Otherwise, I think you will have to write a basic function to give you the format that you are after.

function formatDate(date) {
    var year = date.getFullYear(),
        month = date.getMonth() + 1, // months are zero indexed
        day = date.getDate(),
        hour = date.getHours(),
        minute = date.getMinutes(),
        second = date.getSeconds(),
        hourFormatted = hour % 12 || 12, // hour returned in 24 hour format
        minuteFormatted = minute < 10 ? "0" + minute : minute,
        morning = hour < 12 ? "am" : "pm";

    return month + "/" + day + "/" + year + " " + hourFormatted + ":" +
            minuteFormatted + morning;
}

Actionbar notification count icon (badge) like Google has

I found better way to do it. if you want to use something like this

enter image description here

Use this dependency

   compile 'com.nex3z:notification-badge:0.1.0'

create one xml file in drawable and Save it as Badge.xml

<?xml version="1.0" encoding="utf-8"?>
  <layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item>
    <shape android:shape="oval">
        <solid android:color="#66000000"/>
        <size android:width="30dp" android:height="40dp"/>
    </shape>
</item>
<item android:bottom="1dp" android:right="0.6dp">
    <shape android:shape="oval">
        <solid android:color="@color/Error_color"/>
        <size android:width="20dp" android:height="20dp"/>
    </shape>
</item>
</layer-list>

Now wherever you want to use that badge use following code in xml. with the help of this you will be able to see that badge on top-right corner of your image or anything.

  <com.nex3z.notificationbadge.NotificationBadge
    android:id="@+id/badge"
    android:layout_toRightOf="@id/Your_ICON/IMAGE"
    android:layout_alignTop="@id/Your_ICON/IMAGE"
    android:layout_marginLeft="-16dp"
    android:layout_marginTop="-8dp"
    android:layout_width="28dp"
    android:layout_height="28dp"
    app:badgeBackground="@drawable/Badge"
    app:maxTextLength="2"
    ></com.nex3z.notificationbadge.NotificationBadge>

Now finally on yourFile.java use this 2 simple thing.. 1) Define

 NotificationBadge mBadge;

2) where your loop or anything which is counting this number use this:

 mBadge.setNumber(your_LoopCount);

here, mBadge.setNumber(0) will not show anything.

Hope this help.

Loop X number of times

Use:

1..10 | % { write "loop $_" }

Output:

PS D:\temp> 1..10 | % { write "loop $_" }
loop 1
loop 2
loop 3
loop 4
loop 5
loop 6
loop 7
loop 8
loop 9
loop 10

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

In addition to what TaskManager shows, if you use ProcessExplorer from Sysinternals, you can tell when you right-click on the process name and select Properties. In the Image tab, there is a field toward the bottom that says Image. It says 32-bit for a 32 bit application and 64 bit for the 64 bit application.

Microsoft.WebApplication.targets was not found, on the build server. What's your solution?

To answer the title of the question (but not the question about the output you're getting):

Copying the following folder from your dev machine to your build server fixes this if it's just web applications

C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\WebApplications

Remove x86 according to how your build breaks. If you have other project types you will probably need to copy the entire msbuild folder.

Remove a modified file from pull request

A pull request is just that: a request to merge one branch into another.

Your pull request doesn't "contain" anything, it's just a marker saying "please merge this branch into that one".

The set of changes the PR shows in the web UI is just the changes between the target branch and your feature branch. To modify your pull request, you must modify your feature branch, probably with a force push to the feature branch.

In your case, you'll probably want to amend your commit. Not sure about your exact situation, but some combination of interactive rebase and add -p should sort you out.

The openssl extension is required for SSL/TLS protection

I had the exact same problem and couldn't find a solution, so after thinking and looking for a while I figured that my PHP.INI apparently didn't look in the correct directory for my PHP Extensions, so I went under:

"Directory in which the loadable extensions (modules) reside." And found the following:

; http://php.net/extension-dir
; extension_dir = "./"
; On windows:
;extension_dir = "ext"

And simply removed the ; infront of "extension_dir = "ext", note this is only for Windows, remove the semicolon in front of the first extension_dir if you are running a different operating system.

I have no idea why mine wasn't already unmarked, but it's just something to look for if you are having problems.

How can I run PowerShell with the .NET 4 runtime?

Here is the contents of the configuration file I used to support both .NET 2.0 and .NET 4 assemblies:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <!-- http://msdn.microsoft.com/en-us/library/w4atty68.aspx -->
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" />
    <supportedRuntime version="v2.0.50727" />
  </startup>
</configuration>

Also, here’s a simplified version of the PowerShell 1.0 compatible code I used to execute our scripts from the passed in command line arguments:

class Program {
  static void Main( string[] args ) {
    Console.WriteLine( ".NET " + Environment.Version );

    string script = "& " + string.Join( " ", args );
    Console.WriteLine( script );
    Console.WriteLine( );

    // Simple host that sends output to System.Console
    PSHost host = new ConsoleHost( this );
    Runspace runspace = RunspaceFactory.CreateRunspace( host );

    Pipeline pipeline = runspace.CreatePipeline( );
    pipeline.Commands.AddScript( script );

    try {
      runspace.Open( );
      IEnumerable<PSObject> output = pipeline.Invoke( );
      runspace.Close( );

      // ...
    }
    catch( RuntimeException ex ) {
      string psLine = ex.ErrorRecord.InvocationInfo.PositionMessage;
      Console.WriteLine( "error : {0}: {1}{2}", ex.GetType( ), ex.Message, psLine );
      ExitCode = -1;
    }
  }
}

In addition to the basic error handling shown above, we also inject a trap statement into the script to display additional diagnostic information (similar to Jeffrey Snover's Resolve-Error function).

How to keep the local file or the remote file during merge using Git and the command line?

This approach seems more straightforward, avoiding the need to individually select each file:

# keep remote files
git merge --strategy-option theirs
# keep local files
git merge --strategy-option ours

or

# keep remote files
git pull -Xtheirs
# keep local files
git pull -Xours

Copied directly from: Resolve Git merge conflicts in favor of their changes during a pull

How to delete the first row of a dataframe in R?

You can use negative indexing to remove rows, e.g.:

dat <- dat[-1, ]

Here is an example:

> dat <- data.frame(A = 1:3, B = 1:3)
> dat[-1, ]
  A B
2 2 2
3 3 3
> dat2 <- dat[-1, ]
> dat2
  A B
2 2 2
3 3 3

That said, you may have more problems than just removing the labels that ended up on row 1. It is more then likely that R has interpreted the data as text and thence converted to factors. Check what str(foo), where foo is your data object, says about the data types.

It sounds like you just need header = TRUE in your call to read in the data (assuming you read it in via read.table() or one of it's wrappers.)

Virtual member call in a constructor

Reasons of the warning are already described, but how would you fix the warning? You have to seal either class or virtual member.

  class B
  {
    protected virtual void Foo() { }
  }

  class A : B
  {
    public A()
    {
      Foo(); // warning here
    }
  }

You can seal class A:

  sealed class A : B
  {
    public A()
    {
      Foo(); // no warning
    }
  }

Or you can seal method Foo:

  class A : B
  {
    public A()
    {
      Foo(); // no warning
    }

    protected sealed override void Foo()
    {
      base.Foo();
    }
  }

Styling of Select2 dropdown select boxes

This is how i changed placeholder arrow color, the 2 classes are for dropdown open and dropdown closed, you need to change the #fff to the color you want:

.select2-container--default.select2-container--open .select2-selection--single .select2-selection__arrow b {
    border-color: transparent transparent #fff transparent !important;
  }
  .select2-container--default .select2-selection--single .select2-selection__arrow b {
    border-color: #fff transparent transparent transparent !important;
  }

Take n rows from a spark dataframe and pass to toPandas()

You can use the limit(n) function:

l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.limit(2).withColumn('age2', df.age + 2).toPandas()

Or:

l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.withColumn('age2', df.age + 2).limit(2).toPandas()

pandas groupby sort within groups

What you want to do is actually again a groupby (on the result of the first groupby): sort and take the first three elements per group.

Starting from the result of the first groupby:

In [60]: df_agg = df.groupby(['job','source']).agg({'count':sum})

We group by the first level of the index:

In [63]: g = df_agg['count'].groupby('job', group_keys=False)

Then we want to sort ('order') each group and take the first three elements:

In [64]: res = g.apply(lambda x: x.sort_values(ascending=False).head(3))

However, for this, there is a shortcut function to do this, nlargest:

In [65]: g.nlargest(3)
Out[65]:
job     source
market  A         5
        D         4
        B         3
sales   E         7
        C         6
        B         4
dtype: int64

So in one go, this looks like:

df_agg['count'].groupby('job', group_keys=False).nlargest(3)

How to save a new sheet in an existing excel file, using Pandas?

I would strongly recommend you work directly with openpyxl since it now supports Pandas DataFrames.

This allows you to concentrate on the relevant Excel and Pandas code.

How do I refresh a DIV content?

Complete working code would look like this:

<script> 
$(document).ready(function(){
setInterval(function(){
      $("#here").load(window.location.href + " #here" );
}, 3000);
});
</script>

<div id="here">dynamic content ?</div>

self reloading div container refreshing every 3 sec.

Run Bash Command from PHP

Your shell_exec is executed by www-data user, from its directory. You can try

putenv("PATH=/home/user/bin/:" .$_ENV["PATH"]."");

Where your script is located in /home/user/bin Later on you can

$output = "<pre>".shell_exec("scriptname v1 v2")."</pre>";
echo $output;

To display the output of command. (Alternatively, without exporting path, try giving entire path of your script instead of just ./script.sh

How to obtain Signing certificate fingerprint (SHA1) for OAuth 2.0 on Android?

Step by step solution:

  1. Open your command prompt or Terminal for Mac
  2. Change directory to directory of the keytool file location. Change directory by using command cd <directory path>. (Note: if any directory name has space then add \ between the two words. Example cd /Applications/Android\ Studio.app//Contents/jre/jdk/Contents/Home/bin/)

    • To find the location of your keytool, you go to android studio..open your project. And go to

    • File>project Structure>SDK location..and find JDK location.

  3. Run the keytool by this command: keytool -list -v –keystore <your jks file path> (Note: if any directory name has space then add \ between the two words. example keytool -list -v -keystore /Users/username/Desktop/tasmiah\ mobile/v3/jordanos.jks)

  4. Command prompt you to key in the password.. so key in your password.. then you get the result

How to implement debounce in Vue2?

If you need a very minimalistic approach to this, I made one (originally forked from vuejs-tips to also support IE) which is available here: https://www.npmjs.com/package/v-debounce

Usage:

<input v-model.lazy="term" v-debounce="delay" placeholder="Search for something" />

Then in your component:

<script>
export default {
  name: 'example',
  data () {
    return {
      delay: 1000,
      term: '',
    }
  },
  watch: {
    term () {
      // Do something with search term after it debounced
      console.log(`Search term changed to ${this.term}`)
    }
  },
  directives: {
    debounce
  }
}
</script>

download a file from Spring boot rest service

If you need to download a huge file from the server's file system, then ByteArrayResource can take all Java heap space. In that case, you can use FileSystemResource

How to install python-dateutil on Windows?

Install from the "Unofficial Windows Binaries for Python Extension Packages"

http://www.lfd.uci.edu/~gohlke/pythonlibs/#python-dateutil

Pretty much has every package you would need.

Nested Recycler view height doesn't wrap its content

Update

Many issues relating to this feature in version 23.2.0 have been fixed in 23.2.1, update to that instead.

With the release of Support Library version 23.2, RecyclerView now supports that!

Update build.gradle to:

compile 'com.android.support:recyclerview-v7:23.2.1'

or any version beyond that.

This release brings an exciting new feature to the LayoutManager API: auto-measurement! This allows a RecyclerView to size itself based on the size of its contents. This means that previously unavailable scenarios, such as using WRAP_CONTENT for a dimension of the RecyclerView, are now possible. You’ll find all built in LayoutManagers now support auto-measurement.

This can be disabled via setAutoMeasurementEnabled() if need be. Check in detail here.

How can I send emails through SSL SMTP with the .NET Framework?

It works with System.Web.Mail (which is marked as obsolete):

private const string SMTP_SERVER        = "http://schemas.microsoft.com/cdo/configuration/smtpserver";
private const string SMTP_SERVER_PORT   = "http://schemas.microsoft.com/cdo/configuration/smtpserverport";
private const string SEND_USING         = "http://schemas.microsoft.com/cdo/configuration/sendusing";
private const string SMTP_USE_SSL       = "http://schemas.microsoft.com/cdo/configuration/smtpusessl";
private const string SMTP_AUTHENTICATE  = "http://schemas.microsoft.com/cdo/configuration/smtpauthenticate";
private const string SEND_USERNAME      = "http://schemas.microsoft.com/cdo/configuration/sendusername";
private const string SEND_PASSWORD      = "http://schemas.microsoft.com/cdo/configuration/sendpassword";

System.Web.Mail.MailMessage mail = new System.Web.Mail.MailMessage();

mail.Fields[SMTP_SERVER] = "tempurl.org";
mail.Fields[SMTP_SERVER_PORT] = 465;
mail.Fields[SEND_USING] = 2;
mail.Fields[SMTP_USE_SSL] = true;
mail.Fields[SMTP_AUTHENTICATE] = 1;
mail.Fields[SEND_USERNAME] = "username";
mail.Fields[SEND_PASSWORD] = "password";

System.Web.Mail.SmtpMail.Send(mail);

What is your point of view regarding obsolete namespace usage?

Move SQL Server 2008 database files to a new folder location

To add the privileges needed to the files add and grant right to the following local user: SQLServerMSSQLUser$COMPUTERNAME$INSTANCENAME, where COMPUTERNAME and INSTANCENAME has to be replaced with name of computer and MSSQL instance respectively.

Where is virtualenvwrapper.sh after pip install?

Although this is an OS X question, here's what worked for me on Linux (Red Hat).

My virtualwrapper.sh was in

~/.local/bin/virtualenvwrapper.sh

This is probably because I installed virtualenvwrapper locally, using the --user flag...

pip install --user virtualenvwrapper

...as an alternative to the risky practice of using sudo pip.

How can I check if a command exists in a shell script?

which <cmd>

also see options which supports for aliases if applicable to your case.

Example

$ which foobar
which: no foobar in (/usr/local/bin:/usr/bin:/cygdrive/c/Program Files (x86)/PC Connectivity Solution:/cygdrive/c/Windows/system32/System32/WindowsPowerShell/v1.0:/cygdrive/d/Program Files (x86)/Graphviz 2.28/bin:/cygdrive/d/Program Files (x86)/GNU/GnuPG
$ if [ $? -eq 0 ]; then echo "foobar is found in PATH"; else echo "foobar is NOT found in PATH, of course it does not mean it is not installed."; fi
foobar is NOT found in PATH, of course it does not mean it is not installed.
$

PS: Note that not everything that's installed may be in PATH. Usually to check whether something is "installed" or not one would use installation related commands relevant to the OS. E.g. rpm -qa | grep -i "foobar" for RHEL.

Copy multiple files with Ansible

You can loop through variable with list of directories:

- name: Copy files from several directories
  copy:
    src: "{{ item }}"
    dest: "/etc/fooapp/"
    owner: root
    mode: "0600"
  loop: "{{ files }}"
  vars:
    files:
      - "dir1/"
      - "dir2/"

How to convert a string to a date in sybase

Use the convert function, for example:

select * from data 
where dateVal < convert(datetime, '01/01/2008', 103)

Where the convert style (103) determines the date format to use.

Counting duplicates in Excel

Step 1: Select top cell of the data

Step 2 : Select Data > Sort.

Step 3 : Select Data >Subtotal

Step 4 : Change use function to "count" and click OK.

Step 5 : Collapse to 2

How can I deploy an iPhone application from Xcode to a real iPhone device?

Solution posted by Cawas works perfectly with XCode4, too. However, there are some changes to IDE's UI, so you need to make some research to find Run Script :)

In the Project Navigator view click the root item of the project, then in the middle window select Target, then click Build Phases tab and at the bottom you'll see Add Build Phase button, click and select Add Run Script, then paste "codesign" script posted by Cawas.

Catching nullpointerexception in Java

You should be catching NullPointerException with the code above, but that doesn't change the fact that your Check_Circular is wrong. If you fix Check_Circular, your code won't throw NullPointerException in the first place, and work as intended.

Try:

public static boolean Check_Circular(LinkedListNode head)
{
    LinkedListNode curNode = head;
    do
    {
        curNode = curNode.next;
        if(curNode == head)
            return true;
    }
    while(curNode != null);

    return false;
}

Python: create dictionary using dict() with integer keys?

a = dict(one=1, two=2, three=3)

Providing keyword arguments as in this example only works for keys that are valid Python identifiers. Otherwise, any valid keys can be used.

PowerShell: Store Entire Text File Contents in Variable

Powershell 2.0:

(see detailed explanation here)

$text = Get-Content $filePath | Out-String

The IO.File.ReadAllText didn't work for me with a relative path, it looks for the file in %USERPROFILE%\$filePath instead of the current directory (when running from Powershell ISE at least):

$text = [IO.File]::ReadAllText($filePath)

Powershell 3+:

$text = Get-Content $filePath -Raw

npm install hangs

I am behind a corporate proxy, so I usually use an intermediate proxy to enable NTLM authentication.

I had hangs problem with npm install when using CNTLM proxy. With NTLM-APS (a similar proxy) the hangs were gone.

How to run a .jar in mac?

Make Executable your jar and after that double click on it on Mac OS then it works successfully.

sudo chmod +x filename.jar

Try this, I hope this works.

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

I spent half a day searching for answers to an identical "Illegal mix of collations" error with conflicts between utf8_unicode_ci and utf8_general_ci.

I found that some columns in my database were not specifically collated utf8_unicode_ci. It seems mysql implicitly collated these columns utf8_general_ci.

Specifically, running a 'SHOW CREATE TABLE table1' query outputted something like the following:

| table1 | CREATE TABLE `table1` (
`id` int(11) NOT NULL,
`col1` varchar(4) CHARACTER SET utf8 NOT NULL,
`col2` int(11) NOT NULL,
PRIMARY KEY (`col1`,`col2`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci |

Note the line 'col1' varchar(4) CHARACTER SET utf8 NOT NULL does not have a collation specified. I then ran the following query:

ALTER TABLE table1 CHANGE col1 col1 VARCHAR(4) CHARACTER SET utf8 COLLATE utf8_unicode_ci NOT NULL;

This solved my "Illegal mix of collations" error. Hope this might help someone else out there.

curl posting with header application/x-www-form-urlencoded

<?php
//
// A very simple PHP example that sends a HTTP POST to a remote site
//

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL,"http://xxxxxxxx.xxx/xx/xx");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,
            "dispnumber=567567567&extension=6");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));


// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

$server_output = curl_exec ($ch);

curl_close ($ch);

// further processing ....
if ($server_output == "OK") { ... } else { ... }

?>

How to Convert a Text File into a List in Python

Going with what you've started:

row = [[]] 
crimefile = open(fileName, 'r') 
for line in crimefile.readlines(): 
    tmp = []
    for element in line[0:-1].split(','):
        tmp.append(element)
row.append(tmp)

How do I iterate through the files in a directory in Java?

For Java 7+, there is also https://docs.oracle.com/javase/7/docs/api/java/nio/file/DirectoryStream.html

Example taken from the Javadoc:

List<Path> listSourceFiles(Path dir) throws IOException {
   List<Path> result = new ArrayList<>();
   try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "*.{c,h,cpp,hpp,java}")) {
       for (Path entry: stream) {
           result.add(entry);
       }
   } catch (DirectoryIteratorException ex) {
       // I/O error encounted during the iteration, the cause is an IOException
       throw ex.getCause();
   }
   return result;
}

Passing variables to the next middleware using next() in Express.js

The trick is pretty simple... The request cycle is still pretty much alive. You can just add a new variable that will create a temporary, calling

app.get('some/url/endpoint', middleware1, middleware2);

Since you can handle your request in the first middleware

(req, res, next) => {
    var yourvalue = anyvalue
}

In middleware 1 you handle your logic and store your value like below:

req.anyvariable = yourvalue

In middleware 2 you can catch this value from middleware 1 doing the following:

(req, res, next) => {
    var storedvalue = req.yourvalue
}

Is a slash ("/") equivalent to an encoded slash ("%2F") in the path portion of an HTTP URL

The story of %2F vs / was that, according to the initial W3C recommendations, slashes «must imply a hierarchical structure»:

The slash ("/", ASCII 2F hex) character is reserved for the delimiting of substrings whose relationship is hierarchical. This enables partial forms of the URI.

Example 2

The URIs

http://www.w3.org/albert/bertram/marie-claude

and

http://www.w3.org/albert/bertram%2Fmarie-claude

are NOT identical, as in the second case the encoded slash does not have hierarchical significance.

What does .shape[] do in "for i in range(Y.shape[0])"?

shape is a tuple that gives dimensions of the array..

>>> c = arange(20).reshape(5,4)
>>> c
array([[ 0,  1,  2,  3],
       [ 4,  5,  6,  7],
       [ 8,  9, 10, 11],
       [12, 13, 14, 15],
       [16, 17, 18, 19]])

c.shape[0] 
5

Gives the number of rows

c.shape[1] 
4

Gives number of columns

C# Error: Parent does not contain a constructor that takes 0 arguments

Since you don't explicitly invoke a parent constructor as part of your child class constructor, there is an implicit call to a parameterless parent constructor inserted. That constructor does not exist, and so you get that error.

To correct the situation, you need to add an explicit call:

public Child(int i) : base(i)
{
    Console.WriteLine("child");
}

Or, you can just add a parameterless parent constructor:

protected Parent() { } 

Command-line tool for finding out who is locking a file

I have used Unlocker for years and really like it. It not only will identify programs and offer to unlock the folder\file, it will allow you to kill the processing that has the lock as well.

Additionally, it offers actions to do to the locked file in question such as deleting it.

Unlocker helps delete locked files with error messages including "cannot delete file," and "access is denied." Video tutorial available.

Some errors you might get that Unlocker can help with include:

  • Cannot delete file: Access is denied.
  • There has been a sharing violation.
  • The source or destination file may be in use.
  • The file is in use by another program or user.
  • Make sure the disk is not full or write-protected and that the file is not currently in use.

Iterating over dictionaries using 'for' loops

key is just a variable name.

for key in d:

will simply loop over the keys in the dictionary, rather than the keys and values. To loop over both key and value you can use the following:

For Python 3.x:

for key, value in d.items():

For Python 2.x:

for key, value in d.iteritems():

To test for yourself, change the word key to poop.

In Python 3.x, iteritems() was replaced with simply items(), which returns a set-like view backed by the dict, like iteritems() but even better. This is also available in 2.7 as viewitems().

The operation items() will work for both 2 and 3, but in 2 it will return a list of the dictionary's (key, value) pairs, which will not reflect changes to the dict that happen after the items() call. If you want the 2.x behavior in 3.x, you can call list(d.items()).

How to compare two dates in php

Try this

$data1 = strtotime(\date("d/m/Y"));
$data1 = date_create($data1);
$data2 = date_create("21/06/2017");

if($data1 < $data2){
    return "The most current date is date1";
}

return "The most current date is date2";

Remove non-ASCII characters from CSV

awk '{ sub("[^a-zA-Z0-9\"!@#$%^&*|_\[](){}", ""); print }' MYinputfile.txt > pipe_out_to_CONVERTED_FILE.txt

Decoding UTF-8 strings in Python

It's an encoding error - so if it's a unicode string, this ought to fix it:

text.encode("windows-1252").decode("utf-8")

If it's a plain string, you'll need an extra step:

text.decode("utf-8").encode("windows-1252").decode("utf-8")

Both of these will give you a unicode string.

By the way - to discover how a piece of text like this has been mangled due to encoding issues, you can use chardet:

>>> import chardet
>>> chardet.detect(u"And the Hip’s coming, too")
{'confidence': 0.5, 'encoding': 'windows-1252'}

Interface vs Abstract Class (general OO)

How about an analogy: when I was in the Air Force, I went to pilot training and became a USAF (US Air Force) pilot. At that point I wasn't qualified to fly anything, and had to attend aircraft type training. Once I qualified, I was a pilot (Abstract class) and a C-141 pilot (concrete class). At one of my assignments, I was given an additional duty: Safety Officer. Now I was still a pilot and a C-141 pilot, but I also performed Safety Officer duties (I implemented ISafetyOfficer, so to speak). A pilot wasn't required to be a safety officer, other people could have done it as well.

All USAF pilots have to follow certain Air Force-wide regulations, and all C-141 (or F-16, or T-38) pilots 'are' USAF pilots. Anyone can be a safety officer. So, to summarize:

  • Pilot: abstract class
  • C-141 Pilot: concrete class
  • ISafety Officer: interface

added note: this was meant to be an analogy to help explain the concept, not a coding recommendation. See the various comments below, the discussion is interesting.

Animate a custom Dialog

I meet the same problem,but ,at last I solve the problem by followed way

((ViewGroup)dialog.getWindow().getDecorView())
.getChildAt(0).startAnimation(AnimationUtils.loadAnimation(
context,android.R.anim.slide_in_left));

jQuery change method on input type="file"

is the ajax uploader refreshing your input element? if so you should consider using .live() method.

 $('#imageFile').live('change', function(){ uploadFile(); });

update:

from jQuery 1.7+ you should use now .on()

 $(parent_element_selector_here or document ).on('change','#imageFile' , function(){ uploadFile(); });