Programs & Examples On #Aggregation

Aggregation is a relationship between two classes that is best described as a "has-a" and "whole/part" relationship.

Implementation difference between Aggregation and Composition in Java

Aggregation vs Composition

Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist.

whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart don’t exist separate to a Human.

Aggregation relation is “has-a” and composition is “part-of” relation.

Composition is a strong Association whereas Aggregation is a weak Association.

MySQL - Using COUNT(*) in the WHERE clause

try this;

select gid
from `gd`
group by gid 
having count(*) > 10
order by lastupdated desc

Prefer composition over inheritance?

When you want to "copy"/Expose the base class' API, you use inheritance. When you only want to "copy" functionality, use delegation.

One example of this: You want to create a Stack out of a List. Stack only has pop, push and peek. You shouldn't use inheritance given that you don't want push_back, push_front, removeAt, et al.-kind of functionality in a Stack.

What is the difference between association, aggregation and composition?

In a very simple sentence:
Aggregation and Composition are subsets of association.

  • A uses B -> this is an aggregation

  • A needs B -> is composition.

Read more here.

Disable clipboard prompt in Excel VBA on workbook close

I can offer two options

  1. Direct copy

Based on your description I'm guessing you are doing something like

Set wb2 = Application.Workbooks.Open("YourFile.xls")
wb2.Sheets("YourSheet").[<YourRange>].Copy
ThisWorkbook.Sheets("SomeSheet").Paste
wb2.close

If this is the case, you don't need to copy via the clipboard. This method copies from source to destination directly. No data in clipboard = no prompt

Set wb2 = Application.Workbooks.Open("YourFile.xls")
wb2.Sheets("YourSheet").[<YourRange>].Copy ThisWorkbook.Sheets("SomeSheet").Cells(<YourCell")
wb2.close
  1. Suppress prompt

You can prevent all alert pop-ups by setting

Application.DisplayAlerts = False

[Edit]

  1. To copy values only: don't use copy/paste at all

Dim rSrc As Range
Dim rDst As Range
Set rSrc = wb2.Sheets("YourSheet").Range("YourRange")
Set rDst = ThisWorkbook.Sheets("SomeSheet").Cells("YourCell").Resize(rSrc.Rows.Count, rSrc.Columns.Count)
rDst = rSrc.Value

Including a css file in a blade template?

@include directive allows you to include a Blade view from within another view, like this :

@include('another.view')

Include CSS or JS from master layout

asset()

The asset function generates a URL for an asset using the current scheme of the request (HTTP or HTTPS):

<link href="{{ asset('css/styles.css') }}" rel="stylesheet">
<script type="text/javascript" src="{{ asset('js/scripts.js') }}"></script>

mix()

If you are using versioned Mix file, you can also use mix() function. It will returns the path to a versioned Mix file:

<link href="{{ mix('css/styles.css') }}" rel="stylesheet">
<script type="text/javascript" src="{{ mix('js/scripts.js') }}"></script>

Incude CSS or JS from sub-view, use @push().

layout.blade.php

<html>
    <head>
        <!-- push target to head -->
        @stack('styles')
        @stack('scripts')
    </head>
    <body>

        <!-- or push target to footer -->
        @stack('scripts')
    </body>
</html

view.blade.php

@push('styles')
    <link href="{{ asset('css/styles.css') }}" rel="stylesheet">
@endpush

@push('scripts')
    <script type="text/javascript" src="{{ asset('js/scripts.js') }}"></script>
@endpush

Recording video feed from an IP camera over a network

about 3 years ago i needed cctv. I found zoneminder, tried to edit it to my liking, but found i was fixing it more than editing it.

Not to mention mp4 recording feature isn't actually part of the master branch (which is kind of lol, since its a cctv program and its already been about 3 years or more since it was suggested). Its literally just adapting the ffmpeg command lol.

So i found the solution!

If you want something done right, do it yourself.

I present to you Shinobi! Shinobi : The Open Source CCTV Platform

enter image description here

How to get an input text value in JavaScript

How to get an input text value in JavaScript

_x000D_
_x000D_
    var textbox;_x000D_
    function onload() { _x000D_
        //Get value._x000D_
        textbox = document.getElementById('textbox');_x000D_
    }_x000D_
_x000D_
    function showMessage() { _x000D_
        //Show message in alert()_x000D_
        alert("The message is: " + textbox.value);_x000D_
    }
_x000D_
<body onload="onload();">_x000D_
<div>_x000D_
<input type="text" name="enter" class="enter" placeholder="Write something here!" value="It´s a wonderful day!" id="textbox"/>_x000D_
<input type="button" value="Show this message!" onClick="showMessage()" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check if MySQL returns null/empty?

if ( (strlen($ownerID) == 0) || ($ownerID == '0') || (empty($ownerID )) )

if $ownerID is NULL it will be triggered by the empty() test

https://www.php.net/empty

Eclipse change project files location

This link shows how to edit the eclipse workspace metadata to update the project's location manually, useful if the location has already changed or you have a lot of projects to move and don't want to do several clicks and waits for each one: https://web.archive.org/web/20160421171614/http://www.joeflash.ca/blog/2008/11/moving-a-fb-workspace-update.html

LINQ select in C# dictionary

var res = exitDictionary
            .Select(p => p.Value).Cast<Dictionary<string, object>>()
            .SelectMany(d => d)
            .Where(p => p.Key == "fieldname1")
            .Select(p => p.Value).Cast<List<Dictionary<string,string>>>()
            .SelectMany(l => l)
            .SelectMany(d=> d)
            .Where(p => p.Key == "valueTitle")
            .Select(p => p.Value)
            .ToList();

This also works, and easy to understand.

How to load/edit/run/save text files (.py) into an IPython notebook cell?

I have found it satisfactory to use ls and cd within ipython notebook to find the file. Then type cat your_file_name into the cell, and you'll get back the contents of the file, which you can then paste into the cell as code.

how to reset <input type = "file">

Works for dynamic controls too.

Javascript

<input type="file" onchange="FileValidate(this)" />

function FileValidate(object) {
    if ((object.files[0].size / 1024 / 1024) > 1) {   //greater than 1 MB         
        $(object).val('');
    }     
}

JQuery

<input type="file" class="UpoloadFileSize">

$(document).ready(function () {

    $('.UpoloadFileSize').bind('change', function () {                
        if ((this.files[0].size / 1024000) > 1.5) { //greater than 1.5 MB
            $(this).val('');
            alert('Size exceeded !!');
        }
    });

});

How to copy static files to build directory with Webpack?

You can write bash in your package.json:

# package.json
{
  "name": ...,
  "version": ...,
  "scripts": {
    "build": "NODE_ENV=production npm run webpack && cp -v <this> <that> && echo ok",
    ...
  }
}

Reloading the page gives wrong GET request with AngularJS HTML5 mode

Finally I got a way to to solve this issue by server side as it's more like an issue with AngularJs itself I am using 1.5 Angularjs and I got same issue on reload the page. But after adding below code in my server.js file it is save my day but it's not a proper solution or not a good way .

app.use(function(req, res, next){
  var d = res.status(404);
     if(d){
        res.sendfile('index.html');
     }
});

SASS and @font-face

In case anyone was wondering - it was probably my css...

@font-face
  font-family: "bingo"
  src: url('bingo.eot')
  src: local('bingo')
  src: url('bingo.svg#bingo') format('svg')
  src: url('bingo.otf') format('opentype')

will render as

@font-face {
  font-family: "bingo";
  src: url('bingo.eot');
  src: local('bingo');
  src: url('bingo.svg#bingo') format('svg');
  src: url('bingo.otf') format('opentype'); }

which seems to be close enough... just need to check the SVG rendering

C: socket connection timeout

This article might help:

Connect with timeout (or another use for select() )

Looks like you put the socket into non-blocking mode until you've connected, and then put it back into blocking mode once the connection's established.

void connect_w_to(void) { 
  int res; 
  struct sockaddr_in addr; 
  long arg; 
  fd_set myset; 
  struct timeval tv; 
  int valopt; 
  socklen_t lon; 

  // Create socket 
  soc = socket(AF_INET, SOCK_STREAM, 0); 
  if (soc < 0) { 
     fprintf(stderr, "Error creating socket (%d %s)\n", errno, strerror(errno)); 
     exit(0); 
  } 

  addr.sin_family = AF_INET; 
  addr.sin_port = htons(2000); 
  addr.sin_addr.s_addr = inet_addr("192.168.0.1"); 

  // Set non-blocking 
  if( (arg = fcntl(soc, F_GETFL, NULL)) < 0) { 
     fprintf(stderr, "Error fcntl(..., F_GETFL) (%s)\n", strerror(errno)); 
     exit(0); 
  } 
  arg |= O_NONBLOCK; 
  if( fcntl(soc, F_SETFL, arg) < 0) { 
     fprintf(stderr, "Error fcntl(..., F_SETFL) (%s)\n", strerror(errno)); 
     exit(0); 
  } 
  // Trying to connect with timeout 
  res = connect(soc, (struct sockaddr *)&addr, sizeof(addr)); 
  if (res < 0) { 
     if (errno == EINPROGRESS) { 
        fprintf(stderr, "EINPROGRESS in connect() - selecting\n"); 
        do { 
           tv.tv_sec = 15; 
           tv.tv_usec = 0; 
           FD_ZERO(&myset); 
           FD_SET(soc, &myset); 
           res = select(soc+1, NULL, &myset, NULL, &tv); 
           if (res < 0 && errno != EINTR) { 
              fprintf(stderr, "Error connecting %d - %s\n", errno, strerror(errno)); 
              exit(0); 
           } 
           else if (res > 0) { 
              // Socket selected for write 
              lon = sizeof(int); 
              if (getsockopt(soc, SOL_SOCKET, SO_ERROR, (void*)(&valopt), &lon) < 0) { 
                 fprintf(stderr, "Error in getsockopt() %d - %s\n", errno, strerror(errno)); 
                 exit(0); 
              } 
              // Check the value returned... 
              if (valopt) { 
                 fprintf(stderr, "Error in delayed connection() %d - %s\n", valopt, strerror(valopt) 
); 
                 exit(0); 
              } 
              break; 
           } 
           else { 
              fprintf(stderr, "Timeout in select() - Cancelling!\n"); 
              exit(0); 
           } 
        } while (1); 
     } 
     else { 
        fprintf(stderr, "Error connecting %d - %s\n", errno, strerror(errno)); 
        exit(0); 
     } 
  } 
  // Set to blocking mode again... 
  if( (arg = fcntl(soc, F_GETFL, NULL)) < 0) { 
     fprintf(stderr, "Error fcntl(..., F_GETFL) (%s)\n", strerror(errno)); 
     exit(0); 
  } 
  arg &= (~O_NONBLOCK); 
  if( fcntl(soc, F_SETFL, arg) < 0) { 
     fprintf(stderr, "Error fcntl(..., F_SETFL) (%s)\n", strerror(errno)); 
     exit(0); 
  } 
  // I hope that is all 
}

Java ByteBuffer to String

private String convertFrom(String lines, String from, String to) {
    ByteBuffer bb = ByteBuffer.wrap(lines.getBytes());
    CharBuffer cb = Charset.forName(to).decode(bb);
    return new String(Charset.forName(from).encode(cb).array());
};
public Doit(){
    String concatenatedLines = convertFrom(concatenatedLines, "CP1252", "UTF-8");
};

How to free memory from char array in C

Local variables are automatically freed when the function ends, you don't need to free them by yourself. You only free dynamically allocated memory (e.g using malloc) as it's allocated on the heap:

char *arr = malloc(3 * sizeof(char));
strcpy(arr, "bo");
// ...
free(arr);

More about dynamic memory allocation: http://en.wikipedia.org/wiki/C_dynamic_memory_allocation

Local Storage vs Cookies

Cookies and local storage serve different purposes. Cookies are primarily for reading server-side, local storage can only be read by the client-side. So the question is, in your app, who needs this data — the client or the server?

If it's your client (your JavaScript), then by all means switch. You're wasting bandwidth by sending all the data in each HTTP header.

If it's your server, local storage isn't so useful because you'd have to forward the data along somehow (with Ajax or hidden form fields or something). This might be okay if the server only needs a small subset of the total data for each request.

You'll want to leave your session cookie as a cookie either way though.

As per the technical difference, and also my understanding:

  1. Apart from being an old way of saving data, Cookies give you a limit of 4096 bytes (4095, actually) — it's per cookie. Local Storage is as big as 5MB per domainSO Question also mentions it.

  2. localStorage is an implementation of the Storage Interface. It stores data with no expiration date, and gets cleared only through JavaScript, or clearing the Browser Cache / Locally Stored Data — unlike cookie expiry.

concatenate char array in C

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

char *name = "hello";

int main(void) {
  char *ext = ".txt";
  int len   = strlen(name) + strlen(ext) + 1;
  char *n2  = malloc(len);
  char *n2a = malloc(len);

  if (n2 == NULL || n2a == NULL)
    abort();

  strlcpy(n2, name, len);
  strlcat(n2, ext, len);
  printf("%s\n", n2);

  /* or for conforming C99 ...  */
  strncpy(n2a, name, len);
  strncat(n2a, ext, len - strlen(n2a));
  printf("%s\n", n2a);

  return 0; // this exits, otherwise free n2 && n2a
}

Can Windows' built-in ZIP compression be scripted?

There are VBA methods to zip and unzip using the windows built in compression as well, which should give some insight as to how the system operates. You may be able to build these methods into a scripting language of your choice.

The basic principle is that within windows you can treat a zip file as a directory, and copy into and out of it. So to create a new zip file, you simply make a file with the extension .zip that has the right header for an empty zip file. Then you close it, and tell windows you want to copy files into it as though it were another directory.

Unzipping is easier - just treat it as a directory.

In case the web pages are lost again, here are a few of the relevant code snippets:

ZIP

Sub NewZip(sPath)
'Create empty Zip File
'Changed by keepITcool Dec-12-2005
    If Len(Dir(sPath)) > 0 Then Kill sPath
    Open sPath For Output As #1
    Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
    Close #1
End Sub


Function bIsBookOpen(ByRef szBookName As String) As Boolean
' Rob Bovey
    On Error Resume Next
    bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
End Function


Function Split97(sStr As Variant, sdelim As String) As Variant
'Tom Ogilvy
    Split97 = Evaluate("{""" & _
                       Application.Substitute(sStr, sdelim, """,""") & """}")
End Function

Sub Zip_File_Or_Files()
    Dim strDate As String, DefPath As String, sFName As String
    Dim oApp As Object, iCtr As Long, I As Integer
    Dim FName, vArr, FileNameZip

    DefPath = Application.DefaultFilePath
    If Right(DefPath, 1) <> "\" Then
        DefPath = DefPath & "\"
    End If

    strDate = Format(Now, " dd-mmm-yy h-mm-ss")
    FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip"

    'Browse to the file(s), use the Ctrl key to select more files
    FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
                    MultiSelect:=True, Title:="Select the files you want to zip")
    If IsArray(FName) = False Then
        'do nothing
    Else
        'Create empty Zip File
        NewZip (FileNameZip)
        Set oApp = CreateObject("Shell.Application")
        I = 0
        For iCtr = LBound(FName) To UBound(FName)
            vArr = Split97(FName(iCtr), "\")
            sFName = vArr(UBound(vArr))
            If bIsBookOpen(sFName) Then
                MsgBox "You can't zip a file that is open!" & vbLf & _
                       "Please close it and try again: " & FName(iCtr)
            Else
                'Copy the file to the compressed folder
                I = I + 1
                oApp.Namespace(FileNameZip).CopyHere FName(iCtr)

                'Keep script waiting until Compressing is done
                On Error Resume Next
                Do Until oApp.Namespace(FileNameZip).items.Count = I
                    Application.Wait (Now + TimeValue("0:00:01"))
                Loop
                On Error GoTo 0
            End If
        Next iCtr

        MsgBox "You find the zipfile here: " & FileNameZip
    End If
End Sub

UNZIP

Sub Unzip1()
    Dim FSO As Object
    Dim oApp As Object
    Dim Fname As Variant
    Dim FileNameFolder As Variant
    Dim DefPath As String
    Dim strDate As String

    Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _
                                        MultiSelect:=False)
    If Fname = False Then
        'Do nothing
    Else
        'Root folder for the new folder.
        'You can also use DefPath = "C:\Users\Ron\test\"
        DefPath = Application.DefaultFilePath
        If Right(DefPath, 1) <> "\" Then
            DefPath = DefPath & "\"
        End If

        'Create the folder name
        strDate = Format(Now, " dd-mm-yy h-mm-ss")
        FileNameFolder = DefPath & "MyUnzipFolder " & strDate & "\"

        'Make the normal folder in DefPath
        MkDir FileNameFolder

        'Extract the files into the newly created folder
        Set oApp = CreateObject("Shell.Application")

        oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items

        'If you want to extract only one file you can use this:
        'oApp.Namespace(FileNameFolder).CopyHere _
         'oApp.Namespace(Fname).items.Item("test.txt")

        MsgBox "You find the files here: " & FileNameFolder

        On Error Resume Next
        Set FSO = CreateObject("scripting.filesystemobject")
        FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
    End If
End Sub

How to implement a property in an interface

The simple example of using a property in an interface:

using System;
interface IName
{
    string Name { get; set; }
}

class Employee : IName
{
    public string Name { get; set; }
}

class Company : IName
{
    private string _company { get; set; }
    public string Name
    {
        get
        {
            return _company;
        }
        set
        {
            _company = value;
        }   
    }
}

class Client
{
    static void Main(string[] args)
    {
        IName e = new Employee();
        e.Name = "Tim Bridges";

        IName c = new Company();
        c.Name = "Inforsoft";

        Console.WriteLine("{0} from {1}.", e.Name, c.Name);
        Console.ReadKey();
    }
}
/*output:
 Tim Bridges from Inforsoft.
 */

jquery, selector for class within id

You can use find() :

$('#my_id').find('my_class');

Or maybe:

$('#my_id').find('span');

Both methods will word for what you want

How to put more than 1000 values into an Oracle IN clause

Where do you get the list of ids from in the first place? Since they are IDs in your database, did they come from some previous query?

When I have seen this in the past it has been because:-

  1. a reference table is missing and the correct way would be to add the new table, put an attribute on that table and join to it
  2. a list of ids is extracted from the database, and then used in a subsequent SQL statement (perhaps later or on another server or whatever). In this case, the answer is to never extract it from the database. Either store in a temporary table or just write one query.

I think there may be better ways to rework this code that just getting this SQL statement to work. If you provide more details you might get some ideas.

How prevent CPU usage 100% because of worker process in iis

I was facing the same issues recently and found a solution which worked for me and reduced the memory consumption level upto a great extent.

Solution:

First of all find the application which is causing heavy memory usage.

You can find this in the Details section of the Task Manager.

Next.

  1. Open the IIS manager.
  2. Click on Application Pools. You'll find many application pools which your system is using.
  3. Now from the task manager you've found which application is causing the heavy memory consumption. There would be multiple options for that and you need to select the one which is having '1' in it's Application column of your web application.
  4. When you click on the application pool on the right hand side you'll see an option Advance settings under Edit Application pools. Go to Advanced Settings. 5.Now under General category set the Enable 32-bit Applications to True
  5. Restart the IIS server or you can see the consumption goes down in performance section of your Task Manager.

If this solution works for you please add a comment so that I can know.

MySql with JAVA error. The last packet sent successfully to the server was 0 milliseconds ago

The problem is mostly due to a MySQL service that is not running, so make sure it is. If it isn't, run this CMD with administrator privilege in order to start it:

sc start [Your MySQL Service name]

Strip double quotes from a string in .NET

s = s.Replace("\"", "");

You need to use the \ to escape the double quote character in a string.

how to get the one entry from hashmap without iterating

What do you mean with "without iterating"?

You can use map.entrySet().iterator().next() and you wouldn't iterate through map (in the meaning of "touching each object"). You can't get hold of an Entry<K, V> without using an iterator though. The Javadoc of Map.Entry says:

The Map.entrySet method returns a collection-view of the map, whose elements are of this class. The only way to obtain a reference to a map entry is from the iterator of this collection-view. These Map.Entry objects are valid only for the duration of the iteration.

Can you explain in more detail, what you are trying to accomplish? If you want to handle objects first, that match a specific criterion (like "have a particular key") and fall back to the remaining objects otherwise, then look at a PriorityQueue. It will order your objects based on natural order or a custom-defined Comparator that you provide.

Regular expression for matching latitude/longitude coordinates?

Try this:

(?<!\d)([-+]?(?:[1-8]?\d(?:\.\d+)?|90(?:\.0+)?)),\s*([-+]?(?:180(?:\.0+)?|(?:(?:1[0-7]\d)|(?:[1-9]?\d))(?:\.\d+)?))(?!\d)`

JSON Parse File Path

My case of working code is:

var request = new XMLHttpRequest();
request.open("GET", "<path_to_file>", false);
request.overrideMimeType("application/json");
request.send(null);
var jsonData = JSON.parse(request.responseText);
console.log(jsonData);

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

Try to add

GRANT USAGE ON SCHEMA public to readonly;

You probably were not aware that one needs to have the requisite permissions to a schema, in order to use objects in the schema.

Send POST data using XMLHttpRequest

Minimal use of FormData to submit an AJAX request

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=Edge, chrome=1"/>
<script>
"use strict";
function submitForm(oFormElement)
{
  var xhr = new XMLHttpRequest();
  xhr.onload = function(){ alert (xhr.responseText); } // success case
  xhr.onerror = function(){ alert (xhr.responseText); } // failure case
  xhr.open (oFormElement.method, oFormElement.action, true);
  xhr.send (new FormData (oFormElement));
  return false;
}
</script>
</head>

<body>
<form method="post" action="somewhere" onsubmit="return submitForm(this);">
  <input type="hidden" value="person"   name="user" />
  <input type="hidden" value="password" name="pwd" />
  <input type="hidden" value="place"    name="organization" />
  <input type="hidden" value="key"      name="requiredkey" />
  <input type="submit" value="post request"/>
</form>
</body>
</html>

Remarks

  1. This does not fully answer the OP question because it requires the user to click in order to submit the request. But this may be useful to people searching for this kind of simple solution.

  2. This example is very simple and does not support the GET method. If you are interesting by more sophisticated examples, please have a look at the excellent MDN documentation. See also similar answer about XMLHttpRequest to Post HTML Form.

  3. Limitation of this solution: As pointed out by Justin Blank and Thomas Munk (see their comments), FormData is not supported by IE9 and lower, and default browser on Android 2.3.

How do you extract IP addresses from files using a regex in a linux shell?

If you are not given a specific file and you need to extract IP address then we need to do it recursively. grep command -> Searches a text or file for matching a given string and displays the matched string .

grep -roE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | grep -oE '[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'

-r We can search the entire directory tree i.e. the current directory and all levels of sub-directories. It denotes recursive searching.

-o Print only the matching string

-E Use extended regular expression

If we would not have used the second grep command after the pipe we would have got the IP address along with the path where it is present

Convert timestamp in milliseconds to string formatted time in Java

public static String timeDifference(long timeDifference1) {
long timeDifference = timeDifference1/1000;
int h = (int) (timeDifference / (3600));
int m = (int) ((timeDifference - (h * 3600)) / 60);
int s = (int) (timeDifference - (h * 3600) - m * 60);

return String.format("%02d:%02d:%02d", h,m,s);

How to determine the installed webpack version

Version Installed:

Using webpack CLI: (--version, -v Show version number [boolean])

webpack --version

or:

webpack -v

Using npm list command:

npm list webpack

Results in name@version-range:

<projectName>@<projectVersion> /path/to/project
+-- webpack@<version-range>

Using yarn list command:

yarn list webpack

How to do it programmatically?

Webpack 2 introduced Configuration Types.

Instead of exporting a configuration object, you may return a function which accepts an environment as argument. When running webpack, you may specify build environment keys via --env, such as --env.production or --env.platform=web.

We will use a build environment key called --env.version.

webpack --env.version $(webpack --version)

or:

webpack --env.version $(webpack -v)

For this to work we will need to do two things:

Change our webpack.config.js file and use DefinePlugin.

The DefinePlugin allows you to create global constants which can be configured at compile time.

-module.exports = {
+module.exports = function(env) {
+  return {
    plugins: [
      new webpack.DefinePlugin({
+        WEBPACK_VERSION: JSON.stringify(env.version) //<version-range>
      })
    ]
+  };
};

Now we can access the global constant like so:

console.log(WEBPACK_VERSION);

Latest version available:

Using npm view command will return the latest version available on the registry:

npm view [<@scope>/]<name>[@<version>] [<field>[.<subfield>]...]


For webpack use:

npm view webpack version

PHP: How to send HTTP response code?

Add this line before any output of the body, in the event you aren't using output buffering.

header("HTTP/1.1 200 OK");

Replace the message portion ('OK') with the appropriate message, and the status code with your code as appropriate (404, 501, etc)

How to convert a string to character array in c (or) how to extract a single char form string?

In C, there's no (real, distinct type of) strings. Every C "string" is an array of chars, zero terminated.

Therefore, to extract a character c at index i from string your_string, just use

char c = your_string[i];

Index is base 0 (first character is your_string[0], second is your_string[1]...).

How to send image to PHP file using Ajax?

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
      $(function () {

        $('#abc').on('submit', function (e) {

          e.preventDefault();

          $.ajax({
            url: 'post.php',
            method:'POST',
            data: new FormData(this),
            contentType: false,
            cache:false,
            processData:false,
            success: function (data) {
              alert(data);
              location.reload();
            }
          });

        });

      });
    </script>
  </head>
  <body>
    <form enctype= "multipart/form-data" id="abc">
      <input name="fname" ><br>
      <input name="lname"><br>
      <input type="file" name="file" required=""><br>
      <input name="submit" type="submit" value="Submit">
    </form>
  </body>
</html>

Center Oversized Image in Div

The width and height are only for example:

parentDiv{
    width: 100px;
    height: 100px;
    position:relative; 
}
innerDiv{
    width: 200px;
    height: 200px;
    position:absolute; 
    margin: auto;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
}

It has to work for you if the left and top of your parent div are not the very top and left of the window of your screen. It works for me.

Could not load the Tomcat server configuration

A quick solution in eclipse to resolve when Tomcat could not load as per the following error: Tomcat Error

Just refresh the Tomcat folder should do the trick. If it still does not work, delete all files in eclipse under the Tomcat folder, re-copy the server files then refresh the Tomcat folder. Tomcat should restart correctly after that.

Refresh Tomcat folder

The easiest way to transform collection to array?

Alternative solution to the updated question using Java 8:

Bar[] result = foos.stream()
    .map(x -> new Bar(x))
    .toArray(size -> new Bar[size]);

What is the difference between user variables and system variables?

Right-click My Computer and go to Properties->Advanced->Environmental Variables...

What's above are user variables, and below are system variables. The elements are combined when creating the environment for an application. System variables are shared for all users, but user variables are only for your account/profile.

If you deleted the system ones by accident, bring up the Registry Editor, then go to HKLM\ControlSet002\Control\Session Manager\Environment (assuming your current control set is not ControlSet002). Then find the Path value and copy the data into the Path value of HKLM\CurrentControlSet\Control\Session Manager\Environment. You might need to reboot the computer. (Hopefully, these backups weren't from too long ago, and they contain the info you need.)

How to multiply a BigDecimal by an integer in Java

You have a lot of type-mismatches in your code such as trying to put an int value where BigDecimal is required. The corrected version of your code:

public class Payment
{
    BigDecimal itemCost  = BigDecimal.ZERO;
    BigDecimal totalCost = BigDecimal.ZERO;

    public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
    {
        itemCost  = itemPrice.multiply(new BigDecimal(itemQuantity));
        totalCost = totalCost.add(itemCost);
        return totalCost;
    }
}

JSON order mixed up

from lemiorhan example i can solve with just change some line of lemiorhan's code use:

JSONObject json = new JSONObject(obj);

instead of this:

JSONObject json = (JSONObject) obj

so in my test code is :

Map item_sub2 = new LinkedHashMap();
item_sub2.put("name", "flare");
item_sub2.put("val1", "val1");
item_sub2.put("val2", "val2");
item_sub2.put("size",102);

JSONArray itemarray2 = new JSONArray();
itemarray2.add(item_sub2);
itemarray2.add(item_sub2);//just for test
itemarray2.add(item_sub2);//just for test


Map item_sub1 = new LinkedHashMap();
item_sub1.put("name", "flare");
item_sub1.put("val1", "val1");
item_sub1.put("val2", "val2");
item_sub1.put("children",itemarray2);

JSONArray itemarray = new JSONArray();
itemarray.add(item_sub1);
itemarray.add(item_sub1);//just for test
itemarray.add(item_sub1);//just for test

Map item_root = new LinkedHashMap();
item_root.put("name", "flare");
item_root.put("children",itemarray);

JSONObject json = new JSONObject(item_root);

System.out.println(json.toJSONString());

How to use npm with ASP.NET Core

What is the right approach for doing this?

There are a lot of "right" approaches, you just have decide which one best suites your needs. It appears as though you're misunderstanding how to use node_modules...

If you're familiar with NuGet you should think of npm as its client-side counterpart. Where the node_modules directory is like the bin directory for NuGet. The idea is that this directory is just a common location for storing packages, in my opinion it is better to take a dependency on the packages you need as you have done in the package.json. Then use a task runner like Gulp for example to copy the files you need into your desired wwwroot location.

I wrote a blog post about this back in January that details npm, Gulp and a whole bunch of other details that are still relevant today. Additionally, someone called attention to my SO question I asked and ultimately answered myself here, which is probably helpful.

I created a Gist that shows the gulpfile.js as an example.

In your Startup.cs it is still important to use static files:

app.UseStaticFiles();

This will ensure that your application can access what it needs.

How to reverse a 'rails generate'

This is a prototype to generate or destroy a controller or model in Rails:

rails generate/destroy controller/model [controller/model Name]

For example, if you need to generate a User Controller:

rails generate controller User

or

rails g controller User

If you want to destroy the User controller or revert to above action then use:

rails destroy controller User

or:

rails d controller User

enter image description here

How do I style radio buttons with images - laughing smiley for good, sad smiley for bad?

Here's a pure HTML+CSS solution.

HTML:

<div class="image-radio">
  <input type="radio" value="true" checked="checked" name="ice_cream" id="ice_cream_vanilla">
  <label for="ice_cream_vanilla">Vanilla</label>
  <input type="radio" value="true" name="ice_cream" id="ice_cream_chocolate">
  <label for="ice_cream_chocolate">Chocolate</label>
</div>

SCSS:

  // use an image instead of the native radio widget
.image-radio {   
  input[type=radio] {
    display: none;
  }
  input[type=radio] + label {
    background: asset-url('icons/choice-unchecked.svg') no-repeat left;
    padding-left: 2rem;
  }
  input[type=radio]:checked + label {
    background: asset-url('icons/choice-checked.svg') no-repeat left;
  }
}

How to read/write files in .Net Core?

Works in Net Core 2.1

    var file = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "email", "EmailRegister.htm");

    string SendData = System.IO.File.ReadAllText(file);

Check if one date is between two dates

Instead of comparing the dates directly, compare the getTime() value of the date. The getTime() function returns the number of milliseconds since Jan 1, 1970 as an integer-- should be trivial to determine if one integer falls between two other integers.

Something like

if((check.getTime() <= to.getTime() && check.getTime() >= from.getTime()))      alert("date contained");

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

To read characters try

scan("/PathTo/file.csv", "")

If you're reading numeric values, then just use

scan("/PathTo/file.csv")

scan by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).

Regex expressions in Java, \\s vs. \\s+

First of all you need to understand that final output of both the statements will be same i.e. to remove all the spaces from given string.

However x.replaceAll("\\s+", ""); will be more efficient way of trimming spaces (if string can have multiple contiguous spaces) because of potentially less no of replacements due the to fact that regex \\s+ matches 1 or more spaces at once and replaces them with empty string.

So even though you get the same output from both it is better to use:

x.replaceAll("\\s+", "");

How to form a correct MySQL connection string?

string MyConString = "Data Source='mysql7.000webhost.com';" +
"Port=3306;" +
"Database='a455555_test';" +
"UID='a455555_me';" +
"PWD='something';";

Opening the Settings app from another app

You can use the below code for it.

[[UIApplication sharedApplication]openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];

Redirecting to authentication dialog - "An error occurred. Please try again later"

For me the problem was that the Facebook users I was using to test the app did not have its email address confirmed by Facebook.

My client had set up 2 fake accounts on Facebook and told me that they were not working. But he forgot to confirm the email addresses of those accounts (the emails Facebook sent went to his spam folder and he didn't notice).

Took me hours to find this, so I hope it helps somebody.

Cheers!

Auto select file in Solution Explorer from its open tab

In Visual Studio 2012, the same can be done using the "Sync With Active Document" option in Solution Explorer

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

What worked for me:

  1. Add a folder to the project call it ThirdParty.
  2. Add in the ThirdParty folder both DocumentFormat.OpenXML.dll and WindowsBase.dll
  3. Make sure the the project uses the ThirdParty dir as reference for both the DLLs
  4. Build and published to an external server.

Disable single warning error

If you want to disable unreferenced local variable write in some header

template<class T>
void ignore (const T & ) {}

and use

catch(const Except & excpt) {
    ignore(excpt); // No warning
    // ...  
} 

Program does not contain a static 'Main' method suitable for an entry point

Maybe the "Output type" in properties->Application of the project must be a "Class Library" instead of console or windows application.

How to link home brew python version and set it as default

I use these commands to solve it.

mkdir /usr/local/lib
mkdir /usr/local/lib/pkgconfig
brew link python

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

I deleted folders build inside a project. After cleaned and rebuilt it in Android Studio. Then corrected errors in build.gradle and AndroidManifest.

Variables declared outside function

When Python parses a function, it notes when a variable assignment is made. When there is an assignment, it assumes by default that that variable is a local variable. To declare that the assignment refers to a global variable, you must use the global declaration.

When you access a variable in a function, its value is looked up using the LEGB scoping rules.


So, the first example

  x = 1
  def inc():
      x += 5
  inc()

produces an UnboundLocalError because Python determined x inside inc to be a local variable,

while accessing x works in your second example

 def inc():
    print x

because here, in accordance with the LEGB rule, Python looks for x in the local scope, does not find it, then looks for it in the extended scope, still does not find it, and finally looks for it in the global scope successfully.

Google Maps v2 - set both my location and zoom in

@CommonsWare's answer doesn't not actually work. I found that this is working properly :

map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-33.88,151.21), 15));

RecyclerView expand/collapse items

There is a very simple to use library with gradle support: https://github.com/cachapa/ExpandableLayout.

Right from the library docs:

<net.cachapa.expandablelayout.ExpandableLinearLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:el_duration="1000"
    app:el_expanded="true">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Click here to toggle expansion" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:text="Fixed height"
        app:layout_expandable="true" />

 </net.cachapa.expandablelayout.ExpandableLinearLayout>

After you mark your expandable views, just call any of these methods on the container: expand(), collapse() or toggle()

How to set my phpmyadmin user session to not time out so quickly?

Once you're logged into phpmyadmin look on the top navigation for "Settings" and click that then:

"Features" >

...and you'll find "Login cookie validity" which is typically set to 1440.

Unfortunately changing it through the UI means that the changes don't persist between logins.

Converting DateTime format using razor

In general, the written month is escaped as MMM, the 4-digit year as yyyy, so your format string should look like "dd MMM yyyy"

DateTime.ToString("dd MMM yyyy")

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

Here's another way through the GUI that does exactly what your script does even though it goes through Indexes (not Constraints) in the object explorer.

  1. Right click on "Indexes" and click "New Index..." (note: this is disabled if you have the table open in design view)

enter image description here

  1. Give new index a name ("U_Name"), check "Unique", and click "Add..."

enter image description here

  1. Select "Name" column in the next windown

enter image description here

  1. Click OK in both windows

Amazon Interview Question: Design an OO parking lot

public class ParkingLot 
{
    Vector<ParkingSpace> vacantParkingSpaces = null;
    Vector<ParkingSpace> fullParkingSpaces = null;

    int parkingSpaceCount = 0;

    boolean isFull;
    boolean isEmpty;

    ParkingSpace findNearestVacant(ParkingType type)
    {
        Iterator<ParkingSpace> itr = vacantParkingSpaces.iterator();

        while(itr.hasNext())
        {
            ParkingSpace parkingSpace = itr.next();

            if(parkingSpace.parkingType == type)
            {
                return parkingSpace;
            }
        }
        return null;
    }

    void parkVehicle(ParkingType type, Vehicle vehicle)
    {
        if(!isFull())
        {
            ParkingSpace parkingSpace = findNearestVacant(type);

            if(parkingSpace != null)
            {
                parkingSpace.vehicle = vehicle;
                parkingSpace.isVacant = false;

                vacantParkingSpaces.remove(parkingSpace);
                fullParkingSpaces.add(parkingSpace);

                if(fullParkingSpaces.size() == parkingSpaceCount)
                    isFull = true;

                isEmpty = false;
            }
        }
    }

    void releaseVehicle(Vehicle vehicle)
    {
        if(!isEmpty())
        {
            Iterator<ParkingSpace> itr = fullParkingSpaces.iterator();

            while(itr.hasNext())
            {
                ParkingSpace parkingSpace = itr.next();

                if(parkingSpace.vehicle.equals(vehicle))
                {
                    fullParkingSpaces.remove(parkingSpace);
                    vacantParkingSpaces.add(parkingSpace);

                    parkingSpace.isVacant = true;
                    parkingSpace.vehicle = null;

                    if(vacantParkingSpaces.size() == parkingSpaceCount)
                        isEmpty = true;

                    isFull = false;
                }
            }
        }
    }

    boolean isFull()
    {
        return isFull;
    }

    boolean isEmpty()
    {
        return isEmpty;
    }
}

public class ParkingSpace 
{
    boolean isVacant;
    Vehicle vehicle;
    ParkingType parkingType;
    int distance;
}

public class Vehicle 
{
    int num;
}

public enum ParkingType
{
    REGULAR,
    HANDICAPPED,
    COMPACT,
    MAX_PARKING_TYPE,
}

What does print(... sep='', '\t' ) mean?

The sep='\t' can be use in many forms, for example if you want to read tab separated value: Example: I have a dataset tsv = tab separated value NOT comma separated value df = pd.read_csv('gapminder.tsv'). when you try to read this, it will give you an error because you have tab separated value not csv. so you need to give read csv a different parameter called sep='\t'.

Now you can read: df = pd.read_csv('gapminder.tsv, sep='\t'), with this you can read the it.

Invisible characters - ASCII

An invisible Character is ?, or U+200b

?

Could not open ServletContext resource

Mark sure propertie file is in "/WEB-INF/classes" try to use

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="location">
        <value>/WEB-INF/classes/social.properties</value>
    </property>
</bean>

Local file access with JavaScript

UPDATE This feature is removed since Firefox 17 (see https://bugzilla.mozilla.org/show_bug.cgi?id=546848).


On Firefox you (the programmer) can do this from within a JavaScript file:

netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserWrite");

and you (the browser user) will be prompted to allow access. (for Firefox you just need to do this once every time the browser is started)

If the browser user is someone else, they have to grant permission.

MySQL Query to select data from last week?

WHERE yourDateColumn > DATEADD(DAY, -7, GETDATE()) ;

Run Android studio emulator on AMD processor

My laptop runs on AMD Ryzen 5 and I was facing a similar issue. I tried some of the fixes here but didn't work but eventually, I read hundreds of blogs and came up with a solution. You need the following setup requirements to be in place:

AMD Processor - Recommended: AMD® Ryzen™ processors Android Studio 3.2 Beta or higher(I run on BETA, However the latest version of Android Studio doesn't need you to install ARM images anymore) Android Emulator v27.3.8+ x86 Android Virtual Device (AVD) Windows 10 with April 2018 Update Enable via Windows Features: "Windows Hypervisor Platform"

With all these features in place, I was running Android studio again. Hope it helped!

How do I plot list of tuples in Python?

If I get your question correctly, you could do something like this.

>>> import matplotlib.pyplot as plt
>>> testList =[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08), 
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09), 
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]
>>> from math import log
>>> testList2 = [(elem1, log(elem2)) for elem1, elem2 in testList]
>>> testList2
[(0, -16.617236475334405), (1, -17.67799605473062), (2, -18.691431541177973), (3, -18.9767093108359), (4, -19.420021520728017), (5, -19.298411635970396)]
>>> zip(*testList2)
[(0, 1, 2, 3, 4, 5), (-16.617236475334405, -17.67799605473062, -18.691431541177973, -18.9767093108359, -19.420021520728017, -19.298411635970396)]
>>> plt.scatter(*zip(*testList2))
>>> plt.show()

which would give you something like

enter image description here

Or as a line plot,

>>> plt.plot(*zip(*testList2))
>>> plt.show()

enter image description here

EDIT - If you want to add a title and labels for the axis, you could do something like

>>> plt.scatter(*zip(*testList2))
>>> plt.title('Random Figure')
>>> plt.xlabel('X-Axis')
>>> plt.ylabel('Y-Axis')
>>> plt.show()

which would give you

enter image description here

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

This isn't exactly an "asking for yes or no" but just a hack: alias the hg push ... not to hgpushrepo but to hgpushrepoconfirmedpush and by the time I can spell out the whole thing, the left brain has made a logical choice.

How to define custom exception class in Java, the easiest way?

Exception class has two constructors

  • public Exception() -- This constructs an Exception without any additional information.Nature of the exception is typically inferred from the class name.
  • public Exception(String s) -- Constructs an exception with specified error message.A detail message is a String that describes the error condition for this particular exception.

How to strip a specific word from a string?

You can also use a regexp with re.sub:

article_title_str = re.sub(r'(\s?-?\|?\s?Times of India|\s?-?\|?\s?the Times of India|\s?-?\|?\s+?Gadgets No'',
                           article_title_str, flags=re.IGNORECASE)

Download the Android SDK components for offline install

follow this video https://www.youtube.com/watch?v=883HjO06_E0 for how to download and install Android SDK components manually

How do you clone a Git repository into a specific folder?

You can use following git command to clone with custom directory name

git clone <git_repo_url> <your_custom_directory_name>

Note: You don't need to create your custom directory because it will create automatically

Jquery array.push() not working

another workaround:

var myarray = [];
$("#test").click(function() {
    myarray[index]=$("#drop").val();
    alert(myarray);
});

i wanted to add all checked checkbox to array. so example, if .each is used:

var vpp = [];
var incr=0;
$('.prsn').each(function(idx) {
   if (this.checked) {
       var p=$('.pp').eq(idx).val();
       vpp[incr]=(p);
       incr++;
   }
});
//do what ever with vpp array;

How do I force Robocopy to overwrite files?

This is really weird, why nobody is mentioning the /IM switch ?! I've been using it for a long time in backup jobs. But I tried googling just now and I couldn't land on a single web page that says anything about it even on MS website !!! Also found so many user posts complaining about the same issue!!

Anyway.. to use Robocopy to overwrite EVERYTHING what ever size or time in source or distination you must include these three switches in your command (/IS /IT /IM)

/IS :: Include Same files. (Includes same size files)
/IT :: Include Tweaked files. (Includes same files with different Attributes)
/IM :: Include Modified files (Includes same files with different times).

This is the exact command I use to transfer few TeraBytes of mostly 1GB+ files (ISOs - Disk Images - 4K Videos):

robocopy B:\Source D:\Destination /E /J /COPYALL /MT:1 /DCOPY:DATE /IS /IT /IM /X /V /NP /LOG:A:\ROBOCOPY.LOG

I did a small test for you .. and here is the result:

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :      1028      1028         0         0         0       169
   Files :      8053      8053         0         0         0         1
   Bytes : 649.666 g 649.666 g         0         0         0   1.707 g
   Times :   2:46:53   0:41:43                       0:00:00   0:41:44


   Speed :           278653398 Bytes/sec.
   Speed :           15944.675 MegaBytes/min.
   Ended : Friday, August 21, 2020 7:34:33 AM

Dest, Disk: WD Gold 6TB (Compare the write speed with my result)

Even with those "Extras", that's for reporting only because of the "/X" switch. As you can see nothing was Skipped and Total number and size of all files are equal to the Copied. Sometimes It will show small number of skipped files when I abuse it and cancel it multiple times during operation but even with that the values in the first 2 columns are always Equal. I also confirmed that once before by running a PowerShell script that scans all files in destination and generate a report of all time-stamps.

Some performance tips from my history with it and so many tests & troubles!:

. Despite of what most users online advise to use maximum threads "/MT:128" like it's a general trick to get the best performance ... PLEASE DON'T USE "/MT:128" WITH VERY LARGE FILES ... that's a big mistake and it will decrease your drive performance dramatically after several runs .. it will create very high fragmentation or even cause the files system to fail in some cases and you end up spending valuable time trying to recover a RAW partition and all that nonsense. And above all that, It will perform 4-6 times slower!!

For very large files:

  1. Use Only "One" thread "/MT:1" | Impact: BIG
  2. Must use "/J" to disable buffering. | Impact: High
  3. Use "/NP" with "/LOG:file" and Don't output to the console by "/TEE" | Impact: Medium.
  4. Put the "/LOG:file" on a separate drive from the source or destination | Impact: Low.

For regular big files:

  1. Use multi threads, I would not exceed "/MT:4" | Impact: BIG
  2. IF destination disk has low Cache specs use "/J" to disable buffering | Impact: High
  3. & 4 same as above.

For thousands of tiny files:

  1. Go nuts :) with Multi threads, at first I would start with 16 and multibly by 2 while monitoring the disk performance. Once it starts dropping I'll fall back to the prevouse value and stik with it | Impact: BIG
  2. Don't use "/J" | Impact: High
  3. Use "/NP" with "/LOG:file" and Don't output to the console by "/TEE" | Impact: HIGH.
  4. Put the "/LOG:file" on a separate drive from the source or destination | Impact: HIGH.

Jquery .on('scroll') not firing the event while scrolling

I know that this is quite old thing, but I solved issue like that: I had parent and child element was scrollable.

   if ($('#parent > *').length == 0 ){
        var wait = setInterval(function() {
            if($('#parent > *').length != 0 ) {
                $('#parent .child').bind('scroll',function() {
                  //do staff
                });
                clearInterval(wait);
            },1000);
        }

The issue I had is that I didn't know when the child is loaded to DOM, but I kept checking for it every second.

NOTE:this is useful if it happens soon but not right after document load, otherwise it will use clients computing power for no reason.

How to draw a path on a map using kml file?

In above code, you don't pass the kml data to your mapView anywhere in your code, as far as I can see. To display the route, you should parse the kml data i.e. via SAX parser, then display the route markers on the map.

See the code below for an example, but it's not complete though - just for you as a reference and get some idea.

This is a simple bean I use to hold the route information I will be parsing.

package com.myapp.android.model.navigation;

import java.util.ArrayList;
import java.util.Iterator;


public class NavigationDataSet { 

private ArrayList<Placemark> placemarks = new ArrayList<Placemark>();
private Placemark currentPlacemark;
private Placemark routePlacemark;

public String toString() {
    String s= "";
    for (Iterator<Placemark> iter=placemarks.iterator();iter.hasNext();) {
        Placemark p = (Placemark)iter.next();
        s += p.getTitle() + "\n" + p.getDescription() + "\n\n";
    }
    return s;
}

public void addCurrentPlacemark() {
    placemarks.add(currentPlacemark);
}

public ArrayList<Placemark> getPlacemarks() {
    return placemarks;
}

public void setPlacemarks(ArrayList<Placemark> placemarks) {
    this.placemarks = placemarks;
}

public Placemark getCurrentPlacemark() {
    return currentPlacemark;
}

public void setCurrentPlacemark(Placemark currentPlacemark) {
    this.currentPlacemark = currentPlacemark;
}

public Placemark getRoutePlacemark() {
    return routePlacemark;
}

public void setRoutePlacemark(Placemark routePlacemark) {
    this.routePlacemark = routePlacemark;
}

}

And the SAX Handler to parse the kml:

package com.myapp.android.model.navigation;

import android.util.Log;
import com.myapp.android.myapp;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.myapp.android.model.navigation.NavigationDataSet;
import com.myapp.android.model.navigation.Placemark;


public class NavigationSaxHandler extends DefaultHandler{ 

 // =========================================================== 
 // Fields 
 // =========================================================== 

 private boolean in_kmltag = false; 
 private boolean in_placemarktag = false; 
 private boolean in_nametag = false;
 private boolean in_descriptiontag = false;
 private boolean in_geometrycollectiontag = false;
 private boolean in_linestringtag = false;
 private boolean in_pointtag = false;
 private boolean in_coordinatestag = false;

 private StringBuffer buffer;

 private NavigationDataSet navigationDataSet = new NavigationDataSet(); 

 // =========================================================== 
 // Getter & Setter 
 // =========================================================== 

 public NavigationDataSet getParsedData() {
      navigationDataSet.getCurrentPlacemark().setCoordinates(buffer.toString().trim());
      return this.navigationDataSet; 
 } 

 // =========================================================== 
 // Methods 
 // =========================================================== 
 @Override 
 public void startDocument() throws SAXException { 
      this.navigationDataSet = new NavigationDataSet(); 
 } 

 @Override 
 public void endDocument() throws SAXException { 
      // Nothing to do
 } 

 /** Gets be called on opening tags like: 
  * <tag> 
  * Can provide attribute(s), when xml was like: 
  * <tag attribute="attributeValue">*/ 
 @Override 
 public void startElement(String namespaceURI, String localName, 
           String qName, Attributes atts) throws SAXException { 
      if (localName.equals("kml")) { 
           this.in_kmltag = true;
      } else if (localName.equals("Placemark")) { 
           this.in_placemarktag = true; 
           navigationDataSet.setCurrentPlacemark(new Placemark());
      } else if (localName.equals("name")) { 
           this.in_nametag = true;
      } else if (localName.equals("description")) { 
          this.in_descriptiontag = true;
      } else if (localName.equals("GeometryCollection")) { 
          this.in_geometrycollectiontag = true;
      } else if (localName.equals("LineString")) { 
          this.in_linestringtag = true;              
      } else if (localName.equals("point")) { 
          this.in_pointtag = true;          
      } else if (localName.equals("coordinates")) {
          buffer = new StringBuffer();
          this.in_coordinatestag = true;                        
      }
 } 

 /** Gets be called on closing tags like: 
  * </tag> */ 
 @Override 
 public void endElement(String namespaceURI, String localName, String qName) 
           throws SAXException { 
       if (localName.equals("kml")) {
           this.in_kmltag = false; 
       } else if (localName.equals("Placemark")) { 
           this.in_placemarktag = false;

       if ("Route".equals(navigationDataSet.getCurrentPlacemark().getTitle())) 
               navigationDataSet.setRoutePlacemark(navigationDataSet.getCurrentPlacemark());
        else navigationDataSet.addCurrentPlacemark();

       } else if (localName.equals("name")) { 
           this.in_nametag = false;           
       } else if (localName.equals("description")) { 
           this.in_descriptiontag = false;
       } else if (localName.equals("GeometryCollection")) { 
           this.in_geometrycollectiontag = false;
       } else if (localName.equals("LineString")) { 
           this.in_linestringtag = false;              
       } else if (localName.equals("point")) { 
           this.in_pointtag = false;          
       } else if (localName.equals("coordinates")) { 
           this.in_coordinatestag = false;
       }
 } 

 /** Gets be called on the following structure: 
  * <tag>characters</tag> */ 
 @Override 
public void characters(char ch[], int start, int length) { 
    if(this.in_nametag){ 
        if (navigationDataSet.getCurrentPlacemark()==null) navigationDataSet.setCurrentPlacemark(new Placemark());
        navigationDataSet.getCurrentPlacemark().setTitle(new String(ch, start, length));            
    } else 
    if(this.in_descriptiontag){ 
        if (navigationDataSet.getCurrentPlacemark()==null) navigationDataSet.setCurrentPlacemark(new Placemark());
        navigationDataSet.getCurrentPlacemark().setDescription(new String(ch, start, length));          
    } else
    if(this.in_coordinatestag){        
        if (navigationDataSet.getCurrentPlacemark()==null) navigationDataSet.setCurrentPlacemark(new Placemark());
        //navigationDataSet.getCurrentPlacemark().setCoordinates(new String(ch, start, length));
        buffer.append(ch, start, length);
    }
} 
}

and a simple placeMark bean:

package com.myapp.android.model.navigation;

public class Placemark {

String title;
String description;
String coordinates;
String address;

public String getTitle() {
    return title;
}
public void setTitle(String title) {
    this.title = title;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
public String getCoordinates() {
    return coordinates;
}
public void setCoordinates(String coordinates) {
    this.coordinates = coordinates;
}
public String getAddress() {
    return address;
}
public void setAddress(String address) {
    this.address = address;
}

}

Finally the service class in my model that calls the calculation:

package com.myapp.android.model.navigation;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import com.myapp.android.myapp;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.util.Log;

public class MapService {

public static final int MODE_ANY = 0;
public static final int MODE_CAR = 1;
public static final int MODE_WALKING = 2;


public static String inputStreamToString (InputStream in) throws IOException {
    StringBuffer out = new StringBuffer();
    byte[] b = new byte[4096];
    for (int n; (n = in.read(b)) != -1;) {
        out.append(new String(b, 0, n));
    }
    return out.toString();
}


public static NavigationDataSet calculateRoute(Double startLat, Double startLng, Double targetLat, Double targetLng, int mode) {
    return calculateRoute(startLat + "," + startLng, targetLat + "," + targetLng, mode);
}

public static NavigationDataSet calculateRoute(String startCoords, String targetCoords, int mode) {
    String urlPedestrianMode = "http://maps.google.com/maps?" + "saddr=" + startCoords + "&daddr="
            + targetCoords + "&sll=" + startCoords + "&dirflg=w&hl=en&ie=UTF8&z=14&output=kml";

    Log.d(myapp.APP, "urlPedestrianMode: "+urlPedestrianMode);

    String urlCarMode = "http://maps.google.com/maps?" + "saddr=" + startCoords + "&daddr="
            + targetCoords + "&sll=" + startCoords + "&hl=en&ie=UTF8&z=14&output=kml";

    Log.d(myapp.APP, "urlCarMode: "+urlCarMode);

    NavigationDataSet navSet = null;
    // for mode_any: try pedestrian route calculation first, if it fails, fall back to car route
    if (mode==MODE_ANY||mode==MODE_WALKING) navSet = MapService.getNavigationDataSet(urlPedestrianMode);
    if (mode==MODE_ANY&&navSet==null||mode==MODE_CAR) navSet = MapService.getNavigationDataSet(urlCarMode);
    return navSet;
}

/**
 * Retrieve navigation data set from either remote URL or String
 * @param url
 * @return navigation set
 */
public static NavigationDataSet getNavigationDataSet(String url) {

    // urlString = "http://192.168.1.100:80/test.kml";
    Log.d(myapp.APP,"urlString -->> " + url);
    NavigationDataSet navigationDataSet = null;
    try
        {           
        final URL aUrl = new URL(url);
        final URLConnection conn = aUrl.openConnection();
        conn.setReadTimeout(15 * 1000);  // timeout for reading the google maps data: 15 secs
        conn.connect();

        /* Get a SAXParser from the SAXPArserFactory. */
        SAXParserFactory spf = SAXParserFactory.newInstance(); 
        SAXParser sp = spf.newSAXParser(); 

        /* Get the XMLReader of the SAXParser we created. */
        XMLReader xr = sp.getXMLReader();

        /* Create a new ContentHandler and apply it to the XML-Reader*/ 
        NavigationSaxHandler navSax2Handler = new NavigationSaxHandler(); 
        xr.setContentHandler(navSax2Handler); 

        /* Parse the xml-data from our URL. */ 
        xr.parse(new InputSource(aUrl.openStream()));

        /* Our NavigationSaxHandler now provides the parsed data to us. */ 
        navigationDataSet = navSax2Handler.getParsedData(); 

        /* Set the result to be displayed in our GUI. */ 
        Log.d(myapp.APP,"navigationDataSet: "+navigationDataSet.toString());

    } catch (Exception e) {
        // Log.e(myapp.APP, "error with kml xml", e);
        navigationDataSet = null;
    }   

    return navigationDataSet;
}

}

Drawing:

/**
 * Does the actual drawing of the route, based on the geo points provided in the nav set
 *
 * @param navSet     Navigation set bean that holds the route information, incl. geo pos
 * @param color      Color in which to draw the lines
 * @param mMapView01 Map view to draw onto
 */
public void drawPath(NavigationDataSet navSet, int color, MapView mMapView01) {

    Log.d(myapp.APP, "map color before: " + color);        

    // color correction for dining, make it darker
    if (color == Color.parseColor("#add331")) color = Color.parseColor("#6C8715");
    Log.d(myapp.APP, "map color after: " + color);

    Collection overlaysToAddAgain = new ArrayList();
    for (Iterator iter = mMapView01.getOverlays().iterator(); iter.hasNext();) {
        Object o = iter.next();
        Log.d(myapp.APP, "overlay type: " + o.getClass().getName());
        if (!RouteOverlay.class.getName().equals(o.getClass().getName())) {
            // mMapView01.getOverlays().remove(o);
            overlaysToAddAgain.add(o);
        }
    }
    mMapView01.getOverlays().clear();
    mMapView01.getOverlays().addAll(overlaysToAddAgain);

    String path = navSet.getRoutePlacemark().getCoordinates();
    Log.d(myapp.APP, "path=" + path);
    if (path != null && path.trim().length() > 0) {
        String[] pairs = path.trim().split(" ");

        Log.d(myapp.APP, "pairs.length=" + pairs.length);

        String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height

        Log.d(myapp.APP, "lnglat =" + lngLat + ", length: " + lngLat.length);

        if (lngLat.length<3) lngLat = pairs[1].split(","); // if first pair is not transferred completely, take seconds pair //TODO 

        try {
            GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));
            mMapView01.getOverlays().add(new RouteOverlay(startGP, startGP, 1));
            GeoPoint gp1;
            GeoPoint gp2 = startGP;

            for (int i = 1; i < pairs.length; i++) // the last one would be crash
            {
                lngLat = pairs[i].split(",");

                gp1 = gp2;

                if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
                        && gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {

                    // for GeoPoint, first:latitude, second:longitude
                    gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));

                    if (gp2.getLatitudeE6() != 22200000) { 
                        mMapView01.getOverlays().add(new RouteOverlay(gp1, gp2, 2, color));
                        Log.d(myapp.APP, "draw:" + gp1.getLatitudeE6() + "/" + gp1.getLongitudeE6() + " TO " + gp2.getLatitudeE6() + "/" + gp2.getLongitudeE6());
                    }
                }
                // Log.d(myapp.APP,"pair:" + pairs[i]);
            }
            //routeOverlays.add(new RouteOverlay(gp2,gp2, 3));
            mMapView01.getOverlays().add(new RouteOverlay(gp2, gp2, 3));
        } catch (NumberFormatException e) {
            Log.e(myapp.APP, "Cannot draw route.", e);
        }
    }
    // mMapView01.getOverlays().addAll(routeOverlays); // use the default color
    mMapView01.setEnabled(true);
}

This is the RouteOverlay class:

package com.myapp.android.activity.map.nav;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;

public class RouteOverlay extends Overlay { 

private GeoPoint gp1;
private GeoPoint gp2;
private int mRadius=6;
private int mode=0;
private int defaultColor;
private String text="";
private Bitmap img = null;

public RouteOverlay(GeoPoint gp1,GeoPoint gp2,int mode) { // GeoPoint is a int. (6E)
    this.gp1 = gp1;
    this.gp2 = gp2;
    this.mode = mode;
    defaultColor = 999; // no defaultColor
}

public RouteOverlay(GeoPoint gp1,GeoPoint gp2,int mode, int defaultColor) {
    this.gp1 = gp1;
    this.gp2 = gp2;
    this.mode = mode;
    this.defaultColor = defaultColor;
}

public void setText(String t) {
    this.text = t;
}

public void setBitmap(Bitmap bitmap) { 
    this.img = bitmap;
}

public int getMode() {
    return mode;
}

@Override
public boolean draw (Canvas canvas, MapView mapView, boolean shadow, long when) {
    Projection projection = mapView.getProjection();
    if (shadow == false) {
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        Point point = new Point();
        projection.toPixels(gp1, point);
        // mode=1&#65306;start
        if(mode==1) {
            if(defaultColor==999)
            paint.setColor(Color.BLACK); // Color.BLUE
            else
            paint.setColor(defaultColor);
            RectF oval=new RectF(point.x - mRadius, point.y - mRadius,
            point.x + mRadius, point.y + mRadius);
            // start point
            canvas.drawOval(oval, paint);
        }
        // mode=2&#65306;path
        else if(mode==2) {
            if(defaultColor==999)
            paint.setColor(Color.RED);
            else
            paint.setColor(defaultColor);
            Point point2 = new Point();
            projection.toPixels(gp2, point2);
            paint.setStrokeWidth(5);
            paint.setAlpha(defaultColor==Color.parseColor("#6C8715")?220:120);
            canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
        }
        /* mode=3&#65306;end */
        else if(mode==3) {
            /* the last path */

            if(defaultColor==999)
                paint.setColor(Color.BLACK);  // Color.GREEN
            else
                paint.setColor(defaultColor);

            Point point2 = new Point();
            projection.toPixels(gp2, point2);
            paint.setStrokeWidth(5);
            paint.setAlpha(defaultColor==Color.parseColor("#6C8715")?220:120);
            canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
            RectF oval=new RectF(point2.x - mRadius,point2.y - mRadius,
            point2.x + mRadius,point2.y + mRadius);
            /* end point */
            paint.setAlpha(255);
            canvas.drawOval(oval, paint);
        }
    }
    return super.draw(canvas, mapView, shadow, when);
}

}

What is the proper way to check if a string is empty in Perl?

To check for an empty string you could also do something as follows

if (!defined $val || $val eq '')
{
    # empty
}

Items in JSON object are out of order using "json.dumps"?

The order of a dictionary doesn't have any relationship to the order it was defined in. This is true of all dictionaries, not just those turned into JSON.

>>> {"b": 1, "a": 2}
{'a': 2, 'b': 1}

Indeed, the dictionary was turned "upside down" before it even reached json.dumps:

>>> {"id":1,"name":"David","timezone":3}
{'timezone': 3, 'id': 1, 'name': 'David'}

Get textarea text with javascript or Jquery

To get the value from a textarea with an id you just have to do

Edited

$("#area1").val();

If you are having more than one element with the same id in the document then the HTML is invalid.

Why is my CSS style not being applied?

In addition to the solutions posted above, having gone through the exact same problem, make sure you check your HTML. More specifically whether you've properly labelled your elements, as well as class and id selectors. You can do this either manually or through a validator (https://validator.w3.org/).

For me, I missed the equal sign next to the class (<div class someDiv> vs <div class = "someDiv">, hence why no CSS property was applied.

"Please try running this command again as Root/Administrator" error when trying to install LESS

Re Explosion Pills "An installation can run arbitrary scripts and running it with sudo can be extremely dangerous!"

Seems like using sudo is the wrong way of doing it.

"Change the owner of the files in your /usr/local folder to the current user:"

sudo chown -R $USER /usr/local

Then run the install

node install -g less

Check out:

What is the difference between <jsp:include page = ... > and <%@ include file = ... >?

Java Revisited

  1. Resource included by include directive is loaded during jsp translation time, while resource included by include action is loaded during request time.
  2. Any change on included resource will not be visible in case of include directive until jsp file compiles again. While in case of include action, any change in included resource will be visible in next request.
  3. Include directive is static import, while include action is dynamic import
  4. Include directive uses file attribute to specify resource to be included while include action use page attribute for same purpose.

Using continue in a switch statement

It's fine, the continue statement relates to the enclosing loop, and your code should be equivalent to (avoiding such jump statements):

while (something = get_something()) {
    if (something == A || something == B)
        do_something();
}

But if you expect break to exit the loop, as your comment suggest (it always tries again with another something, until it evaluates to false), you'll need a different structure.

For example:

do {
    something = get_something();
} while (!(something == A || something == B));
do_something();

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

It is hard to get pip working on El Capitan for several reasons:

  1. OS X doesn't set some distutils variables correctly, so pip tries to install ancillary files in locations under /System/Library/. El Capitan blocks this, which is the error you are running into.
  2. OS X includes a number of outdated packages under /System/Library/. pip often wants to upgrade these but cannot on El Capitan.
  3. OS X places /System/Library/ higher in the python search order than /Library/Python/2.7/site-packages (the system-wide python package location), so even if you manage to install newer versions of some packages, the old ones still get loaded, breaking some dependencies.

There are workarounds for all of these at https://apple.stackexchange.com/a/223163/143849 . But you may be best off installing your own version of Python via the standard Python installer, Homebrew or Anaconda.

Go build: "Cannot find package" (even though GOPATH is set)

In the recent go versions from 1.14 onwards, we have to do go mod vendor before building or running, since by default go appends -mod=vendor to the go commands. So after doing go mod vendor, if we try to build, we won't face this issue.

rails simple_form - hidden field - create?

Correct way (if you are not trying to reset the value of the hidden_field input) is:

f.hidden_field :method, :value => value_of_the_hidden_field_as_it_comes_through_in_your_form

Where :method is the method that when called on the object results in the value you want

So following the example above:

= simple_form_for @movie do |f|
  = f.hidden :title, "some value"
  = f.button :submit

The code used in the example will reset the value (:title) of @movie being passed by the form. If you need to access the value (:title) of a movie, instead of resetting it, do this:

= simple_form_for @movie do |f|
  = f.hidden :title, :value => params[:movie][:title]
  = f.button :submit

Again only use my answer is you do not want to reset the value submitted by the user.

I hope this makes sense.

How can I uninstall Ruby on ubuntu?

Why you are removing old version of the ruby?

rvm install 2.4.2 // version of ruby u need to insatll rvm use 2.4.2 --default // set ruby version you want use by default

Using rvm you can install multiple ruby version in the system

Please follow below steps install ruby using rvm

sudo apt-get install libgdbm-dev libncurses5-dev automake libtool bison libffi-dev
gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3 
curl -sSL https://get.rvm.io | bash -s stable 
source ~/.rvm/scripts/rvm
rvm install 2.4.2 
rvm use 2.4.2 --default 
ruby -v

The installation step will change for different Ubuntu version

For more info,

https://gorails.com/setup/ubuntu/14.04

How to Apply Gradient to background view of iOS Swift App

Just Specify the Frame of the View, where you want to show the gradient color.

let firstColor =  UIColor(red: 69/255, green: 90/255, blue: 195/255, alpha: 1.0).CGColor

 let secondColor = UIColor(red: 230/255, green: 44/255, blue: 75/255, alpha: 1.0).CGColor

    let gradientLayer = CAGradientLayer()
    gradientLayer.colors = [ firstColor, secondColor]
    gradientLayer.locations = [ 0.0, 1.0]
    gradientLayer.frame = CGRectMake(0, 0, 375, 64)// You can mention frame here

    self.view.layer.addSublayer(gradientLayer)

How to prevent gcc optimizing some statements in C?

Instead of using the new pragmas, you can also use __attribute__((optimize("O0"))) for your needs. This has the advantage of just applying to a single function and not all functions defined in the same file.

Usage example:

void __attribute__((optimize("O0"))) foo(unsigned char data) {
    // unmodifiable compiler code
}

PHP - Get array value with a numeric index

I am proposing my idea about it against any disadvantages array_values( ) function, because I think that is not a direct get function. In this way it have to create a copy of the values numerically indexed array and then access. If PHP does not hide a method that automatically translates an integer in the position of the desired element, maybe a slightly better solution might consist of a function that runs the array with a counter until it leads to the desired position, then return the element reached.

So the work would be optimized for very large array of sizes, since the algorithm would be best performing indices for small, stopping immediately. In the solution highlighted of array_values( ), however, it has to do with a cycle flowing through the whole array, even if, for e.g., I have to access $ array [1].

function array_get_by_index($index, $array) {

    $i=0;
    foreach ($array as $value) {
        if($i==$index) {
            return $value;
        }
        $i++;
    }
    // may be $index exceedes size of $array. In this case NULL is returned.
    return NULL;
}

How do I correctly detect orientation change using Phonegap on iOS?

This is what I do:

_x000D_
_x000D_
function doOnOrientationChange() {_x000D_
    switch(window.orientation) {  _x000D_
      case -90: case 90:_x000D_
        alert('landscape');_x000D_
        break; _x000D_
      default:_x000D_
        alert('portrait');_x000D_
        break; _x000D_
    }_x000D_
}_x000D_
  _x000D_
window.addEventListener('orientationchange', doOnOrientationChange);_x000D_
  _x000D_
// Initial execution if needed_x000D_
doOnOrientationChange();
_x000D_
_x000D_
_x000D_


Update May 2019: window.orientation is a deprecated feature and not supported by most browsers according to MDN. The orientationchange event is associated with window.orientation and therefore should probably not be used.

read subprocess stdout line by line

Pythont 3.5 added the methods run() and call() to the subprocess module, both returning a CompletedProcess object. With this you are fine using proc.stdout.splitlines():

proc = subprocess.run( comman, shell=True, capture_output=True, text=True, check=True )
for line in proc.stdout.splitlines():
   print "stdout:", line

See also How to Execute Shell Commands in Python Using the Subprocess Run Method

MVC Return Partial View as JSON

Url.Action("Evil", model)

will generate a get query string but your ajax method is post and it will throw error status of 500(Internal Server Error). – Fereydoon Barikzehy Feb 14 at 9:51

Just Add "JsonRequestBehavior.AllowGet" on your Json object.

How to close a web page on a button click, a hyperlink or a link button click?

double click the button and add write // this.close();

  private void buttonClick(object sender, EventArgs e)
{
    this.Close();
}

Asynchronous shell exec in PHP

On linux you can do the following:

$cmd = 'nohup nice -n 10 php -f php/file.php > log/file.log & printf "%u" $!';
$pid = shell_exec($cmd);

This will execute the command at the command prompty and then just return the PID, which you can check for > 0 to ensure it worked.

This question is similar: Does PHP have threading?

Eclipse java debugging: source not found

I had this problem while working on java code to do process on a excel file containing a data set, then convert it to .csv file, i tried answers to this post, but they did not work. the problem was the jar files themselves. after downloading needed jar files one by one(older releases) and add them to my project, "source not found" error vanished. maybe you can check your jar files. hope this would help.

How to check Spark Version

According to the Cloudera documentation - What's New in CDH 5.7.0 it includes Spark 1.6.0.

Setting "checked" for a checkbox with jQuery

I couldn't get it working using:

$("#cb").prop('checked', 'true');
$("#cb").prop('checked', 'false');

Both true and false would check the checkbox. What worked for me was:

$("#cb").prop('checked', 'true'); // For checking
$("#cb").prop('checked', '');     // For unchecking

How to use if statements in LESS

I stumbled over the same question and I've found a solution.

First make sure you upgrade to LESS 1.6 at least. You can use npm for that case.

Now you can use the following mixin:

.if (@condition, @property, @value) when (@condition = true){
     @{property}: @value;
 }

Since LESS 1.6 you are able to pass PropertyNames to Mixins as well. So for example you could just use:

.myHeadline {
   .if(@include-lineHeight,  line-height, '35px');
}

If @include-lineheight resolves to true LESS will print the line-height: 35px and it will skip the mixin if @include-lineheight is not true.

Getting the client's time zone (and offset) in JavaScript

Try this :

new Date().toLocaleString("en-US",Intl.DateTimeFormat().resolvedOptions().timeZone)

This will look for timeZone on your client's browser.

WPF ListView - detect when selected item is clicked

You can handle click on list view item like this:

<ListView.ItemTemplate>
  <DataTemplate>
     <Button BorderBrush="Transparent" Background="Transparent" Focusable="False">
        <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <i:InvokeCommandAction Command="{Binding DataContext.MyCommand, ElementName=ListViewName}" CommandParameter="{Binding}"/>
                </i:EventTrigger>
        </i:Interaction.Triggers>
      <Button.Template>
      <ControlTemplate>
         <Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
    ...

Python Socket Multiple Clients

Here is the example from the SocketServer documentation which would make an excellent starting point

import SocketServer

class MyTCPHandler(SocketServer.BaseRequestHandler):
    """
    The RequestHandler class for our server.

    It is instantiated once per connection to the server, and must
    override the handle() method to implement communication to the
    client.
    """

    def handle(self):
        # self.request is the TCP socket connected to the client
        self.data = self.request.recv(1024).strip()
        print "{} wrote:".format(self.client_address[0])
        print self.data
        # just send back the same data, but upper-cased
        self.request.sendall(self.data.upper())

if __name__ == "__main__":
    HOST, PORT = "localhost", 9999

    # Create the server, binding to localhost on port 9999
    server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)

    # Activate the server; this will keep running until you
    # interrupt the program with Ctrl-C
    server.serve_forever()

Try it from a terminal like this

$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Hello
HELLOConnection closed by foreign host.
$ telnet localhost 9999
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
Sausage
SAUSAGEConnection closed by foreign host.

You'll probably need to use A Forking or Threading Mixin too

Angular 2 Unit Tests: Cannot find name 'describe'

I'm up to the latest as of today and found the best way to resolve this is to do nothing...no typeRoots no types no exclude no include all the defaults seem to be working just fine. Actually it didn't work right for me until I removed them all. I had:

"exclude": [
    "node_modules"
]

but that's in the defaults so I removed that.

I had:

"types": [
    "node"
]

to get past some compiler warning. But now I removed that too.

The warning that shouldn't be is: error TS2304: Cannot find name 'AsyncIterable'. from node_modules\@types\graphql\subscription\subscribe.d.ts

which is very obnoxious so I did this in tsconfig so that it loads it:

"compilerOptions": {
    "target": "esnext",
}

since it's in the esnext set. I'm not using it directly so no worries here about compatibility just yet. Hope that doesn't burn me later.

How to configure SSL certificates with Charles Web Proxy and the latest Android Emulator on Windows?

These things helped me

  1. Go to proxy -> SSL proxy settings -> Add
  2. Add your site name here and give port number as 8888

enter image description here enter image description here

  1. Right click on your site name on the left panel and choose "Enable SSL Proxying" enter image description here

Hope this helps someone out there.

Frequency table for a single variable

You can use list comprehension on a dataframe to count frequencies of the columns as such

[my_series[c].value_counts() for c in list(my_series.select_dtypes(include=['O']).columns)]

Breakdown:

my_series.select_dtypes(include=['O']) 

Selects just the categorical data

list(my_series.select_dtypes(include=['O']).columns) 

Turns the columns from above into a list

[my_series[c].value_counts() for c in list(my_series.select_dtypes(include=['O']).columns)] 

Iterates through the list above and applies value_counts() to each of the columns

How do you sign a Certificate Signing Request with your Certification Authority?

In addition to answer of @jww, I would like to say that the configuration in openssl-ca.cnf,

default_days     = 1000         # How long to certify for

defines the default number of days the certificate signed by this root-ca will be valid. To set the validity of root-ca itself you should use '-days n' option in:

openssl req -x509 -days 3000 -config openssl-ca.cnf -newkey rsa:4096 -sha256 -nodes -out cacert.pem -outform PEM

Failing to do so, your root-ca will be valid for only the default one month and any certificate signed by this root CA will also have validity of one month.

Using Powershell to stop a service remotely without WMI or remoting

The output of Get-Service is a System.ServiceProcess.ServiceController .NET class that can operate on remote computers. How it accomplishes that, I don't know - probably DCOM or WMI. Once you've gotten one of these from Get-Service, it can be passed into Stop-Service which most likely just calls the Stop() method on this object. That stops the service on the remote machine. In fact, you could probably do this as well:

(get-service -ComputerName remotePC -Name Spooler).Stop()

How do I link to Google Maps with a particular longitude and latitude?

This schema has changed again (23rd October 2018). See Kushagr's answer for the latest.

This for a map with the marker (via aaronm's comment):

https://www.google.com/maps/?q=-15.623037,18.388672

For an older example (no marker on this one):

https://www.google.com/maps/preview/@-15.623037,18.388672,8z

The oldest format:

http://maps.google.com/maps?ll=-15.623037,18.388672&spn=65.61535,79.013672

How to easily initialize a list of Tuples?

Yes! This is possible.

The { } syntax of the collection initializer works on any IEnumerable type which has an Add method with the correct amount of arguments. Without bothering how that works under the covers, that means you can simply extend from List<T>, add a custom Add method to initialize your T, and you are done!

public class TupleList<T1, T2> : List<Tuple<T1, T2>>
{
    public void Add( T1 item, T2 item2 )
    {
        Add( new Tuple<T1, T2>( item, item2 ) );
    }
}

This allows you to do the following:

var groceryList = new TupleList<int, string>
{
    { 1, "kiwi" },
    { 5, "apples" },
    { 3, "potatoes" },
    { 1, "tomato" }
};

Select rows from a data frame based on values in a vector

Have a look at ?"%in%".

dt[dt$fct %in% vc,]
   fct X
1    a 2
3    c 3
5    c 5
7    a 7
9    c 9
10   a 1
12   c 2
14   c 4

You could also use ?is.element:

dt[is.element(dt$fct, vc),]

How to redirect to a different domain using NGINX?

If you would like to redirect requests for "domain1.com" to "domain2.com", you could create a server block that looks like this:

server {
    listen 80;
    server_name domain1.com;
    return 301 $scheme://domain2.com$request_uri;
}

Test if executable exists in Python?

You can try the external lib called "sh" (http://amoffat.github.io/sh/).

import sh
print sh.which('ls')  # prints '/bin/ls' depending on your setup
print sh.which('xxx') # prints None

Share data between html pages

possibly if you want to just transfer data to be used by JavaScript then you can use Hash Tags like this

http://localhost/project/index.html#exist

so once when you are done retriving the data show the message and change the window.location.hash to a suitable value.. now whenever you ll refresh the page the hashtag wont be present
NOTE: when you will use this instead ot query strings the data being sent cannot be retrived/read by the server

What is the best/simplest way to read in an XML file in Java application?

Depending on your application and the scope of the cfg file, a properties file might be the easiest. Sure it isn't as elegant as xml but it certainly easier.

How to use timeit module

I'll let you in on a secret: the best way to use timeit is on the command line.

On the command line, timeit does proper statistical analysis: it tells you how long the shortest run took. This is good because all error in timing is positive. So the shortest time has the least error in it. There's no way to get negative error because a computer can't ever compute faster than it can compute!

So, the command-line interface:

%~> python -m timeit "1 + 2"
10000000 loops, best of 3: 0.0468 usec per loop

That's quite simple, eh?

You can set stuff up:

%~> python -m timeit -s "x = range(10000)" "sum(x)"
1000 loops, best of 3: 543 usec per loop

which is useful, too!

If you want multiple lines, you can either use the shell's automatic continuation or use separate arguments:

%~> python -m timeit -s "x = range(10000)" -s "y = range(100)" "sum(x)" "min(y)"
1000 loops, best of 3: 554 usec per loop

That gives a setup of

x = range(1000)
y = range(100)

and times

sum(x)
min(y)

If you want to have longer scripts you might be tempted to move to timeit inside a Python script. I suggest avoiding that because the analysis and timing is simply better on the command line. Instead, I tend to make shell scripts:

 SETUP="

 ... # lots of stuff

 "

 echo Minmod arr1
 python -m timeit -s "$SETUP" "Minmod(arr1)"

 echo pure_minmod arr1
 python -m timeit -s "$SETUP" "pure_minmod(arr1)"

 echo better_minmod arr1
 python -m timeit -s "$SETUP" "better_minmod(arr1)"

 ... etc

This can take a bit longer due to the multiple initialisations, but normally that's not a big deal.


But what if you want to use timeit inside your module?

Well, the simple way is to do:

def function(...):
    ...

timeit.Timer(function).timeit(number=NUMBER)

and that gives you cumulative (not minimum!) time to run that number of times.

To get a good analysis, use .repeat and take the minimum:

min(timeit.Timer(function).repeat(repeat=REPEATS, number=NUMBER))

You should normally combine this with functools.partial instead of lambda: ... to lower overhead. Thus you could have something like:

from functools import partial

def to_time(items):
    ...

test_items = [1, 2, 3] * 100
times = timeit.Timer(partial(to_time, test_items)).repeat(3, 1000)

# Divide by the number of repeats
time_taken = min(times) / 1000

You can also do:

timeit.timeit("...", setup="from __main__ import ...", number=NUMBER)

which would give you something closer to the interface from the command-line, but in a much less cool manner. The "from __main__ import ..." lets you use code from your main module inside the artificial environment created by timeit.

It's worth noting that this is a convenience wrapper for Timer(...).timeit(...) and so isn't particularly good at timing. I personally far prefer using Timer(...).repeat(...) as I've shown above.


Warnings

There are a few caveats with timeit that hold everywhere.

  • Overhead is not accounted for. Say you want to time x += 1, to find out how long addition takes:

    >>> python -m timeit -s "x = 0" "x += 1"
    10000000 loops, best of 3: 0.0476 usec per loop
    

    Well, it's not 0.0476 µs. You only know that it's less than that. All error is positive.

    So try and find pure overhead:

    >>> python -m timeit -s "x = 0" ""      
    100000000 loops, best of 3: 0.014 usec per loop
    

    That's a good 30% overhead just from timing! This can massively skew relative timings. But you only really cared about the adding timings; the look-up timings for x also need to be included in overhead:

    >>> python -m timeit -s "x = 0" "x"
    100000000 loops, best of 3: 0.0166 usec per loop
    

    The difference isn't much larger, but it's there.

  • Mutating methods are dangerous.

    >>> python -m timeit -s "x = [0]*100000" "while x: x.pop()"
    10000000 loops, best of 3: 0.0436 usec per loop
    

    But that's completely wrong! x is the empty list after the first iteration. You'll need to reinitialize:

    >>> python -m timeit "x = [0]*100000" "while x: x.pop()"
    100 loops, best of 3: 9.79 msec per loop
    

    But then you have lots of overhead. Account for that separately.

    >>> python -m timeit "x = [0]*100000"                   
    1000 loops, best of 3: 261 usec per loop
    

    Note that subtracting the overhead is reasonable here only because the overhead is a small-ish fraction of the time.

    For your example, it's worth noting that both Insertion Sort and Tim Sort have completely unusual timing behaviours for already-sorted lists. This means you will require a random.shuffle between sorts if you want to avoid wrecking your timings.

How can I add a PHP page to WordPress?

You can name your file "newpage.php" - put it in your theme directory in wp-content. You can make it a page template (see http://codex.wordpress.org/Pages...) or you can include it in one of the PHP files in your theme, such as header.php or single.php.

Even better, create a child theme and put it in there, so you leave your theme code alone, and it's easier to update.

http://codex.wordpress.org/Pages#Creating_Your_Own_Page_Templates

How to load a resource bundle from a file resource in Java?

This works for me:

File f = new File("some.properties");
Properties props = new Properties();
FileInputStream fis = null;
try {
    fis = new FileInputStream(f);
    props.load(fis);
} catch (FileNotFoundException e) {
    e.printStackTrace();                    
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fis != null) {
        try {
            fis.close();
            fis = null;
        } catch (IOException e2) {
            e2.printStackTrace();
        }
    }
}           

How to select specific form element in jQuery?

although it is invalid html but you can use selector context to limit your selector in your case it would be like :

$("input[name='name']" , "#form2").val("Hello World! ");

http://api.jquery.com/jquery/#selector-context

Checking if a string can be converted to float in Python

If you don't need to worry about scientific or other expressions of numbers and are only working with strings that could be numbers with or without a period:

Function

def is_float(s):
    result = False
    if s.count(".") == 1:
        if s.replace(".", "").isdigit():
            result = True
    return result

Lambda version

is_float = lambda x: x.replace('.','',1).isdigit() and "." in x

Example

if is_float(some_string):
    some_string = float(some_string)
elif some_string.isdigit():
    some_string = int(some_string)
else:
    print "Does not convert to int or float."

This way you aren't accidentally converting what should be an int, into a float.

Setting session variable using javascript

It is very important to understand both sessionStorage and localStorage as they both have different uses:

From MDN:

All of your web storage data is contained within two object-like structures inside the browser: sessionStorage and localStorage. The first one persists data for as long as the browser is open (the data is lost when the browser is closed) and the second one persists data even after the browser is closed and then opened again.

sessionStorage - Saves data until the browser is closed, the data is deleted when the tab/browser is closed.

localStorage - Saves data "forever" even after the browser is closed BUT you shouldn't count on the data you store to be there later, the data might get deleted by the browser at any time because of pretty much anything, or deleted by the user, best practice would be to validate that the data is there first, and continue the rest if it is there. (or set it up again if its not there)

To understand more, read here: localStorage | sessionStorage

In Excel, sum all values in one column in each row where another column is a specific value

If column A contains the amounts to be reimbursed, and column B contains the "yes/no" indicating whether the reimbursement has been made, then either of the following will work, though the first option is recommended:

=SUMIF(B:B,"No",A:A)

or

=SUMIFS(A:A,B:B,"No")

Here is an example that will display the amounts paid and outstanding for a small set of sample data.

 A         B            C                   D
 Amount    Reimbursed?  Total Paid:         =SUMIF(B:B,"Yes",A:A)
 $100      Yes          Total Outstanding:  =SUMIF(B:B,"No",A:A)
 $200      No           
 $300      No
 $400      Yes
 $500      No

Result of Excel calculations

Find nearest latitude/longitude with an SQL query

It sounds like you want to do a nearest neighbour search with some bound on the distance. SQL does not support anything like this as far as I am aware and you would need to use an alternative data structure such as an R-tree or kd-tree.

Android Closing Activity Programmatically

finish() method is used to finish the activity and remove it from back stack. You can call it in any method in activity. But make sure you close all the Database connections, all reference variables null to prevent any memory leaks.

How to sum up an array of integers in C#

Using foreach would be shorter code, but probably do exactly the same steps at runtime after JIT optimization recognizes the comparison to Length in the for-loop controlling expression.

How to read file with space separated values in pandas

you can use regex as the delimiter:

pd.read_csv("whitespace.csv", header=None, delimiter=r"\s+")

C# "as" cast vs classic cast

The as operator is useful in a couple of circumstances.

  1. When you only need to know an object is of a specific type but don't need to specifically act on members of that type
  2. When you'd like to avoid exceptions and instead explicitly deal with null
  3. You want to know if there is a CLR conversion between the objects and not just some user defined conversion.

The 3rd point is subtle but important. There is not a 1-1 mapping between which casts will succeed with the cast operator and those which will succeed with the as operator. The as operator is strictly limited to CLR conversions and will not consider user defined conversions (the cast operator will).

Specifically the as operator only allows for the following (from section 7.9.11 of the C# lang spec)

  • An identity (§6.1.1), implicit reference (§6.1.6), boxing (§6.1.7), explicit reference (§6.2.4), or unboxing (§6.2.5) conversion exists from the type of E to T.
  • The type of E or T is an open type.
  • E is the null literal.

iTerm 2: How to set keyboard shortcuts to jump to beginning/end of line?

The only things that work for for moving to the beginning and end of line are

?? "SEND ESC SEQ" OH - to move to the beginning of line
?? "SEND ESC SEQ" OF - to move to the end of line

R: invalid multibyte string

I figured out Leafpad to be an adequate and simple text-editor to view and save/convert in certain character sets - at least in the linux-world.

I used this to save the Latin-15 to UTF-8 and it worked.

How to get the name of the current method from code

You can also use MethodBase.GetCurrentMethod() which will inhibit the JIT compiler from inlining the method where it's used.


Update:

This method contains a special enumeration StackCrawlMark that from my understanding will specify to the JIT compiler that the current method should not be inlined.

This is my interpretation of the comment associated to that enumeration present in SSCLI. The comment follows:

// declaring a local var of this enum type and passing it by ref into a function 
// that needs to do a stack crawl will both prevent inlining of the calle and 
// pass an ESP point to stack crawl to
// 
// Declaring these in EH clauses is illegal; 
// they must declared in the main method body

React: why child component doesn't update when prop changes

Because children do not rerender if the props of the parent change, but if its STATE changes :)

What you are showing is this: https://facebook.github.io/react/tips/communicate-between-components.html

It will pass data from parent to child through props but there is no rerender logic there.

You need to set some state to the parent then rerender the child on parent change state. This could help. https://facebook.github.io/react/tips/expose-component-functions.html

How to append binary data to a buffer in node.js

insert byte to specific place.

insertToArray(arr,index,item) {
   return Buffer.concat([arr.slice(0,index),Buffer.from(item,"utf-8"),arr.slice(index)]);
}

How do I get a plist as a Dictionary in Swift?

This is what I do if I want to convert a .plist to a Swift dictionary:

if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist") {
  if let dict = NSDictionary(contentsOfFile: path) as? Dictionary<String, AnyObject> {
    // use swift dictionary as normal
  }
}

Edited for Swift 2.0:

if let path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist"), dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
    // use swift dictionary as normal
}

Edited for Swift 3.0:

if let path = Bundle.main.path(forResource: "Config", ofType: "plist"), let dict = NSDictionary(contentsOfFile: path) as? [String: AnyObject] {
        // use swift dictionary as normal
}

Open directory using C

You should really post your code(a), but here goes. Start with something like:

    #include <stdio.h>
    #include <dirent.h>

    int main (int argc, char *argv[]) {
        struct dirent *pDirent;
        DIR *pDir;

        // Ensure correct argument count.

        if (argc != 2) {
            printf ("Usage: testprog <dirname>\n");
            return 1;
        }

        // Ensure we can open directory.

        pDir = opendir (argv[1]);
        if (pDir == NULL) {
            printf ("Cannot open directory '%s'\n", argv[1]);
            return 1;
        }

        // Process each entry.

        while ((pDirent = readdir(pDir)) != NULL) {
            printf ("[%s]\n", pDirent->d_name);
        }

        // Close directory and exit.

        closedir (pDir);
        return 0;
    }

You need to check in your case that args[1] is both set and refers to an actual directory. A sample run, with tmp is a subdirectory off my current directory but you can use any valid directory, gives me: testprog tmp

[.]
[..]
[file1.txt]
[file1_file1.txt]
[file2.avi]
[file2_file2.avi]
[file3.b.txt]
[file3_file3.b.txt]

Note also that you have to pass a directory in, not a file. When I execute:

testprog tmp/file1.txt

I get:

Cannot open directory 'tmp/file1.txt'

That's because it's a file rather than a directory (though, if you're sneaky, you can attempt to use diropen(dirname(argv[1])) if the initial diropen fails).


(a) This has now been rectified but, since this answer has been accepted, I'm going to assume it was the issue of whatever you were passing in.

SELECT *, COUNT(*) in SQLite

If what you want is the total number of records in the table appended to each row you can do something like

SELECT *
  FROM my_table
  CROSS JOIN (SELECT COUNT(*) AS COUNT_OF_RECS_IN_MY_TABLE
                FROM MY_TABLE)

How to create custom config section in app.config?

Import namespace :

using System.Configuration;

Create ConfigurationElement Company :

public class Company : ConfigurationElement
{

        [ConfigurationProperty("name", IsRequired = true)]
        public string Name
        {
            get
            {
                return this["name"] as string;
            }
        }
            [ConfigurationProperty("code", IsRequired = true)]
        public string Code
        {
            get
            {
                return this["code"] as string;
            }
        }
}

ConfigurationElementCollection:

public class Companies
        : ConfigurationElementCollection
    {
        public Company this[int index]
        {
            get
            {
                return base.BaseGet(index) as Company ;
            }
            set
            {
                if (base.BaseGet(index) != null)
                {
                    base.BaseRemoveAt(index);
                }
                this.BaseAdd(index, value);
            }
        }

       public new Company this[string responseString]
       {
            get { return (Company) BaseGet(responseString); }
            set
            {
                if(BaseGet(responseString) != null)
                {
                    BaseRemoveAt(BaseIndexOf(BaseGet(responseString)));
                }
                BaseAdd(value);
            }
        }

        protected override System.Configuration.ConfigurationElement CreateNewElement()
        {
            return new Company();
        }

        protected override object GetElementKey(System.Configuration.ConfigurationElement element)
        {
            return ((Company)element).Name;
        }
    }

and ConfigurationSection:

public class RegisterCompaniesConfig
        : ConfigurationSection
    {

        public static RegisterCompaniesConfig GetConfig()
        {
            return (RegisterCompaniesConfig)System.Configuration.ConfigurationManager.GetSection("RegisterCompanies") ?? new RegisterCompaniesConfig();
        }

        [System.Configuration.ConfigurationProperty("Companies")]
            [ConfigurationCollection(typeof(Companies), AddItemName = "Company")]
        public Companies Companies
        {
            get
            {
                object o = this["Companies"];
                return o as Companies ;
            }
        }

    }

and you must also register your new configuration section in web.config (app.config):

<configuration>       
    <configSections>
          <section name="Companies" type="blablabla.RegisterCompaniesConfig" ..>

then you load your config with

var config = RegisterCompaniesConfig.GetConfig();
foreach(var item in config.Companies)
{
   do something ..
}

How to use conditional breakpoint in Eclipse?

A way that might be more convenient: where you want a breakpoint, write a no-op if statement and set a breakpoint in its contents.

if(tablist[i].equalsIgnoreCase("LEADDELEGATES")) {
-->    int noop = 0; //don't do anything
}

(the breakpoint is represented by the arrow)

This way, the breakpoint only triggers if your condition is true. This could potentially be easier without that many pop-ups.

'dict' object has no attribute 'has_key'

has_key has been deprecated in Python 3.0. Alternatively you can use 'in'

graph={'A':['B','C'],
   'B':['C','D']}

print('A' in graph)
>> True

print('E' in graph)
>> False

How to append data to a json file?

I have some code which is similar, but does not rewrite the entire contents each time. This is meant to run periodically and append a JSON entry at the end of an array.

If the file doesn't exist yet, it creates it and dumps the JSON into an array. If the file has already been created, it goes to the end, replaces the ] with a , drops the new JSON object in, and then closes it up again with another ]

# Append JSON object to output file JSON array
fname = "somefile.txt"
if os.path.isfile(fname):
    # File exists
    with open(fname, 'a+') as outfile:
        outfile.seek(-1, os.SEEK_END)
        outfile.truncate()
        outfile.write(',')
        json.dump(data_dict, outfile)
        outfile.write(']')
else: 
    # Create file
    with open(fname, 'w') as outfile:
        array = []
        array.append(data_dict)
        json.dump(array, outfile)

How to pass parameters to a Script tag?

JQuery has a way to pass parameters from HTML to javascript:

Put this in the myhtml.html file:

<!-- Import javascript -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<!-- Invoke a different javascript file called subscript.js -->
<script id="myscript" src="subscript.js" video_filename="foobar.mp4">/script>

In the same directory make a subscript.js file and put this in there:

//Use jquery to look up the tag with the id of 'myscript' above.  Get 
//the attribute called video_filename, stuff it into variable filename.
var filename = $('#myscript').attr("video_filename");

//print filename out to screen.
document.write(filename);

Analyze Result:

Loading the myhtml.html page has 'foobar.mp4' print to screen. The variable called video_filename was passed from html to javascript. Javascript printed it to screen, and it appeared as embedded into the html in the parent.

jsfiddle proof that the above works:

http://jsfiddle.net/xqr77dLt/

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);
Response.BinaryWrite(fileContent);

And

<asp:LinkButton OnClientClick="openInNewTab();" OnClick="CodeBehindMethod".../>

In javaScript:

<script type="text/javascript">
    function openInNewTab() {
        window.document.forms[0].target = '_blank'; 
        setTimeout(function () { window.document.forms[0].target = ''; }, 0);
    }
</script>

Take care to reset target, otherwise all other calls like Response.Redirect will open in a new tab, which might be not what you want.

@Resource vs @Autowired

Both @Autowired (or @Inject) and @Resource work equally well. But there is a conceptual difference or a difference in the meaning

  • @Resource means get me a known resource by name. The name is extracted from the name of the annotated setter or field, or it is taken from the name-Parameter.
  • @Inject or @Autowired try to wire in a suitable other component by type.

So, basically these are two quite distinct concepts. Unfortunately the Spring-Implementation of @Resource has a built-in fallback, which kicks in when resolution by-name fails. In this case, it falls back to the @Autowired-kind resolution by-type. While this fallback is convenient, IMHO it causes a lot of confusion, because people are unaware of the conceptual difference and tend to use @Resource for type-based autowiring.

Box-Shadow on the left side of the element only

This question is very, very, very old, but as a trick in the future, I recommend something like this:

.element{
    box-shadow: 0px 0px 10px #232931;
}
.container{
    height: 100px;
    width: 100px;
    overflow: hidden;
}

Basically, you have a box shadow and then wrapping the element in a div with its overflow set to hidden. You'll need to adjust the height, width, and even padding of the div to only show the left box shadow, but it works. See here for an example If you look at the example, you can see how there's no other shadows, but only a black left shadow. Edit: this is a retake of the same screen shot, in case some one thinks that I just cropped out the right. You can find it here

How do I create a simple 'Hello World' module in Magento?

First and foremost, I highly recommend you buy the PDF/E-Book from PHP Architect. It's US$20, but is the only straightforward "Here's how Magento works" resource I've been able to find. I've also started writing Magento tutorials at my own website.

Second, if you have a choice, and aren't an experienced programmer or don't have access to an experienced programmer (ideally in PHP and Java), pick another cart. Magento is well engineered, but it was engineered to be a shopping cart solution that other programmers can build modules on top of. It was not engineered to be easily understood by people who are smart, but aren't programmers.

Third, Magento MVC is very different from the Ruby on Rails, Django, CodeIgniter, CakePHP, etc. MVC model that's popular with PHP developers these days. I think it's based on the Zend model, and the whole thing is very Java OOP-like. There's two controllers you need to be concerned about. The module/frontName controller, and then the MVC controller.

Fourth, the Magento application itself is built using the same module system you'll be using, so poking around the core code is a useful learning tactic. Also, a lot of what you'll be doing with Magento is overriding existing classes. What I'm covering here is creating new functionality, not overriding. Keep this in mind when you're looking at the code samples out there.

I'm going to start with your first question, showing you how to setup a controller/router to respond to a specific URL. This will be a small novel. I might have time later for the model/template related topics, but for now, I don't. I will, however, briefly speak to your SQL question.

Magento uses an EAV database architecture. Whenever possible, try to use the model objects the system provides to get the information you need. I know it's all there in the SQL tables, but it's best not to think of grabbing data using raw SQL queries, or you'll go mad.

Final disclaimer. I've been using Magento for about two or three weeks, so caveat emptor. This is an exercise to get this straight in my head as much as it is to help Stack Overflow.

Create a module

All additions and customizations to Magento are done through modules. So, the first thing you'll need to do is create a new module. Create an XML file in app/modules named as follows

cd /path/to/store/app
touch etc/modules/MyCompanyName_HelloWorld.xml
<?xml version="1.0"?>
<config>
     <modules>
        <MyCompanyName_HelloWorld>
            <active>true</active>
            <codePool>local</codePool>
        </MyCompanyName_HelloWorld>
     </modules>
</config>

MyCompanyName is a unique namespace for your modifications, it doesn't have to be your company's name, but that the recommended convention my magento. HelloWorld is the name of your module.

Clear the application cache

Now that the module file is in place, we'll need to let Magento know about it (and check our work). In the admin application

  1. Go to System->Cache Management
  2. Select Refresh from the All Cache menu
  3. Click Save Cache settings

Now, we make sure that Magento knows about the module

  1. Go to System->Configuration
  2. Click Advanced
  3. In the "Disable modules output" setting box, look for your new module named "MyCompanyName_HelloWorld"

If you can live with the performance slow down, you might want to turn off the application cache while developing/learning. Nothing is more frustrating then forgetting the clear out the cache and wondering why your changes aren't showing up.

Setup the directory structure

Next, we'll need to setup a directory structure for the module. You won't need all these directories, but there's no harm in setting them all up now.

mkdir -p app/code/local/MyCompanyName/HelloWorld/Block
mkdir -p app/code/local/MyCompanyName/HelloWorld/controllers
mkdir -p app/code/local/MyCompanyName/HelloWorld/Model
mkdir -p app/code/local/MyCompanyName/HelloWorld/Helper
mkdir -p app/code/local/MyCompanyName/HelloWorld/etc
mkdir -p app/code/local/MyCompanyName/HelloWorld/sql

And add a configuration file

touch app/code/local/MyCompanyName/HelloWorld/etc/config.xml

and inside the configuration file, add the following, which is essentially a "blank" configuration.

<?xml version="1.0"?>
<config>
    <modules>
        <MyCompanyName_HelloWorld>
            <version>0.1.0</version>
        </MyCompanyName_HelloWorld>
    </modules>
</config>

Oversimplifying things, this configuration file will let you tell Magento what code you want to run.

Setting up the router

Next, we need to setup the module's routers. This will let the system know that we're handling any URLs in the form of

http://example.com/magento/index.php/helloworld

So, in your configuration file, add the following section.

<config>
<!-- ... -->
    <frontend>
        <routers>
            <!-- the <helloworld> tagname appears to be arbitrary, but by
            convention is should match the frontName tag below-->
            <helloworld>
                <use>standard</use>
                <args>
                    <module>MyCompanyName_HelloWorld</module>
                    <frontName>helloworld</frontName>
                </args>
            </helloworld>
        </routers>
    </frontend>
<!-- ... -->
</config>

What you're saying here is "any URL with the frontName of helloworld ...

http://example.com/magento/index.php/helloworld

should use the frontName controller MyCompanyName_HelloWorld".

So, with the above configuration in place, when you load the helloworld page above, you'll get a 404 page. That's because we haven't created a file for our controller. Let's do that now.

touch app/code/local/MyCompanyName/HelloWorld/controllers/IndexController.php

Now try loading the page. Progress! Instead of a 404, you'll get a PHP/Magento exception

Controller file was loaded but class does not exist

So, open the file we just created, and paste in the following code. The name of the class needs to be based on the name you provided in your router.

<?php
class MyCompanyName_HelloWorld_IndexController extends Mage_Core_Controller_Front_Action{
    public function indexAction(){
        echo "We're echoing just to show that this is what's called, normally you'd have some kind of redirect going on here";
    }
}

What we've just setup is the module/frontName controller. This is the default controller and the default action of the module. If you want to add controllers or actions, you have to remember that the tree first part of a Magento URL are immutable they will always go this way http://example.com/magento/index.php/frontName/controllerName/actionName

So if you want to match this url

http://example.com/magento/index.php/helloworld/foo

You will have to have a FooController, which you can do this way :

touch app/code/local/MyCompanyName/HelloWorld/controllers/FooController.php
<?php
class MyCompanyName_HelloWorld_FooController extends Mage_Core_Controller_Front_Action{
    public function indexAction(){
        echo 'Foo Index Action';
    }

    public function addAction(){
        echo 'Foo add Action';
    }

    public function deleteAction(){
        echo 'Foo delete Action';
    }
}

Please note that the default controller IndexController and the default action indexAction can by implicit but have to be explicit if something come after it. So http://example.com/magento/index.php/helloworld/foo will match the controller FooController and the action indexAction and NOT the action fooAction of the IndexController. If you want to have a fooAction, in the controller IndexController you then have to call this controller explicitly like this way : http://example.com/magento/index.php/helloworld/index/foo because the second part of the url is and will always be the controllerName. This behaviour is an inheritance of the Zend Framework bundled in Magento.

You should now be able to hit the following URLs and see the results of your echo statements

http://example.com/magento/index.php/helloworld/foo
http://example.com/magento/index.php/helloworld/foo/add
http://example.com/magento/index.php/helloworld/foo/delete

So, that should give you a basic idea on how Magento dispatches to a controller. From here I'd recommended poking at the existing Magento controller classes to see how models and the template/layout system should be used.

Logo image and H1 heading on the same line

Try this:

<img style="display: inline;" src="img/logo.png" alt="logo" />
<h1 style="display: inline;">My website name</h1>

Center Align on a Absolutely Positioned Div

I was having the same issue, and my limitation was that i cannot have a predefined width. If your element does not have a fixed width, then try this

div#thing 
{ 
  position: absolute; 
  top: 0px; 
  z-index: 2; 
  left:0;
  right:0;
 }

div#thing-body
{
  text-align:center;
}

then modify your html to look like this

<div id="thing">
 <div id="thing-child">
  <p>text text text with no fixed size, variable font</p>
 </div>
</div>

postgresql - replace all instances of a string within text field

Here is an example that replaces all instances of 1 or more white space characters in a column with an underscore using regular expression -

select distinct on (pd)
regexp_replace(rndc.pd, '\\s+', '_','g') as pd
from rndc14_ndc_mstr rndc;

Refresh image with a new one at the same url

Try adding a cachebreaker at the end of the url:

newImage.src = "http://localhost/image.jpg?" + new Date().getTime();

This will append the current timestamp automatically when you are creating the image, and it will make the browser look again for the image instead of retrieving the one in the cache.

ggplot with 2 y axes on each side and different scales

There are common use-cases dual y axes, e.g., the climatograph showing monthly temperature and precipitation. Here is a simple solution, generalized from Megatron's solution by allowing you to set the lower limit of the variables to something else than zero:

Example data:

climate <- tibble(
  Month = 1:12,
  Temp = c(-4,-4,0,5,11,15,16,15,11,6,1,-3),
  Precip = c(49,36,47,41,53,65,81,89,90,84,73,55)
  )

Set the following two values to values close to the limits of the data (you can play around with these to adjust the positions of the graphs; the axes will still be correct):

ylim.prim <- c(0, 180)   # in this example, precipitation
ylim.sec <- c(-4, 18)    # in this example, temperature

The following makes the necessary calculations based on these limits, and makes the plot itself:

b <- diff(ylim.prim)/diff(ylim.sec)
a <- ylim.prim[1] - b*ylim.sec[1]) # there was a bug here

ggplot(climate, aes(Month, Precip)) +
  geom_col() +
  geom_line(aes(y = a + Temp*b), color = "red") +
  scale_y_continuous("Precipitation", sec.axis = sec_axis(~ (. - a)/b, name = "Temperature")) +
  scale_x_continuous("Month", breaks = 1:12) +
  ggtitle("Climatogram for Oslo (1961-1990)")  

Climatogram showing temperature as line and precipitation as barplot

If you want to make sure that the red line corresponds to the right-hand y axis, you can add a theme sentence to the code:

ggplot(climate, aes(Month, Precip)) +
  geom_col() +
  geom_line(aes(y = a + Temp*b), color = "red") +
  scale_y_continuous("Precipitation", sec.axis = sec_axis(~ (. - a)/b, name = "Temperature")) +
  scale_x_continuous("Month", breaks = 1:12) +
  theme(axis.line.y.right = element_line(color = "red"), 
        axis.ticks.y.right = element_line(color = "red"),
        axis.text.y.right = element_text(color = "red"), 
        axis.title.y.right = element_text(color = "red")
        ) +
  ggtitle("Climatogram for Oslo (1961-1990)")

which colors the right-hand axis:

Climatogram with red right-hand axis

How to update MySql timestamp column to current timestamp on PHP?

Use this query:

UPDATE `table` SET date_date=now();

Sample code can be:

<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("my_db", $con);

mysql_query("UPDATE `table` SET date_date=now()");

mysql_close($con);
?>

Redirect in Spring MVC

try to change this in your dispatcher-servlet.xml

<!-- Your View Resolver -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.ResourceBundleViewResolver">
    <property name="basenames" value="views" />
    <property name="order" value="1" />
</bean>   
<!-- UrlBasedViewResolver to Handle Redirects & Forward -->
<bean id="urlViewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver">
    <property name="viewClass" value="org.springframework.web.servlet.view.tiles2.TilesView" />
    <property name="order" value="2" />
</bean>        

What happens is clearly explained here http://projects.nigelsim.org/wiki/RedirectWithSpringWebMvc

How to compile a 32-bit binary on a 64-bit linux machine with gcc/cmake

For any complex application, I suggest to use an lxc container. lxc containers are 'something in the middle between a chroot on steroids and a full fledged virtual machine'.

For example, here's a way to build 32-bit wine using lxc on an Ubuntu Trusty system:

sudo apt-get install lxc lxc-templates
sudo lxc-create -t ubuntu -n my32bitbox -- --bindhome $LOGNAME -a i386 --release trusty
sudo lxc-start -n my32bitbox
# login as yourself
sudo sh -c "sed s/deb/deb-src/ /etc/apt/sources.list >> /etc/apt/sources.list"
sudo apt-get install devscripts
sudo apt-get build-dep wine1.7
apt-get source wine1.7
cd wine1.7-*
debuild -eDEB_BUILD_OPTIONS="parallel=8" -i -us -uc -b
shutdown -h now   # to exit the container

Here is the wiki page about how to build 32-bit wine on a 64-bit host using lxc.

How to print VARCHAR(MAX) using Print Statement?

Here's another version. This one extracts each substring to print from the main string instead of taking reducing the main string by 4000 on each loop (which might create a lot of very long strings under the hood - not sure).

CREATE PROCEDURE [Internal].[LongPrint]
    @msg nvarchar(max)
AS
BEGIN

    -- SET NOCOUNT ON reduces network overhead
    SET NOCOUNT ON;

    DECLARE @MsgLen int;
    DECLARE @CurrLineStartIdx int = 1;
    DECLARE @CurrLineEndIdx int;
    DECLARE @CurrLineLen int;   
    DECLARE @SkipCount int;

    -- Normalise line end characters.
    SET @msg = REPLACE(@msg, char(13) + char(10), char(10));
    SET @msg = REPLACE(@msg, char(13), char(10));

    -- Store length of the normalised string.
    SET @MsgLen = LEN(@msg);        

    -- Special case: Empty string.
    IF @MsgLen = 0
    BEGIN
        PRINT '';
        RETURN;
    END

    -- Find the end of next substring to print.
    SET @CurrLineEndIdx = CHARINDEX(CHAR(10), @msg);
    IF @CurrLineEndIdx BETWEEN 1 AND 4000
    BEGIN
        SET @CurrLineEndIdx = @CurrLineEndIdx - 1
        SET @SkipCount = 2;
    END
    ELSE
    BEGIN
        SET @CurrLineEndIdx = 4000;
        SET @SkipCount = 1;
    END     

    -- Loop: Print current substring, identify next substring (a do-while pattern is preferable but TSQL doesn't have one).
    WHILE @CurrLineStartIdx < @MsgLen
    BEGIN
        -- Print substring.
        PRINT SUBSTRING(@msg, @CurrLineStartIdx, (@CurrLineEndIdx - @CurrLineStartIdx)+1);

        -- Move to start of next substring.
        SET @CurrLineStartIdx = @CurrLineEndIdx + @SkipCount;

        -- Find the end of next substring to print.
        SET @CurrLineEndIdx = CHARINDEX(CHAR(10), @msg, @CurrLineStartIdx);
        SET @CurrLineLen = @CurrLineEndIdx - @CurrLineStartIdx;

        -- Find bounds of next substring to print.              
        IF @CurrLineLen BETWEEN 1 AND 4000
        BEGIN
            SET @CurrLineEndIdx = @CurrLineEndIdx - 1
            SET @SkipCount = 2;
        END
        ELSE
        BEGIN
            SET @CurrLineEndIdx = @CurrLineStartIdx + 4000;
            SET @SkipCount = 1;
        END
    END
END

How to increase Bootstrap Modal Width?

If you want to keep the modal responsive use % of width instead of pixels. You can do it in-line (see below) or with CSS.

<div class="modal fade" id="phpModal" role="dialog">
            <div class="modal-dialog modal-lg" style="width:80%;">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title">HERE YOU TITLE</h4>
                    </div>
                    <div class="modal-body helpModal phpModal">
                        HERE YOUR CONTENT
                    </div>
                </div>
            </div>
        </div>

If you use CSS, you can even do different % for modal-sm and modal-lg.

Filter output in logcat by tagname

use this:

adb logcat -s "TAGNAME"

How can I set the default value for an HTML <select> element?

I myself use it

<select selected=''>
    <option value=''></option>
    <option value='1'>ccc</option>
    <option value='2'>xxx</option>
    <option value='3'>zzz</option>
    <option value='4'>aaa</option>
    <option value='5'>qqq</option>
    <option value='6'>wwww</option>
</select>

Undefined symbols for architecture armv7

I had this warning, when wrote two classes in .h file of another class, but FORGOT to write the implementation for this classes in .m file.

How to find column names for all tables in all databases in SQL Server

Some minor improvements

->previous answers weren't showing all results

->possible to filter on column name by setting the column name variable

DECLARE @columnname nvarchar(150)
SET @columnname=''

DECLARE @SQL varchar(max)
SET @SQL=''
SELECT @SQL=@SQL+'UNION
select 
'''+d.name+'.''+sh.name+''.''+o.name COLLATE SQL_Latin1_General_CP1_CI_AS as name,c.name COLLATE SQL_Latin1_General_CP1_CI_AS as columnname,c.column_id
from '+d.name+'.sys.columns            c
    inner join '+d.name+'.sys.objects  o on c.object_id=o.object_id
    INNER JOIN '+d.name+'.sys.schemas  sh on o.schema_id=sh.schema_id
    where c.name like ''%'+@columnname+'%'' and sh.name<>''sys'' 
'
FROM sys.databases d
SELECT @SQL=RIGHT(@SQL,LEN(@SQL)-5)+'order by 1,3'
--print @SQL
EXEC (@SQL)

Insert results of a stored procedure into a temporary table

If you let dynamic SQL create a temp table, this table is owned by the Dynamic SQL connection, as opposed to the connection your stored procedure is called from.

DECLARE @COMMA_SEPARATED_KEYS varchar(MAX);
DROP TABLE IF EXISTS KV;
CREATE TABLE KV (id_person int, mykey varchar(30), myvalue int);
INSERT INTO KV VALUES
(1, 'age', 16),
(1, 'weight', 63),
(1, 'height', 175),
(2, 'age', 26),
(2, 'weight', 83),
(2, 'height', 185);
WITH cte(mykey) AS (
    SELECT DISTINCT mykey FROM KV
) 
SELECT @COMMA_SEPARATED_KEYS=STRING_AGG(mykey,',') FROM cte;
SELECT @COMMA_SEPARATED_KEYS AS keys;

enter image description here

DECLARE @ExecuteExpression varchar(MAX);

DROP TABLE IF EXISTS #Pivoted;

SET @ExecuteExpression = N'
SELECT * 
INTO #Pivoted
FROM
(
    SELECT
        mykey,
        myvalue,
        id_person
    FROM KV
) AS t
PIVOT(
    MAX(t.myvalue) 
    FOR mykey IN (COMMA_SEPARATED_KEYS)
) AS pivot_table;
';

SET @ExecuteExpression = REPLACE(@ExecuteExpression, 'COMMA_SEPARATED_KEYS', @COMMA_SEPARATED_KEYS);

EXEC(@ExecuteExpression);

SELECT * FROM #Pivoted;

Msg 208, Level 16, State 0 Invalid object name '#Pivoted'. This is because #Pivoted is owned by the Dynamic SQL connection. So the last instruction

SELECT * FROM #Pivoted

fails.

One way to not face this issue is to make sure all references to #Pivoted are made from inside the dynamic query itself:

DECLARE @COMMA_SEPARATED_KEYS varchar(MAX);
DROP TABLE IF EXISTS KV;
CREATE TABLE KV (id_person int, mykey varchar(30), myvalue int);
INSERT INTO KV VALUES
(1, 'age', 16),
(1, 'weight', 63),
(1, 'height', 175),
(2, 'age', 26),
(2, 'weight', 83),
(2, 'height', 185);
WITH cte(mykey) AS (
    SELECT DISTINCT mykey FROM KV
) 
SELECT @COMMA_SEPARATED_KEYS=STRING_AGG(mykey,',') FROM cte;
SELECT @COMMA_SEPARATED_KEYS AS keys;


DECLARE @ExecuteExpression varchar(MAX);

DROP TABLE IF EXISTS #Pivoted;

SET @ExecuteExpression = N'
SELECT * 
INTO #Pivoted
FROM
(
    SELECT
        mykey,
        myvalue,
        id_person
    FROM KV
) AS t
PIVOT(
    MAX(t.myvalue) 
    FOR mykey IN (COMMA_SEPARATED_KEYS)
) AS pivot_table;
SELECT * FROM #Pivoted;
';

SET @ExecuteExpression = REPLACE(@ExecuteExpression, 'COMMA_SEPARATED_KEYS', @COMMA_SEPARATED_KEYS);

EXEC(@ExecuteExpression);

enter image description here

Content Type application/soap+xml; charset=utf-8 was not supported by service

As suggested by others this happens due to service client mismatch.

I ran into the same problem, when was debugging got to know that there is a mismatch in the binding. Instead of WSHTTPBinding I was referring to BasicHttpBinding. In my case I am referring both BasicHttp and WsHttp. I was dynamically assigning the binding based on the reference. So check your service constructor as shown below

Refer this image

How can I selectively escape percent (%) in Python strings?

Alternatively, as of Python 2.6, you can use new string formatting (described in PEP 3101):

'Print percent % in sentence and not {0}'.format(test)

which is especially handy as your strings get more complicated.

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

For me it worked like the code below. I made a difference between RouterModule.forRoot and RouterModule.forChild. Then in the child define the parent path and in the children array the childs.

parent-routing.module.ts

RouterModule.forRoot([
  {
    path: 'parent',  //parent path, define the component that you imported earlier..
    component: ParentComponent,
  }
]),
RouterModule.forChild([
  {
    path: 'parent', //parent path
    children: [
      {
        path: '', 
        redirectTo: '/parent/childs', //full child path
        pathMatch: 'full'
      },
      {
        path: 'childs', 
        component: ParentChildsComponent,
      },
    ]
  }
])

Hope this helps.

Eclipse Error: "Failed to connect to remote VM"

Have you setup the remote VM to accept connections?

java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=10000,suspend=n yourServer

Is there a firewall in the way?

Are you specifying the correct host / port?

Are you connected to a VPN?

How to use cURL to get jSON data and decode the data?

I think this one will answer your question :P

$url="https://.../api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=??desc&limit=1&grab_content&content_limit=1";

Using cURL

//  Initiate curl
$ch = curl_init();
// Will return the response, if false it print the response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Set the url
curl_setopt($ch, CURLOPT_URL,$url);
// Execute
$result=curl_exec($ch);
// Closing
curl_close($ch);

// Will dump a beauty json :3
var_dump(json_decode($result, true));

Using file_get_contents

$result = file_get_contents($url);
// Will dump a beauty json :3
var_dump(json_decode($result, true));

Accessing

$array["threads"][13/* thread id */]["title"/* thread key */]

And

$array["threads"][13/* thread id */]["content"/* thread key */]["content"][23/* post id */]["message" /* content key */];

Number of times a particular character appears in a string

You can do that using replace and len.

Count number of x characters in str:

len(str) - len(replace(str, 'x', ''))

jQuery Popup Bubble/Tooltip

Although qTip (the accepted answer) is good, I started using it, and it lacked some features I needed.

I then stumbled upon PoshyTip - it is very flexible, and really easy to use. (And I could do what I needed)

POST data in JSON format

Here is an example using jQuery...

 <head>
   <title>Test</title>
   <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
   <script type="text/javascript" src="http://www.json.org/json2.js"></script>
   <script type="text/javascript">
     $(function() {
       var frm = $(document.myform);
       var dat = JSON.stringify(frm.serializeArray());

       alert("I am about to POST this:\n\n" + dat);

       $.post(
         frm.attr("action"),
         dat,
         function(data) {
           alert("Response: " + data);
         }
       );
     });
   </script>
</head>

The jQuery serializeArray function creates a Javascript object with the form values. Then you can use JSON.stringify to convert that into a string, if needed. And you can remove your body onload, too.

How to convert a string to integer in C?

Robust C89 strtol-based solution

With:

  • no undefined behavior (as could be had with the atoi family)
  • a stricter definition of integer than strtol (e.g. no leading whitespace nor trailing trash chars)
  • classification of the error case (e.g. to give useful error messages to users)
  • a "testsuite"
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

typedef enum {
    STR2INT_SUCCESS,
    STR2INT_OVERFLOW,
    STR2INT_UNDERFLOW,
    STR2INT_INCONVERTIBLE
} str2int_errno;

/* Convert string s to int out.
 *
 * @param[out] out The converted int. Cannot be NULL.
 *
 * @param[in] s Input string to be converted.
 *
 *     The format is the same as strtol,
 *     except that the following are inconvertible:
 *
 *     - empty string
 *     - leading whitespace
 *     - any trailing characters that are not part of the number
 *
 *     Cannot be NULL.
 *
 * @param[in] base Base to interpret string in. Same range as strtol (2 to 36).
 *
 * @return Indicates if the operation succeeded, or why it failed.
 */
str2int_errno str2int(int *out, char *s, int base) {
    char *end;
    if (s[0] == '\0' || isspace(s[0]))
        return STR2INT_INCONVERTIBLE;
    errno = 0;
    long l = strtol(s, &end, base);
    /* Both checks are needed because INT_MAX == LONG_MAX is possible. */
    if (l > INT_MAX || (errno == ERANGE && l == LONG_MAX))
        return STR2INT_OVERFLOW;
    if (l < INT_MIN || (errno == ERANGE && l == LONG_MIN))
        return STR2INT_UNDERFLOW;
    if (*end != '\0')
        return STR2INT_INCONVERTIBLE;
    *out = l;
    return STR2INT_SUCCESS;
}

int main(void) {
    int i;
    /* Lazy to calculate this size properly. */
    char s[256];

    /* Simple case. */
    assert(str2int(&i, "11", 10) == STR2INT_SUCCESS);
    assert(i == 11);

    /* Negative number . */
    assert(str2int(&i, "-11", 10) == STR2INT_SUCCESS);
    assert(i == -11);

    /* Different base. */
    assert(str2int(&i, "11", 16) == STR2INT_SUCCESS);
    assert(i == 17);

    /* 0 */
    assert(str2int(&i, "0", 10) == STR2INT_SUCCESS);
    assert(i == 0);

    /* INT_MAX. */
    sprintf(s, "%d", INT_MAX);
    assert(str2int(&i, s, 10) == STR2INT_SUCCESS);
    assert(i == INT_MAX);

    /* INT_MIN. */
    sprintf(s, "%d", INT_MIN);
    assert(str2int(&i, s, 10) == STR2INT_SUCCESS);
    assert(i == INT_MIN);

    /* Leading and trailing space. */
    assert(str2int(&i, " 1", 10) == STR2INT_INCONVERTIBLE);
    assert(str2int(&i, "1 ", 10) == STR2INT_INCONVERTIBLE);

    /* Trash characters. */
    assert(str2int(&i, "a10", 10) == STR2INT_INCONVERTIBLE);
    assert(str2int(&i, "10a", 10) == STR2INT_INCONVERTIBLE);

    /* int overflow.
     *
     * `if` needed to avoid undefined behaviour
     * on `INT_MAX + 1` if INT_MAX == LONG_MAX.
     */
    if (INT_MAX < LONG_MAX) {
        sprintf(s, "%ld", (long int)INT_MAX + 1L);
        assert(str2int(&i, s, 10) == STR2INT_OVERFLOW);
    }

    /* int underflow */
    if (LONG_MIN < INT_MIN) {
        sprintf(s, "%ld", (long int)INT_MIN - 1L);
        assert(str2int(&i, s, 10) == STR2INT_UNDERFLOW);
    }

    /* long overflow */
    sprintf(s, "%ld0", LONG_MAX);
    assert(str2int(&i, s, 10) == STR2INT_OVERFLOW);

    /* long underflow */
    sprintf(s, "%ld0", LONG_MIN);
    assert(str2int(&i, s, 10) == STR2INT_UNDERFLOW);

    return EXIT_SUCCESS;
}

GitHub upstream.

Based on: https://stackoverflow.com/a/6154614/895245

Validating with an XML schema in Python

You can easily validate an XML file or tree against an XML Schema (XSD) with the xmlschema Python package. It's pure Python, available on PyPi and doesn't have many dependencies.

Example - validate a file:

import xmlschema
xmlschema.validate('doc.xml', 'some.xsd')

The method raises an exception if the file doesn't validate against the XSD. That exception then contains some violation details.

If you want to validate many files you only have to load the XSD once:

xsd = xmlschema.XMLSchema('some.xsd')
for filename in filenames:
    xsd.validate(filename)

If you don't need the exception you can validate like this:

if xsd.is_valid('doc.xml'):
    print('do something useful')

Alternatively, xmlschema directly works on file objects and in memory XML trees (either created with xml.etree.ElementTree or lxml). Example:

import xml.etree.ElementTree as ET
t = ET.parse('doc.xml')
result = xsd.is_valid(t)
print('Document is valid? {}'.format(result))

Error Importing SSL certificate : Not an X.509 Certificate

This seems like an old thread, but I'll add my experience here. I tried to install a cert as well and got that error. I then opened the cer file with a txt editor, and noticed that there is an extra space (character) at the end of each line. Removing those lines allowed me to import the cert.

Hope this is worth something to someone else.

Number input type that takes only integers?

Pattern is nice but if you want to restrict the input to numbers only with type="text", you can use oninput and a regex as below:

<input type="text" oninput="this.value=this.value.replace(/[^0-9]/g,'');" id="myId"/>

I warks for me :)

How can I get list of values from dict?

Yes it's the exact same thing in Python 2:

d.values()

In Python 3 (where dict.values returns a view of the dictionary’s values instead):

list(d.values())

Adding IN clause List to a JPA Query

The proper JPA query format would be:

el.name IN :inclList

If you're using an older version of Hibernate as your provider you have to write:

el.name IN (:inclList)

but that is a bug (HHH-5126) (EDIT: which has been resolved by now).

Python loop for inside lambda

Just in case, if someone is looking for a similar problem...

Most solutions given here are one line and are quite readable and simple. Just wanted to add one more that does not need the use of lambda(I am assuming that you are trying to use lambda just for the sake of making it a one line code). Instead, you can use a simple list comprehension.

[print(i) for i in x]

BTW, the return values will be a list on None s.

java.lang.OutOfMemoryError: Java heap space in Maven

To temporarily work around this problem, I found the following to be the quickest way:

export JAVA_TOOL_OPTIONS="-Xmx1024m -Xms1024m"

kill a process in bash

Please check "top" command then if your script or any are running please note 'PID'

PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
 1384 root      20   0  514m  32m 2188 S  0.3  5.4  55:09.88 example
14490 root      20   0 15140 1216  920 R  0.3  0.2   0:00.02 example2



kill <you process ID>

Example : kill 1384

Nginx not picking up site in sites-enabled?

Changing from:

include /etc/nginx/sites-enabled/*; 

to

include /etc/nginx/sites-enabled/*.*; 

fixed my issue

Iframe positioning

you should use position: relative; for one iframe and position:absolute; for the second;

Example: for first iframe use:

<div id="contentframe" style="position:relative; top: 100px; left: 50px;">

for second iframe use:

<div id="contentframe" style="position:absolute; top: 0px; left: 690px;">

How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?

As Jake points out, TARGET_IPHONE_SIMULATOR is a subset of TARGET_OS_IPHONE.

Also, TARGET_OS_IPHONE is a subset of TARGET_OS_MAC.

So a better approach might be:

#ifdef _WIN64
   //define something for Windows (64-bit)
#elif _WIN32
   //define something for Windows (32-bit)
#elif __APPLE__
    #include "TargetConditionals.h"
    #if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
        // define something for simulator   
    #elif TARGET_OS_IPHONE
        // define something for iphone  
    #else
        #define TARGET_OS_OSX 1
        // define something for OSX
    #endif
#elif __linux
    // linux
#elif __unix // all unices not caught above
    // Unix
#elif __posix
    // POSIX
#endif

Read whole ASCII file into C++ std::string

I don't think you can do this without an explicit or implicit loop, without reading into a char array (or some other container) first and ten constructing the string. If you don't need the other capabilities of a string, it could be done with vector<char> the same way you are currently using a char *.

How do you build a Singleton in Dart?

Thanks to Dart's factory constructors, it's easy to build a singleton:

class Singleton {
  static final Singleton _singleton = Singleton._internal();

  factory Singleton() {
    return _singleton;
  }

  Singleton._internal();
}

You can construct it like this

main() {
  var s1 = Singleton();
  var s2 = Singleton();
  print(identical(s1, s2));  // true
  print(s1 == s2);           // true
}

NSUserDefaults - How to tell if a key exists

"objectForKey will return nil if it doesn't exist." It will also return nil if it does exist and it is either an integer or a boolean with a value of zero (i.e. FALSE or NO for the boolean).

I've tested this in the simulator for both 5.1 and 6.1. This means that you cannot really test for either integers or booleans having been set by asking for "the object". You can get away with this for integers if you don't mind treating "not set" as if it were "set to zero".

The people who already tested this appear to have been fooled by the false negative aspect, i.e. testing this by seeing if objectForKey returns nil when you know the key hasn't been set but failing to notice that it also returns nil if the key has been set but has been set to NO.

For my own problem, that sent me here, I just ended up changing the semantics of my boolean so that my desired default was in congruence with the value being set to NO. If that's not an option, you'll need to store as something other than a boolean and make sure that you can tell the difference between YES, NO, and "not set."

Custom date format with jQuery validation plugin

Jon, you have some syntax errors, see below, this worked for me.

  <script type="text/javascript">
$(document).ready(function () {

  $.validator.addMethod(
      "australianDate",
      function (value, element) {
        // put your own logic here, this is just a (crappy) example 
        return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
      },
      "Please enter a date in the format dd/mm/yyyy"
    );

  $('#testForm').validate({
    rules: {
      "myDate": {
        australianDate: true
      }
    }
  });

});             

What is the use of BindingResult interface in spring MVC?

From the official Spring documentation:

General interface that represents binding results. Extends the interface for error registration capabilities, allowing for a Validator to be applied, and adds binding-specific analysis and model building.

Serves as result holder for a DataBinder, obtained via the DataBinder.getBindingResult() method. BindingResult implementations can also be used directly, for example to invoke a Validator on it (e.g. as part of a unit test).

Table is marked as crashed and should be repaired

Connect to your server via SSH

then connect to your mysql console

and

USE user_base
REPAIR TABLE TABLE;

-OR-

If there are a lot of broken tables in current database:

mysqlcheck -uUSER -pPASSWORD  --repair --extended user_base

If there are a lot of broken tables in a lot of databases:

mysqlcheck -uUSER -pPASSWORD  --repair --extended -A

Graph implementation C++

This question is ancient but for some reason I can't seem to get it out of my mind.

While all of the solutions do provide an implementation of graphs, they are also all very verbose. They are simply not elegant.

Instead of inventing your own graph class all you really need is a way to tell that one point is connected to another -- for that, std::map and std::unordered_map work perfectly fine. Simply, define a graph as a map between nodes and lists of edges. If you don't need extra data on the edge, a list of end nodes will do just fine.

Thus a succinct graph in C++, could be implemented like so:

using graph = std::map<int, std::vector<int>>;

Or, if you need additional data,

struct edge {
    int nodes[2];
    float cost; // add more if you need it
};

using graph = std::map<int, std::vector<edge>>;

Now your graph structure will plug nicely into the rest of the language and you don't have to remember any new clunky interface -- the old clunky interface will do just fine.

No benchmarks, but I have a feeling this will also outperform the other suggestions here.

NB: the ints are not indices -- they are identifiers.

Split a vector into chunks

Here's another variant.

NOTE: with this sample you're specifying the CHUNK SIZE in the second parameter

  1. all chunks are uniform, except for the last;
  2. the last will at worst be smaller, never bigger than the chunk size.

chunk <- function(x,n)
{
    f <- sort(rep(1:(trunc(length(x)/n)+1),n))[1:length(x)]
    return(split(x,f))
}

#Test
n<-c(1,2,3,4,5,6,7,8,9,10,11)

c<-chunk(n,5)

q<-lapply(c, function(r) cat(r,sep=",",collapse="|") )
#output
1,2,3,4,5,|6,7,8,9,10,|11,|

Best timing method in C?

gettimeofday will return time accurate to microseconds within the resolution of the system clock. You might also want to check out the High Res Timers project on SourceForge.

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

How to search file text for a pattern and replace it with a given value

This works for me:

filename = "foo"
text = File.read(filename) 
content = text.gsub(/search_regexp/, "replacestring")
File.open(filename, "w") { |file| file << content }

JavaScript dictionary with names

Another approach would be to have an array of objects, with each individual object holding the properties of a column. This slightly changes the structure of "myMappings", but makes it easy to work with:

var myMappings = [
    { title: "Name", width: "10%" },
    { title: "Phone", width: "10%" },
    { title: "Address", width: "50%" },
    { title: "Zip", width: "10%" },
    { title: "Comments", width: "20%" }
];

Then you could easily iterate through all your "columns" with a for loop:

for (var i = 0; i < myMappings.length; i += 1) {
    // myMappings[i].title ...
    // myMappings[i].width ...
}

Invoking modal window in AngularJS Bootstrap UI using JavaScript

Different version similar to the one offered by Maxim Shoustin

I liked the answer but the part that bothered me was the use of <script id="..."> as a container for the modal's template.

I wanted to place the modal's template in a hidden <div> and bind the inner html with a scope variable called modal_html_template mainly because i think it more correct (and more comfortable to process in WebStorm/PyCharm) to place the template's html inside a <div> instead of <script id="...">

this variable will be used when calling $modal({... 'template': $scope.modal_html_template, ...})

in order to bind the inner html, i created inner-html-bind which is a simple directive

check out the example plunker

<div ng-controller="ModalDemoCtrl">

    <div inner-html-bind inner-html="modal_html_template" class="hidden">
        <div class="modal-header">
            <h3>I'm a modal!</h3>
        </div>
        <div class="modal-body">
            <ul>
                <li ng-repeat="item in items">
                    <a ng-click="selected.item = item">{{ item }}</a>
                </li>
            </ul>
            Selected: <b>{{ selected.item }}</b>
        </div>
        <div class="modal-footer">
            <button class="btn btn-primary" ng-click="ok()">OK</button>
            <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
        </div>
    </div>

    <button class="btn" ng-click="open()">Open me!</button>
    <div ng-show="selected">Selection from a modal: {{ selected }}</div>
</div>

inner-html-bind directive:

app.directive('innerHtmlBind', function() {
  return {
    restrict: 'A',
    scope: {
      inner_html: '=innerHtml'
    },
    link: function(scope, element, attrs) {
      scope.inner_html = element.html();
    }
  }
});

iOS: set font size of UILabel Programmatically

Try [UIFont systemFontOfSize:36] or [UIFont fontWithName:@"HelveticaNeue" size:36] i.e. [[self titleLabel] setFont:[UIFont systemFontOfSize:36]];

Convert a List<T> into an ObservableCollection<T>

The Observable Collection constructor will take an IList or an IEnumerable.

If you find that you are going to do this a lot you can make a simple extension method:

    public static ObservableCollection<T> ToObservableCollection<T>(this IEnumerable<T> enumerable)
    {
        return new ObservableCollection<T>(enumerable);
    }

Postgresql column reference "id" is ambiguous

SELECT vg.id, 
       vg.name
  FROM v_groups vg INNER JOIN  
       people2v_groups p2vg ON vg.id = p2vg.v_group_id
 WHERE p2vg.people_id = 0;