Programs & Examples On #Inkscape

Programming questions about scripting the Inkscape vector-graphics application, e.g. using the Inkscape CLI as part of a graphics conversion workflow. Questions about installing the application should go on Super User. Questions about using the application should go on Graphic Design.

is there a tool to create SVG paths from an SVG file?

Open the svg using Inkscape.

Inkscape is a svg editor it is a bit like Illustrator but as it is built specifically for svg it handles it way better. It is a free software and it's available @ https://inkscape.org/en/

  • ctrl A (select all)
  • shift ctrl C (=Path/Object to paths)
  • ctrl s (save (choose as plain svg))

done

all rect/circle have been converted to path

How to make a <svg> element expand or contract to its parent container?

For your iphone You could use in your head balise :

"width=device-width"

How do you do a deep copy of an object in .NET?

The MSDN documentation seems to hint that Clone should perform a deep copy, but it is never explicitly stated:

The ICloneable interface contains one member, Clone, which is intended to support cloning beyond that supplied by MemberWiseClone… The MemberwiseClone method creates a shallow copy…

You can find my post helpful.

http://pragmaticcoding.com/index.php/cloning-objects-in-c/

MySQL Server has gone away when importing large sql file

If increasing max_allowed_packet doesn't help.

I was getting the same error as you when importing a .sql file into my database via Sequel Pro.

The error still persisted after upping the max_allowed_packet to 512M so I ran the import in the command line instead with:

mysql --verbose -u root -p DatabaseName < MySQL.sql

It gave the following error:

ASCII '\0' appeared in the statement, but this is not allowed unless option --binary-mode is enabled

I found a couple helpful StackOverflow questions:

In my case, my .sql file was a little corrupt or something. The MySQL dump we get comes in two zip files that need to be concatenated together and then unzipped. I think the unzipping was interrupted initially, leaving the file with some odd characters and encodings. Getting a fresh MySQL dump and unzipping it properly worked for me.

Just wanted to add this here in case others find that increasing the max_allowed_packet variable was not helping.

Bootstrap: add margin/padding space between columns

For those looking to control the space between a dynamic number of columns, try:

<div class="row no-gutters">
    <div class="col">
        <div class="inner">
            <!-- content here -->
        </div>
    </div>
    <div class="col">
        <div class="inner">
            <!-- content here -->
        </div>
    </div>
    <!-- etc. -->
</div>

CSS:

.col:not(:last-child) .inner {
  margin: 2px; // Or whatever you want your spacing to be
}

How does collections.defaultdict work?

The defaultdict tool is a container in the collections class of Python. It's similar to the usual dictionary (dict) container, but it has one difference: The value fields' data type is specified upon initialization.

For example:

from collections import defaultdict

d = defaultdict(list)

d['python'].append("awesome")

d['something-else'].append("not relevant")

d['python'].append("language")

for i in d.items():

    print i

This prints:

('python', ['awesome', 'language'])
('something-else', ['not relevant'])

Best way to check for IE less than 9 in JavaScript without library

I liked Mike Lewis' answer but the code did not pass jslint and I could not understand the funky while loop. My use case is to put up a browser not supported message if less than or equal to IE8.

Here is a jslint free version based on Mike Lewis':

/*jslint browser: true */
/*global jQuery */
(function () {
    "use strict";
    var browserNotSupported = (function () {
        var div = document.createElement('DIV');
        // http://msdn.microsoft.com/en-us/library/ms537512(v=vs.85).aspx
        div.innerHTML = '<!--[if lte IE 8]><I></I><![endif]-->';
        return div.getElementsByTagName('I').length > 0;
    }());
    if (browserNotSupported) {
        jQuery("html").addClass("browserNotSupported").data("browserNotSupported", browserNotSupported);
    }
}());

How does jQuery work when there are multiple elements with the same ID value?

Everybody says "Each id value must be used only once within a document", but what we do to get the elements we need when we have a stupid page that has more than one element with same id. If we use JQuery '#duplicatedId' selector we get the first element only. To achieve selecting the other elements you can do something like this

$("[id=duplicatedId]")

You will get a collection with all elements with id=duplicatedId

How to add a list item to an existing unordered list?

Instead of

$("#header ul li:last")

try

$("#header ul")

How to get Spinner selected item value to string?

    spinnerType = (AppCompatSpinner) findViewById(R.id.account_type);
    spinnerType.setPrompt("Select Type");

    spinnerType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            TypeItem clickedItem = (TypeItem) parent.getItemAtPosition(position);
            String TypeName = clickedItem.getTypeName();
            Toast.makeText(AddAccount.this, TypeName + " selected", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

Use directions service of Google Maps API v3. It's basically the same as directions API, but nicely packed in Google Maps API which also provides convenient way to easily render the route on the map.

Information and examples about rendering the directions route on the map can be found in rendering directions section of Google Maps API v3 documentation.

How do I enable Java in Microsoft Edge web browser?

You cannot open Java Applets (nor any other NPAPI plugin) in Microsoft Edge - they aren't supported and won't be added in the future.

Further you should be aware that in the next release of Google Chrome (v45 - due September 2015) NPAPI plugins will also no longer be supported.

Work-arounds

There are a couple of things that you can do:

Use Internet Explorer 11
You will find that in Windows 10 you will already have Internet Explorer 11 installed. IE 11 continues to support NPAPI (incl Java Applets). IE11 is squirrelled away (c:\program files\internet explorer\iexplore.exe). Just pin this exe to your task bar for easy access.

Use FireFox
You can also install and use a Firefox 32-bit Extended Support Release in Win10. Firefox have disabled NPAPI by default, but this can be overridden. This will only be supported until early 2018.

How to create JSON Object using String?

If you use the gson.JsonObject you can have something like that:

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

String jsonString = "{'test1':'value1','test2':{'id':0,'name':'testName'}}"
JsonObject jsonObject = (JsonObject) jsonParser.parse(jsonString)

Some dates recognized as dates, some dates not recognized. Why?

Here is what worked for me on a mm/dd/yyyy format:

=DATE(VALUE(RIGHT(A1,4)),VALUE(LEFT(A1,2)),VALUE(MID(A1,4,2)))

Convert the cell with the formula to date format and drag the formula down.

Run PostgreSQL queries from the command line

psql -U username -d mydatabase -c 'SELECT * FROM mytable'

If you're new to postgresql and unfamiliar with using the command line tool psql then there is some confusing behaviour you should be aware of when you've entered an interactive session.

For example, initiate an interactive session:

psql -U username mydatabase 
mydatabase=#

At this point you can enter a query directly but you must remember to terminate the query with a semicolon ;

For example:

mydatabase=# SELECT * FROM mytable;

If you forget the semicolon then when you hit enter you will get nothing on your return line because psql will be assuming that you have not finished entering your query. This can lead to all kinds of confusion. For example, if you re-enter the same query you will have most likely create a syntax error.

As an experiment, try typing any garble you want at the psql prompt then hit enter. psql will silently provide you with a new line. If you enter a semicolon on that new line and then hit enter, then you will receive the ERROR:

mydatabase=# asdfs 
mydatabase=# ;  
ERROR:  syntax error at or near "asdfs"
LINE 1: asdfs
    ^

The rule of thumb is: If you received no response from psql but you were expecting at least SOMETHING, then you forgot the semicolon ;

Which is faster: multiple single INSERTs or one multiple-row INSERT?

MYSQL 5.5 One sql insert statement took ~300 to ~450ms. while the below stats is for inline multiple insert statments.

(25492 row(s) affected)
Execution Time : 00:00:03:343
Transfer Time  : 00:00:00:000
Total Time     : 00:00:03:343

I would say inline is way to go :)

Sending a JSON HTTP POST request from Android

try some thing like blow:

SString otherParametersUrServiceNeed =  "Company=acompany&Lng=test&MainPeriod=test&UserID=123&CourseDate=8:10:10";
String request = "http://android.schoolportal.gr/Service.svc/SaveValues";

URL url = new URL(request); 
HttpURLConnection connection = (HttpURLConnection) url.openConnection();   
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setInstanceFollowRedirects(false); 
connection.setRequestMethod("POST"); 
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
connection.setRequestProperty("charset", "utf-8");
connection.setRequestProperty("Content-Length", "" + Integer.toString(otherParametersUrServiceNeed.getBytes().length));
connection.setUseCaches (false);

DataOutputStream wr = new DataOutputStream(connection.getOutputStream ());
wr.writeBytes(otherParametersUrServiceNeed);

   JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

wr.writeBytes(jsonParam.toString());

wr.flush();
wr.close();

References :

  1. http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
  2. Java - sending HTTP parameters via POST method easily

Python CSV error: line contains NULL byte

For all those 'rU' filemode haters: I just tried opening a CSV file from a Windows machine on a Mac with the 'rb' filemode and I got this error from the csv module:

Error: new-line character seen in unquoted field - do you need to 
open the file in universal-newline mode?

Opening the file in 'rU' mode works fine. I love universal-newline mode -- it saves me so much hassle.

Javascript use variable as object name

If you already know the list of the possible varible names then try creating a new Object(iconObj) whose properties name are same as object names, Here in below example, iconLib variable will hold two string values , either 'ZondIcons' or 'MaterialIcons'. propertyName is the property of ZondIcons or MaterialsIcon object.

   const iconObj = {
    ZondIcons,
    MaterialIcons,
  }
  const objValue = iconObj[iconLib][propertyName]

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

Step-1: Your Model class

public class RechargeMobileViewModel
    {
        public string CustomerFullName { get; set; }
        public string TelecomSubscriber { get; set; }
        public int TotalAmount { get; set; }
        public string MobileNumber { get; set; }
        public int Month { get; set; }
        public List<SelectListItem> getAllDaysList { get; set; }

        // Define the list which you have to show in Drop down List
        public List<SelectListItem> getAllWeekDaysList()
        {
            List<SelectListItem> myList = new List<SelectListItem>();
            var data = new[]{
                 new SelectListItem{ Value="1",Text="Monday"},
                 new SelectListItem{ Value="2",Text="Tuesday"},
                 new SelectListItem{ Value="3",Text="Wednesday"},
                 new SelectListItem{ Value="4",Text="Thrusday"},
                 new SelectListItem{ Value="5",Text="Friday"},
                 new SelectListItem{ Value="6",Text="Saturday"},
                 new SelectListItem{ Value="7",Text="Sunday"},
             };
            myList = data.ToList();
            return myList;
        }
}

Step-2: Call this method to fill Drop down in your controller Action

namespace MvcVariousApplication.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
              RechargeMobileViewModel objModel = new RechargeMobileViewModel();
                objModel.getAllDaysList = objModel.getAllWeekDaysList();  
                return View(objModel);
            }
    }
    }

Step-3: Fill your Drop-Down List of View as follows

 @model MvcVariousApplication.Models.RechargeMobileViewModel
    @{
        ViewBag.Title = "Contact";
    }
    @Html.LabelFor(model=> model.CustomerFullName)
    @Html.TextBoxFor(model => model.CustomerFullName)

    @Html.LabelFor(model => model.MobileNumber)
    @Html.TextBoxFor(model => model.MobileNumber)

    @Html.LabelFor(model => model.TelecomSubscriber)
    @Html.TextBoxFor(model => model.TelecomSubscriber)

    @Html.LabelFor(model => model.TotalAmount)
    @Html.TextBoxFor(model => model.TotalAmount)

    @Html.LabelFor(model => model.Month)
    @Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")

PHP: Return all dates between two dates in an array

Note that the answer provided by ViNce does NOT include the end date for the period.

If you are using PHP 5.3+, your best bet is to use a function like this:

/**
 * Generate an array of string dates between 2 dates
 *
 * @param string $start Start date
 * @param string $end End date
 * @param string $format Output format (Default: Y-m-d)
 *
 * @return array
 */
function getDatesFromRange($start, $end, $format = 'Y-m-d') {
    $array = array();
    $interval = new DateInterval('P1D');

    $realEnd = new DateTime($end);
    $realEnd->add($interval);

    $period = new DatePeriod(new DateTime($start), $interval, $realEnd);

    foreach($period as $date) { 
        $array[] = $date->format($format); 
    }

    return $array;
}

Then, you would call the function as expected:

getDatesFromRange('2010-10-01', '2010-10-05');

Run demo

Note about DatePeriod class: You can use the 4th parameter of DatePeriod to exclude the start date (DatePeriod::EXCLUDE_START_DATE) but you cannot, at this time, include the end date.

If...Then...Else with multiple statements after Then

Multiple statements are to be separated by a new line:

If SkyIsBlue Then
  StartEngines
  Pollute
ElseIf SkyIsRed Then
  StopAttack
  Vent
ElseIf SkyIsYellow Then
  If Sunset Then
    Sleep
  ElseIf Sunrise or IsMorning Then
    Smoke
    GetCoffee
  Else
    Error
  End If
Else
  Joke
  Laugh
End If

Check array position for null/empty

If the array contains integers, the value cannot be NULL. NULL can be used if the array contains pointers.

SomeClass* myArray[2];
myArray[0] = new SomeClass();
myArray[1] = NULL;

if (myArray[0] != NULL) { // this will be executed }
if (myArray[1] != NULL) { // this will NOT be executed }

As http://en.cppreference.com/w/cpp/types/NULL states, NULL is a null pointer constant!

svn: E155004: ..(path of resource).. is already locked

Just cleanup. Happened in JetBrains PhpStorm

Java Constructor Inheritance

When you inherit from Super this is what in reality happens:

public class Son extends Super{

  // If you dont declare a constructor of any type, adefault one will appear.
  public Son(){
    // If you dont call any other constructor in the first line a call to super() will be placed instead.
    super();
  }

}

So, that is the reason, because you have to call your unique constructor, since"Super" doesn't have a default one.

Now, trying to guess why Java doesn't support constructor inheritance, probably because a constructor only makes sense if it's talking about concrete instances, and you shouldn't be able to create an instance of something when you don't know how it's defined (by polymorphism).

Nexus 7 not visible over USB via "adb devices" from Windows 7 x64

I'm on Win 7 64-bit and I see that most people with the same problem here also on 64-bit. To rule out the hardware and the OS, I used VMware to run Win 7 32-bit on the same PC. Except for having to edit the .inf file with the correct VID/PID everything else went perfectly on Win 7 32-bit so that tells me the PC is fine and Win 7 32-bit is fine also.

Going back to my Win 7 64-bit none of the suggestions above worked for me. However I noticed one thing though, ADB is installed under Program Files (x86) but the driver installer is installing the 64-bit. Win 7 64-bit is recognizing the Nexus 7 as Android Composite ADB Interface but ADB does not detect it.

So is there an ADB 64-bit version somewhere? if my installation is under (x86) on Win 7 64-bit, does it mean I messed up with the installation somewhere.

Would my problem be related to USB drivers 64-bit installed but ADB is 32-bit?

Another issue I noticed when the Nexus 7 USB driver gets installed in the Properties I only see Android Composite ADB Interface for device functions. Under Win 7 32-bit Properties is showing 3 device functions.

Win 7 64b Win 7 32b

it looks like the issue is the USB driver still.

Understanding Matlab FFT example

The reason why your X-axis plots frequencies only till 500 Hz is your command statement 'f = Fs/2*linspace(0,1,NFFT/2+1);'. Your Fs is 1000. So when you divide it by 2 & then multiply by values ranging from 0 to 1, it returns a vector of length NFFT/2+1. This vector consists of equally spaced frequency values, ranging from 0 to Fs/2 (i.e. 500 Hz). Since you plot using 'plot(f,2*abs(Y(1:NFFT/2+1)))' command, your X-axis limit is 500 Hz.

Convert Time DataType into AM PM Format:

Try this:

select CONVERT(varchar(15),CAST('2014-05-28 16:07:54.647' AS TIME),100) as CreatedTime

JAVA How to remove trailing zeros from a double

You should use DecimalFormat("0.#")


For 4.3000

Double price = 4.3000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

output is:

4.3

In case of 5.000 we have

Double price = 5.000;
DecimalFormat format = new DecimalFormat("0.#");
System.out.println(format.format(price));

And the output is:

5

What is the meaning of {...this.props} in Reactjs

It will compile to this:

React.createElement('div', this.props, 'Content Here');

As you can see above, it passes all it's props to the div.

XPath to return only elements containing the text, and not its parents

Do you want to find elements that contain "match", or that equal "match"?

This will find elements that have text nodes that equal 'match' (matches none of the elements because of leading and trailing whitespace in random2):

//*[text()='match']

This will find all elements that have text nodes that equal "match", after removing leading and trailing whitespace(matches random2):

//*[normalize-space(text())='match']

This will find all elements that contain 'match' in the text node value (matches random2 and random3):

//*[contains(text(),'match')]

This XPATH 2.0 solution uses the matches() function and a regex pattern that looks for text nodes that contain 'match' and begin at the start of the string(i.e. ^) or a word boundary (i.e. \W) and terminated by the end of the string (i.e. $) or a word boundary. The third parameter i evaluates the regex pattern case-insensitive. (matches random2)

//*[matches(text(),'(^|\W)match($|\W)','i')]

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

I've had same problem with docker-compose:

  1. Killed docker-proxy processe .
  2. Restart docker
  3. Start docker-compose again.

Printing prime numbers from 1 through 100

#include "stdafx.h"
#include<iostream>
using namespace std;
void main()
{ int f =0;
 for(int i=2;i<=100;i++)
  {
   f=0;
   for(int j=2;j<=i/2;j++)
   { 
     if(i%j==0)
     { f=1;
       break;
     }
   }
 if (f==0)
  cout<<i<<" ";
}
 system("pause");
}

ORA-01882: timezone region not found

ERROR :

ORA-00604: error occurred at recursive SQL level 1 ORA-01882: timezone region not found

Solution: CIM setup in Centos.

/opt/oracle/product/ATG/ATG11.2/home/bin/dynamoEnv.sh

Add this java arguments:

JAVA_ARGS="${JAVA_ARGS} -Duser.timezone=EDT"

How do I tell matplotlib that I am done with a plot?

If you're using Matplotlib interactively, for example in a web application, (e.g. ipython) you maybe looking for

plt.show()

instead of plt.close() or plt.clf().

Meaning of tilde in Linux bash (not home directory)

Are they the home directories of users in /etc/passwd? Services like postgres, sendmail, apache, etc., create system users that have home directories just like normal users.

How do I create a GUI for a windows application using C++?

Just create a new MFC C++ app. It's built in, pretty easy, and thousands of examples exist in the world...

Plus, you can design your dialog box right in Visual Studio, give them variable names, and 90% of the code is generated for you.

How to define multiple CSS attributes in jQuery?

Best way is to use variable.

var style1 = {
   'font-size' : '10px',
   'width' : '30px',
   'height' : '10px'
};
$("#message").css(style1);

C++ - Assigning null to a std::string

compiler gives error because when assigning mValue=0 compiler find assignment operator=(int ) for compile time binding but it's not present in the string class. if we type cast following statement to char like mValue=(char)0 then its compile successfully because string class contain operator=(char) method.

Regular cast vs. static_cast vs. dynamic_cast

dynamic_cast has runtime type checking and only works with references and pointers, whereas static_cast does not offer runtime type checking. For complete information, see the MSDN article static_cast Operator.

Python/Django: log to console under runserver, log to file under Apache

This works quite well in my local.py, saves me messing up the regular logging:

from .settings import *

LOGGING['handlers']['console'] = {
    'level': 'DEBUG',
    'class': 'logging.StreamHandler',
    'formatter': 'verbose'
}
LOGGING['loggers']['foo.bar'] = {
    'handlers': ['console'],
    'propagate': False,
    'level': 'DEBUG',
}

How to get the previous url using PHP

$_SERVER['HTTP_REFERER'] will give you incomplete url.

If you want http://bawse.3owl.com/jayz__magna_carta_holy_grail.php, $_SERVER['HTTP_REFERER'] will give you http://bawse.3owl.com/ only.

Redirect after Login on WordPress

If you have php 5.3+, you can use an anonymous function like so:

add_filter( 'login_redirect', function() { return site_url('news'); } );

ReactJS: "Uncaught SyntaxError: Unexpected token <"

JSTransform is deprecated , please use babel instead.

<script type="text/babel" src="./lander.js"></script>

can we use xpath with BeautifulSoup?

Nope, BeautifulSoup, by itself, does not support XPath expressions.

An alternative library, lxml, does support XPath 1.0. It has a BeautifulSoup compatible mode where it'll try and parse broken HTML the way Soup does. However, the default lxml HTML parser does just as good a job of parsing broken HTML, and I believe is faster.

Once you've parsed your document into an lxml tree, you can use the .xpath() method to search for elements.

try:
    # Python 2
    from urllib2 import urlopen
except ImportError:
    from urllib.request import urlopen
from lxml import etree

url =  "http://www.example.com/servlet/av/ResultTemplate=AVResult.html"
response = urlopen(url)
htmlparser = etree.HTMLParser()
tree = etree.parse(response, htmlparser)
tree.xpath(xpathselector)

There is also a dedicated lxml.html() module with additional functionality.

Note that in the above example I passed the response object directly to lxml, as having the parser read directly from the stream is more efficient than reading the response into a large string first. To do the same with the requests library, you want to set stream=True and pass in the response.raw object after enabling transparent transport decompression:

import lxml.html
import requests

url =  "http://www.example.com/servlet/av/ResultTemplate=AVResult.html"
response = requests.get(url, stream=True)
response.raw.decode_content = True
tree = lxml.html.parse(response.raw)

Of possible interest to you is the CSS Selector support; the CSSSelector class translates CSS statements into XPath expressions, making your search for td.empformbody that much easier:

from lxml.cssselect import CSSSelector

td_empformbody = CSSSelector('td.empformbody')
for elem in td_empformbody(tree):
    # Do something with these table cells.

Coming full circle: BeautifulSoup itself does have very complete CSS selector support:

for cell in soup.select('table#foobar td.empformbody'):
    # Do something with these table cells.

Why can't I center with margin: 0 auto?

An inline-block covers the whole line (from left to right), so a margin left and/or right won't work here. What you need is a block, a block has borders on the left and the right so can be influenced by margins.

This is how it works for me:

#content {
display: block;
margin: 0 auto;
}

What is the cleanest way to get the progress of JQuery ajax request?

jQuery has an AjaxSetup() function that allows you to register global ajax handlers such as beforeSend and complete for all ajax calls as well as allow you to access the xhr object to do the progress that you are looking for

How to check if a variable is both null and /or undefined in JavaScript

A variable cannot be both null and undefined at the same time. However, the direct answer to your question is:

if (variable != null)

One =, not two.

There are two special clauses in the "abstract equality comparison algorithm" in the JavaScript spec devoted to the case of one operand being null and the other being undefined, and the result is true for == and false for !=. Thus if the value of the variable is undefined, it's not != null, and if it's not null, it's obviously not != null.

Now, the case of an identifier not being defined at all, either as a var or let, as a function parameter, or as a property of the global context is different. A reference to such an identifier is treated as an error at runtime. You could attempt a reference and catch the error:

var isDefined = false;
try {
  (variable);
  isDefined = true;
}
catch (x) {}

I would personally consider that a questionable practice however. For global symbols that may or may be there based on the presence or absence of some other library, or some similar situation, you can test for a window property (in browser JavaScript):

var isJqueryAvailable = window.jQuery != null;

or

var isJqueryAvailable = "jQuery" in window;

Generate UML Class Diagram from Java Project

I wrote Class Visualizer, which does it. It's free tool which has all the mentioned functionality - I personally use it for the same purposes, as described in this post. For each browsed class it shows 2 instantly generated class diagrams: class relations and class UML view. Class relations diagram allows to traverse through the whole structure. It has full support for annotations and generics plus special support for JPA entities. Works very well with big projects (thousands of classes).

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

I did not want to install visual studio and development environment, so I have installed AspNetMVC4Setup.exe in Windows server 2016 machine and it solved the problem. The installer was downloaded from Microsoft website.

File properties of the installer

How can I get the active screen dimensions?

Adding a solution that doesn't use WinForms but NativeMethods instead. First you need to define the native methods needed.

public static class NativeMethods
{
    public const Int32 MONITOR_DEFAULTTOPRIMERTY = 0x00000001;
    public const Int32 MONITOR_DEFAULTTONEAREST = 0x00000002;


    [DllImport( "user32.dll" )]
    public static extern IntPtr MonitorFromWindow( IntPtr handle, Int32 flags );


    [DllImport( "user32.dll" )]
    public static extern Boolean GetMonitorInfo( IntPtr hMonitor, NativeMonitorInfo lpmi );


    [Serializable, StructLayout( LayoutKind.Sequential )]
    public struct NativeRectangle
    {
        public Int32 Left;
        public Int32 Top;
        public Int32 Right;
        public Int32 Bottom;


        public NativeRectangle( Int32 left, Int32 top, Int32 right, Int32 bottom )
        {
            this.Left = left;
            this.Top = top;
            this.Right = right;
            this.Bottom = bottom;
        }
    }


    [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Auto )]
    public sealed class NativeMonitorInfo
    {
        public Int32 Size = Marshal.SizeOf( typeof( NativeMonitorInfo ) );
        public NativeRectangle Monitor;
        public NativeRectangle Work;
        public Int32 Flags;
    }
}

And then get the monitor handle and the monitor info like this.

        var hwnd = new WindowInteropHelper( this ).EnsureHandle();
        var monitor = NativeMethods.MonitorFromWindow( hwnd, NativeMethods.MONITOR_DEFAULTTONEAREST );

        if ( monitor != IntPtr.Zero )
        {
            var monitorInfo = new NativeMonitorInfo();
            NativeMethods.GetMonitorInfo( monitor, monitorInfo );

            var left = monitorInfo.Monitor.Left;
            var top = monitorInfo.Monitor.Top;
            var width = ( monitorInfo.Monitor.Right - monitorInfo.Monitor.Left );
            var height = ( monitorInfo.Monitor.Bottom - monitorInfo.Monitor.Top );
        }

Simple example for Intent and Bundle

Basically this is what you need to do:
in the first activity:

Intent intent = new Intent();
intent.setAction(this, SecondActivity.class);
intent.putExtra(tag, value);
startActivity(intent);

and in the second activtiy:

Intent intent = getIntent();
intent.getBooleanExtra(tag, defaultValue);
intent.getStringExtra(tag, defaultValue);
intent.getIntegerExtra(tag, defaultValue);

one of the get-functions will give return you the value, depending on the datatype you are passing through.

CSS vertical alignment text inside li

Simple solution for vertical align middle... for me it works like a charm

ul{display:table; text-align:center; margin:0 auto;}
li{display:inline-block; text-align:center;}
li.items_inside_li{display:inline-block; vertical-align:middle;}

How to get streaming url from online streaming radio station

When you go to a stream url, you get offered a file. feed this file to a parser to extract the contents out of it. the file is (usually) plain text and contains the url to play.

Can I install the "app store" in an IOS simulator?

This is NOT possible

The Simulator does not run ARM code, ONLY x86 code. Unless you have the raw source code from Apple, you won't see the App Store on the Simulator.

The app you write you will be able to test in the Simulator by running it directly from Xcode even if you don't have a developer account. To test your app on an actual device, you will need to be apart of the Apple Developer program.

How do you convert a jQuery object into a string?

No need to clone and add to the DOM to use .html(), you can do:

$('#item-of-interest').wrap('<div></div>').html()

How to parse/read a YAML file into a Python object?

From http://pyyaml.org/wiki/PyYAMLDocumentation:

add_path_resolver(tag, path, kind) adds a path-based implicit tag resolver. A path is a list of keys that form a path to a node in the representation graph. Paths elements can be string values, integers, or None. The kind of a node can be str, list, dict, or None.

#!/usr/bin/env python
import yaml

class Person(yaml.YAMLObject):
  yaml_tag = '!person'

  def __init__(self, name):
    self.name = name

yaml.add_path_resolver('!person', ['Person'], dict)

data = yaml.load("""
Person:
  name: XYZ
""")

print data
# {'Person': <__main__.Person object at 0x7f2b251ceb10>}

print data['Person'].name
# XYZ

TypeError: $(...).DataTable is not a function

CAUSE

There could be multiple reasons for this error.

  • jQuery DataTables library is missing.
  • jQuery library is loaded after jQuery DataTables.
  • Multiple versions of jQuery library is loaded.

SOLUTION

Include only one version of jQuery library version 1.7 or newer before jQuery DataTables.

For example:

<script src="js/jquery.min.js" type="text/javascript"></script>
<script src="js/jquery.dataTables.min.js" type="text/javascript"></script>

See jQuery DataTables: Common JavaScript console errors for more information on this and other common console errors.

Sort an array in Java

If you want to build the Quick sort algorithm yourself and have more understanding of how it works check the below code :

1- Create sort class

class QuickSort {
    private int input[];
    private int length;

    public void sort(int[] numbers) {
        if (numbers == null || numbers.length == 0) {
            return;
        }
        this.input = numbers;
        length = numbers.length;
        quickSort(0, length - 1);
    }
    /*
     * This method implements in-place quicksort algorithm recursively.
     */

    private void quickSort(int low, int high) {
        int i = low;
        int j = high;

        // pivot is middle index
        int pivot = input[low + (high - low) / 2];

        // Divide into two arrays
        while (i <= j) {
            /**
             * As shown in above image, In each iteration, we will identify a
             * number from left side which is greater then the pivot value, and
             * a number from right side which is less then the pivot value. Once
             * search is complete, we can swap both numbers.
             */
            while (input[i] < pivot) {
                i++;
            }
            while (input[j] > pivot) {
                j--;
            }
            if (i <= j) {
                swap(i, j);
                // move index to next position on both sides
                i++;
                j--;
            }
        }

        // calls quickSort() method recursively
        if (low < j) {
            quickSort(low, j);
        }

        if (i < high) {
            quickSort(i, high);
        }
    }

    private void swap(int i, int j) {
        int temp = input[i];
        input[i] = input[j];
        input[j] = temp;
    }
}

2- Send your unsorted array to Quicksort class

import java.util.Arrays;


public class QuickSortDemo {

    public static void main(String args[]) {
        // unsorted integer array
        int[] unsorted = {6, 5, 3, 1, 8, 7, 2, 4};
        System.out.println("Unsorted array :" + Arrays.toString(unsorted));
        QuickSort algorithm = new QuickSort();
        // sorting integer array using quicksort algorithm
        algorithm.sort(unsorted);
        // printing sorted array
        System.out.println("Sorted array :" + Arrays.toString(unsorted));
    }
}

3- Output

Unsorted array :[6, 5, 3, 1, 8, 7, 2, 4] 
Sorted array :[1, 2, 3, 4, 5, 6, 7, 8]

Return an empty Observable

In my case with Angular2 and rxjs, it worked with:

import {EmptyObservable} from 'rxjs/observable/EmptyObservable';
...
return new EmptyObservable();
...

How to call a php script/function on a html button click

the_function() {

$.ajax({url:"demo_test.php",success:function(result){

   alert(result); // will alert 1

 }});

}

// demo_test.php

<?php echo 1; ?>

Notes

  1. Include jquery library for using the jquery Ajax
  2. Keep the demo_test.php file in the same folder where your javascript file resides

Different class for the last element in ng-repeat

To elaborate on Paul's answer, this is the controller logic that coincides with the template code.

// HTML
<div class="row" ng-repeat="thing in things">
  <div class="well" ng-class="isLast($last)">
      <p>Data-driven {{thing.name}}</p>
  </div>
</div>

// CSS
.last { /* Desired Styles */}

// Controller
$scope.isLast = function(check) {
    var cssClass = check ? 'last' : null;
    return cssClass;
};

Its also worth noting that you really should avoid this solution if possible. By nature CSS can handle this, making a JS-based solution is unnecessary and non-performant. Unfortunately if you need to support IE8> this solution won't work for you (see MDN support docs).

CSS-Only Solution

// Using the above example syntax
.row:last-of-type { /* Desired Style */ }

How to select rows that have current day's timestamp?

SELECT * FROM `table` WHERE timestamp >= CURDATE()

it is shorter , there is no need to use 'AND timestamp < CURDATE() + INTERVAL 1 DAY'

because CURDATE() always return current day

MySQL CURDATE() Function

New line in JavaScript alert box

Works with \n but if the script is into a java tag you must write \\\n

<script type="text/javascript">alert('text\ntext');</script>

or

<h:commandButton action="#{XXXXXXX.xxxxxxxxxx}" value="XXXXXXXX" 
    onclick="alert('text\\\ntext');" />

Get div height with plain JavaScript

One option would be

const styleElement = getComputedStyle(document.getElementById("myDiv"));
console.log(styleElement.height);

Can there be an apostrophe in an email address?

Yes, according to RFC 3696 apostrophes are valid as long as they come before the @ symbol.

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

How to tell if browser/tab is active

All of the examples here (with the exception of rockacola's) require that the user physically click on the window to define focus. This isn't ideal, so .hover() is the better choice:

$(window).hover(function(event) {
    if (event.fromElement) {
        console.log("inactive");
    } else {
        console.log("active");
    }
});

This'll tell you when the user has their mouse on the screen, though it still won't tell you if it's in the foreground with the user's mouse elsewhere.

Access images inside public folder in laravel

You simply need to use the asset helper function in Laravel. (The url helper can also be used in this manner)

<img src="{{ asset('images/arrow.gif') }}" />

For the absolute path, you use public_path instead.

<p>Absolute path: {{ public_path('images/arrow.gif') }}</p>

If you are providing the URL to a public image from a controller (backend) you can use asset as well, or secure_asset if you want HTTPS. eg:

$url = asset('images/arrow.gif'); # http://example.com/assets/images/arrow.gif
$secure_url = secure_asset('images/arrow.gif'); # https://example.com/assets/images/arrow.gif

return $secure_url;

Lastly, if you want to go directly to the image on a given route you can redirect to it:

return \Redirect::to($secure_url);

More Laravel helper functions can be found here

Get checkbox list values with jQuery

You can try this...

$(document).ready(function() {
        $("button").click(function(){
            var checkBoxValues = [];
            $.each($("input[name='check_name']:checked"), function(){
                checkBoxValues.push($(this).val());
            });

            console.log(checkBoxValues);

        });
    });

CURL to access a page that requires a login from a different page

The web site likely uses cookies to store your session information. When you run

curl --user user:pass https://xyz.com/a  #works ok
curl https://xyz.com/b #doesn't work

curl is run twice, in two separate sessions. Thus when the second command runs, the cookies set by the 1st command are not available; it's just as if you logged in to page a in one browser session, and tried to access page b in a different one.

What you need to do is save the cookies created by the first command:

curl --user user:pass --cookie-jar ./somefile https://xyz.com/a

and then read them back in when running the second:

curl --cookie ./somefile https://xyz.com/b

Alternatively you can try downloading both files in the same command, which I think will use the same cookies.

How should I throw a divide by zero exception in Java without actually dividing by zero?

public class ZeroDivisionException extends ArithmeticException {
    // ...
}

if (denominator == 0) {
    throw new ZeroDivisionException();
}

Extract specific columns from delimited file using Awk

Other languages have short cuts for ranges of field numbers, but not awk, you'll have to write your code as your fear ;-)

awk -F, 'BEGIN {OFS=","} { print $1, $2, $3, $4 ..... $30, $33}' infile.csv > outfile.csv

There is no direct function in awk to use field names as column specifiers.

I hope this helps.

Entity Framework Provider type could not be loaded?

I was working on the Contoso University tutorial offline and encountered the same issue when trying to create my first controller using EF. I had to use the Package Manager Console to load EF from the nuget cache and created a connection string to my local instance of SQL Server, my point here is my webConfig setting for EF may not be set as you all out there but I was able to resolve my issue by completely deleting the "providers" section within "entityFramework"

Robert

How to update npm

nvm install-latest-npm

if you happen to use nvm

Where should my npm modules be installed on Mac OS X?

/usr/local/lib/node_modules is the correct directory for globally installed node modules.

/usr/local/share/npm/lib/node_modules makes no sense to me. One issue here is that you're confused because there are two directories called node_modules:

/usr/local/lib/node_modules
/usr/local/lib/node_modules/npm/node_modules

The latter seems to be node modules that came with Node, e.g., lodash, when the former is Node modules that I installed using npm.

How to create a QR code reader in a HTML5 website?

The algorithm that drives http://www.webqr.com is a JavaScript implementation of https://github.com/LazarSoft/jsqrcode. I haven't tried how reliable it is yet, but that's certainly the easier plug-and-play solution (client- or server-side) out of the two.

How to run html file using node js

This is a simple html file "demo.htm" stored in the same folder as the node.js file.

<!DOCTYPE html>
<html>
  <body>
    <h1>Heading</h1>
    <p>Paragraph.</p>
  </body>
</html>

Below is the node.js file to call this html file.

var http = require('http');
var fs = require('fs');

var server = http.createServer(function(req, resp){
  // Print the name of the file for which request is made.
  console.log("Request for demo file received.");
  fs.readFile("Documents/nodejs/demo.html",function(error, data){
    if (error) {
      resp.writeHead(404);
      resp.write('Contents you are looking for-not found');
      resp.end();
    }  else {
      resp.writeHead(200, {
        'Content-Type': 'text/html'
      });
      resp.write(data.toString());
      resp.end();
    }
  });
});

server.listen(8081, '127.0.0.1');

console.log('Server running at http://127.0.0.1:8081/');

Intiate the above nodejs file in command prompt and the message "Server running at http://127.0.0.1:8081/" is displayed.Now in your browser type "http://127.0.0.1:8081/demo.html".

Fatal error: Call to undefined function mysqli_connect()

There is no error in the, but the mysqli PHP extension is not installed on your machine. Please contact your service provider to fix this issue.

Is Visual Studio Community a 30 day trial?

In my case, I already was signed in. So I had to sign out and sign in again.

In spanish Cerrar Sesion is sign out.

screenshot

How to hide UINavigationBar 1px bottom line

I ran into the same issue and none of the answers were truly satisfying. Here is my take for Swift3:

func hideNavigationBarLine() {
    navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    navigationController?.navigationBar.shadowImage = UIImage()
}

Simply call this from within viewDidLoad().

Cannot install Aptana Studio 3.6 on Windows

Installing Aptana Studio in passive mode bypasses the installation of Git for Windows and Node.js.

Aptana_Studio_3_Setup_3.6.1 /passive /norestart

(I am unsure whether Aptana Studio will work properly without those "prerequisites", but it appears to.)

If you want a global installation in a specific directory, the command line is

Aptana_Studio_3_Setup_3.6.1.exe /passive /norestart ALLUSERS=1 APPDIR=c:\apps\AptanaStudio

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

For whatever reason, TWO of my solutions have web projects that spontaneously uninstalled asp.net MVC somehow. I installed it from Nuget and now they both work again. This happened after a recent batch of windows updates that included .net framework updates for the version I was using (4.5.1).

Edit: From the .Net Web Development and Tools Blog:

Microsoft Asp.Net MVC Security Update MS14-059 broke my build!

phpMyAdmin - config.inc.php configuration?

for phpMyAdmin-4.8.5-all-languages copy content from config.sample.inc.php into new file config.inc.php and instead of

/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'cookie';
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'localhost';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = false;

put the folowing content:

/* Authentication type */
$cfg['Servers'][$i]['auth_type'] = 'config';
/* Server parameters */
$cfg['Servers'][$i]['host'] = 'localhost}';
$cfg['Servers'][$i]['user'] = '{your root mysql username';
$cfg['Servers'][$i]['password'] = '{your pasword for root user to login into mysql}';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['compress'] = false;
$cfg['Servers'][$i]['AllowNoPassword'] = true;

the rest remain commented an un-changed...

How to quit a java app from within the program

System.exit() will do what you want. But in most situations, you probably want to exit a thread, and leave the main thread alive. By doing that, you can terminate a task, but also keep the ability to start another task without restarting the app.

How do I find the PublicKeyToken for a particular dll?

Just adding more info, I wasn't able to find sn.exe utility in the mentioned locations, in my case it was in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin

Can I limit the length of an array in JavaScript?

I think you could just do:

let array = [];
array.length = 2;
Object.defineProperty(array, 'length', {writable:false});


array[0] = 1 // [1, undefined]

array[1] = 2 // [1, 2]

array[2] = 3 // [1, 2] -> doesn't add anything and fails silently

array.push("something"); //but this throws an Uncaught TypeError

Change color of Back button in navigation bar

For Swift 2.0, To change the Navigation-bar tint color, title text and back button tint color changed by using the following in AppDelegate.swift

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

  // Override point for customization after application launch.


    //Navigation bar tint color change

    UINavigationBar.appearance().barTintColor = UIColor(red: 42/255.0, green: 140/255.0, blue: 166/255.0, alpha: 0.5)

    //Back button tint color change

    UINavigationBar.appearance().barStyle = UIBarStyle.Default
    UINavigationBar.appearance().tintColor =  UIColor(red: 204/255.0, green: 255/255.0, blue: 204/255.0, alpha: 1)

    //Navigation Menu font tint color change

    UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName: UIColor(red: 204/255.0, green: 255/255.0, blue: 204/255.0, alpha: 1), NSFontAttributeName: UIFont(name: "OpenSans-Bold", size: 25)!]//UIColor(red: 42/255.0, green: 140/255.0, blue: 166/255.0, alpha: 1.0)

    UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.LightContent


    return true
}

Why does MSBuild look in C:\ for Microsoft.Cpp.Default.props instead of c:\Program Files (x86)\MSBuild? ( error MSB4019)

I just added VCTargetsPath={c:\...} as an environment variable to my Hudson job.

How to format strings using printf() to get equal length in the output

Additionally, if you want the flexibility of choosing the width, you can choose between one of the following two formats (with or without truncation):

int width = 30;
// No truncation uses %-*s
printf( "%-*s %s\n", width, "Starting initialization...", "Ok." );
// Output is "Starting initialization...     Ok."

// Truncated to the specified width uses %-.*s
printf( "%-.*s %s\n", width, "Starting initialization...", "Ok." );
// Output is "Starting initialization... Ok."

Spaces in URLs?

They are indeed fools. If you look at RFC 3986 Appendix A, you will see that "space" is simply not mentioned anywhere in the grammar for defining a URL. Since it's not mentioned anywhere in the grammar, the only way to encode a space is with percent-encoding (%20).

In fact, the RFC even states that spaces are delimiters and should be ignored:

In some cases, extra whitespace (spaces, line-breaks, tabs, etc.) may have to be added to break a long URI across lines. The whitespace should be ignored when the URI is extracted.

and

For robustness, software that accepts user-typed URI should attempt to recognize and strip both delimiters and embedded whitespace.

Curiously, the use of + as an encoding for space isn't mentioned in the RFC, although it is reserved as a sub-delimeter. I suspect that its use is either just convention or covered by a different RFC (possibly HTTP).

How to see full absolute path of a symlink

realpath <path to the symlink file> should do the trick.

How do I convert a pandas Series or index to a Numpy array?

I converted the pandas dataframe to list and then used the basic list.index(). Something like this:

dd = list(zone[0]) #Where zone[0] is some specific column of the table
idx = dd.index(filename[i])

You have you index value as idx.

If Else in LINQ

I assume from db that this is LINQ-to-SQL / Entity Framework / similar (not LINQ-to-Objects);

Generally, you do better with the conditional syntax ( a ? b : c) - however, I don't know if it will work with your different queries like that (after all, how would your write the TSQL?).

For a trivial example of the type of thing you can do:

select new {p.PriceID, Type = p.Price > 0 ? "debit" : "credit" };

You can do much richer things, but I really doubt you can pick the table in the conditional. You're welcome to try, of course...

How to do while loops with multiple conditions

condition1 = False
condition2 = False
val = -1
#here is the function getstuff is not defined, i hope you define it before
#calling it into while loop code

while condition1 and condition2 is False and val == -1:
#as you can see above , we can write that in a simplified syntax.
    val,something1,something2 = getstuff()

    if something1 == 10:
        condition1 = True

    elif something2 == 20:
# here you don't have to use "if" over and over, if have to then write "elif" instead    
    condition2 = True
# ihope it can be helpfull

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can also enable multiple GPU cores, like so:

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0,2,3,4"

How do I make text bold in HTML?

In Html use:

  • Some <b>text</b> that I want emboldened.
  • Some <strong>text</strong> that I want emboldened.

In CSS use:

  • Some <span style="font-weight:bold">text</span> that I want emboldened.

Using underscores in Java variables and method names

I don't think using _ or m_ to indicate member variables is bad in Java or any other language. It my opinion it improves readability of your code because it allows you to look at a snippet and quickly identify out all of the member variables from locals.

You can also achieve this by forcing users to prepend instance variables with "this" but I find this slighly draconian. In many ways it violates DRY because it's an instance variable, why qualify it twice.

My own personal style is to use m_ instead of _. The reason being that there are also global and static variables. The advantage to m_/_ is it distinguishes a variables scope. So you can't reuse _ for global or static and instead I choose g_ and s_ respectively.

Vim: faster way to select blocks of text in visual mode

I use this with fold in indent mode :

v open Visual mode anywhere on the block

zaza toogle it twice

How to get the hours difference between two date objects?

The simplest way would be to directly subtract the date objects from one another.

For example:

var hours = Math.abs(date1 - date2) / 36e5;

The subtraction returns the difference between the two dates in milliseconds. 36e5 is the scientific notation for 60*60*1000, dividing by which converts the milliseconds difference into hours.

Java - checking if parseInt throws exception

You could try

NumberUtils.isParsable(yourInput)

It is part of org/apache/commons/lang3/math/NumberUtils and it checks whether the string can be parsed by Integer.parseInt(String), Long.parseLong(String), Float.parseFloat(String) or Double.parseDouble(String).

See below:

https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/math/NumberUtils.html#isParsable-java.lang.String-

$apply already in progress error

You can use this statement:

if ($scope.$root.$$phase != '$apply' && $scope.$root.$$phase != '$digest') {
    $scope.$apply();
}

How do I create a basic UIButton programmatically?

UIButton *custombutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[custombutton addTarget:self
                 action:@selector(aMethod:)
       forControlEvents:UIControlEventTouchUpInside];
[custombutton setTitle:@"Click" forState:UIControlStateNormal];
custombutton.frame = CGRectMake(80.0, 110.0, 160.0, 40.0);
custombutton.titleLabel.textColor = [UIColor colorWithRed: 2.0f/255.0f green: 155.0f/255.0f blue: 213.0f/255.0f  alpha:1];
 [custombutton setImage:[UIImage imageNamed:@"hh.png"] forState:UIControlStateNormal];
 [view addSubview:custombutton];

form with no action and where enter does not reload page

The first response is the best solution:

Add an onsubmit handler to the form (either via plain js or jquery $().submit(fn)), and return false unless your specific conditions are met.

More specific with jquery:

$('#your-form-id').submit(function(){return false;});

Unless you don't want the form to submit, ever - in which case, why not just leave out the 'action' attribute on the form element?

Writing Chrome extensions is an example of where you might have a form for user input, but you don't want it to submit. If you use action="javascript:void(0);", the code will probably work but you will end up with this problem where you get an error about running inline Javascript.

If you leave out the action completely, the form will reload which is also undesired in some cases when writing a Chrome extension. Or if you had a webpage with some sort of an embedded calculator, where the user would provide some input and click "Calculate" or something like that.

python filter list of dictionaries based on key value

Use filter, or if the number of dictionaries in exampleSet is too high, use ifilter of the itertools module. It would return an iterator, instead of filling up your system's memory with the entire list at once:

from itertools import ifilter
for elem in ifilter(lambda x: x['type'] in keyValList, exampleSet):
    print elem

Android Studio - mergeDebugResources exception

In my case, when I changed package name this issue appeared, I just followed below steps to fix my problem:

  1. Removed previously installed apk (uninstall)

  2. Applied project clean

  3. Run the app

HTML: how to make 2 tables with different CSS

In your html

<table class="table1">
<tr>
<td>
...
</table>

<table class="table2">

<tr>
<td>
...
</table>

In your css:

table.table1 {...}
table.table1 tr {...}
table.table1 td {...}

table.table2 {...}
table.table2 tr {...}
table.table2 td {...}

Facebook API "This app is in development mode"

App Review > Make {Your App} public? > Yes

Click app review and Turn on the Make your app Public toggle. Save changes

Why can't I declare static methods in an interface?

With Java 8, interfaces can now have static methods.

For example, Comparator has a static naturalOrder() method.

The requirement that interfaces cannot have implementations has also been relaxed. Interfaces can now declare "default" method implementations, which are like normal implementations with one exception: if you inherit both a default implementation from an interface and a normal implementation from a superclass, the superclass's implementation will always take priority.

How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running

There are two ways to achieve that:

  • Use -rpath linker option:

gcc XXX.c -o xxx.out -L$HOME/.usr/lib -lXX -Wl,-rpath=/home/user/.usr/lib

  • Use LD_LIBRARY_PATH environment variable - put this line in your ~/.bashrc file:

    export LD_LIBRARY_PATH=/home/user/.usr/lib

This will work even for a pre-generated binaries, so you can for example download some packages from the debian.org, unpack the binaries and shared libraries into your home directory, and launch them without recompiling.

For a quick test, you can also do (in bash at least):

LD_LIBRARY_PATH=/home/user/.usr/lib ./xxx.out

which has the advantage of not changing your library path for everything else.

What is the difference between os.path.basename() and os.path.dirname()?

To summarize what was mentioned by Breno above

Say you have a variable with a path to a file

path = '/home/User/Desktop/myfile.py'

os.path.basename(path) returns the string 'myfile.py'

and

os.path.dirname(path) returns the string '/home/User/Desktop' (without a trailing slash '/')

These functions are used when you have to get the filename/directory name given a full path name.

In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py' you just have myfile.py), os.path.dirname(path) returns an empty string.

Constants in Kotlin -- what's a recommended way to create them?

In Kotlin, if you want to create the local constants which are supposed to be used with in the class then you can create it like below

val MY_CONSTANT = "Constants"

And if you want to create a public constant in kotlin like public static final in java, you can create it as follow.

companion object{

     const val MY_CONSTANT = "Constants"

}

How can I combine two commits into one commit?

  1. Checkout your branch and count quantity of all your commits.
  2. Open git bash and write: git rebase -i HEAD~<quantity of your commits> (i.e. git rebase -i HEAD~5)
  3. In opened txt file change pick keyword to squash for all commits, except first commit (which is on the top). For top one change it to reword (which means you will provide a new comment for this commit in the next step) and click SAVE! If in vim, press esc then save by entering wq! and press enter.
  4. Provide Comment.
  5. Open Git and make "Fetch all" to see new changes.

Done

Is Laravel really this slow?

I know this is a little old question, but things changed. Laravel isn't that slow. It's, as mentioned, synced folders are slow. However, on Windows 10 I wasn't able to use rsync. I tried both cygwin and minGW. It seems like rsync is incompatible with git for windows's version of ssh.

Here is what worked for me: NFS.

Vagrant docs says:

NFS folders do not work on Windows hosts. Vagrant will ignore your request for NFS synced folders on Windows.

This isn't true anymore. We can use vagrant-winnfsd plugin nowadays. It's really simple to install:

  1. Execute vagrant plugin install vagrant-winnfsd
  2. Change in your Vagrantfile: config.vm.synced_folder ".", "/vagrant", type: "nfs"
  3. Add to Vagrantfile: config.vm.network "private_network", type: "dhcp"

That's all I needed to make NFS work. Laravel response time decreased from 500ms to 100ms for me.

How set the android:gravity to TextView from Java side in Android

labelTV.setGravity(Gravity.CENTER | Gravity.BOTTOM);

Kotlin version (thanks to Thommy)

labelTV.gravity = Gravity.CENTER_HORIZONTAL or Gravity.BOTTOM

Also, are you talking about gravity or about layout_gravity? The latter won't work in a RelativeLayout.

Navigate to another page with a button in angular 2

Having the router link on the button seems to work fine for me:

<button class="nav-link" routerLink="/" (click)="hideMenu()">
     <i class="fa fa-home"></i> 
     <span>Home</span>
</button>

Loading basic HTML in Node.js

we can load the html document with connect frame work. I have placed my html document and the related images in the public folder of my project where the below code and node modules present.

//server.js
var http=require('http');
var connect=require('connect');

var app = connect()
  .use(connect.logger('dev'))
  .use(connect.static('public'))
  .use(function(req, res){
   res.end('hello world\n');
 })

http.createServer(app).listen(3000);

I have tried the readFile() method of fs, but it fails to load the images, that's why i have used the connect framework.

JSON.stringify output to div in pretty print way

Please use a <pre> tag

demo : http://jsfiddle.net/K83cK/

_x000D_
_x000D_
var data = {_x000D_
  "data": {_x000D_
    "x": "1",_x000D_
    "y": "1",_x000D_
    "url": "http://url.com"_x000D_
  },_x000D_
  "event": "start",_x000D_
  "show": 1,_x000D_
  "id": 50_x000D_
}_x000D_
_x000D_
_x000D_
document.getElementById("json").textContent = JSON.stringify(data, undefined, 2);
_x000D_
<pre id="json"></pre>
_x000D_
_x000D_
_x000D_

How much does it cost to develop an iPhone application?

I hate to admit how little I've done an iPhone app for, but I can tell you I won't be doing that again. The guy who said that "simple, one function apps can be done .. [by solo developers]... for $5K" is correct; however, that is still lowball, and presumes almost no project design, graphic design or network backend work.

Day Name from Date in JS

Take a look at this :

var event = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));

var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };

console.log(event.toLocaleDateString('de-DE', options));
// expected output: Donnerstag, 20. Dezember 2012

console.log(event.toLocaleDateString('ar-EG', options));
// expected output: ??????? ?? ??????? ????

console.log(event.toLocaleDateString('ko-KR', options));
// expected output: 2012? 12? 20? ???

Source : Mozilla Doc

Ternary operators in JavaScript without an "else"

To use a ternary operator without else inside of an array or object declaration, you can use the ES6 spread operator, ...():

const cond = false;
const arr = [
  ...(cond ? ['a'] : []),
  'b',
];
    // ['b']

And for objects:

const cond = false;
const obj = {
  ...(cond ? {a: 1} : {}),
  b: 2,
};
    // {b: 2}

Original source

How do I copy items from list to list without foreach?

For a list of elements

List<string> lstTest = new List<string>();

lstTest.Add("test1");
lstTest.Add("test2");
lstTest.Add("test3");
lstTest.Add("test4");
lstTest.Add("test5");
lstTest.Add("test6");

If you want to copy all the elements

List<string> lstNew = new List<string>();
lstNew.AddRange(lstTest);

If you want to copy the first 3 elements

List<string> lstNew = lstTest.GetRange(0, 3);

Git: See my last commit

git diff --stat HEAD

This shows the same diffstat as your last commit.

Multiple radio button groups in MVC 4 Razor

I was able to use the name attribute that you described in your example for the loop I am working on and it worked, perhaps because I created unique ids? I'm still considering whether I should switch to an editor template instead as mentioned in the links in another answer.

    @Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "true", new {Name = item.Description.QuestionId, id = string.Format("CBY{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" }) Yes

    @Html.RadioButtonFor(modelItem => item.Answers.AnswerYesNo, "false", new { Name = item.Description.QuestionId, id = string.Format("CBN{0}", item.Description.QuestionId), onclick = "setDescriptionVisibility(this)" } ) No

How to check the function's return value if true or false

false != 'false'

For good measures, put the result of validate into a variable to avoid double validation and use that in the IF statement. Like this:

var result = ValidateForm();
if(result == false) {
...
}

How to get all enum values in Java?

YourEnumClass[] yourEnums = YourEnumClass.class.getEnumConstants();

Or

YourEnumClass[] yourEnums = YourEnumClass.values();

How to get file path in iPhone app

Remember that the "folders/groups" you make in xcode, those which are yellowish are not reflected as real folders in your iPhone app. They are just there to structure your XCode project. You can nest as many yellow group as you want and they still only serve the purpose of organizing code in XCode.

EDIT

Make a folder outside of XCode then drag it over, and select "Create folder references for any added folders" instead of "Create groups for any added folders" in the popup.

java.lang.ClassCastException

According to the documentation:

Thrown to indicate that the code has attempted to cast an Object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:

Object x = new Integer(0);
System.out.println((String)x); 

In c# is there a method to find the max of 3 numbers?

As generic

public static T Min<T>(params T[] values) {
    return values.Min();
}

public static T Max<T>(params T[] values) {
    return values.Max();
}

PHP sessions that have already been started

<?php
if ( session_id() != "" ) {
    session_start();
}

Basically, you need to check if a session was started before creating another one; ... more reading.

On the other hand, you chose to destroy an existing session before creating another one using session_destroy().

Conditionally formatting cells if their value equals any value of another column

No formulas required. This works on as many columns as you need, but will only compare columns in the same worksheet:

NOTE: remove any duplicates from the individual columns first!

  1. Select the columns to compare
  2. click Conditional Formatting
  3. click Highlight Cells Rules
  4. click Duplicate Values (the defaults should be OK)
  5. Duplicates are now highlighted in red

    • Bonus tip, you can filter each row by colour to either leave the unique values in the column, or leave just the duplicates.

enter image description here enter image description here

Where can I download mysql jdbc jar from?

Here's a one-liner using Maven:

mvn dependency:get -Dartifact=mysql:mysql-connector-java:5.1.38

Then, with default settings, it's available in:

$HOME/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar

Just replace the version number if you need a different one.

how to do bitwise exclusive or of two strings in python?

I've found that the ''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m)) method is pretty slow. Instead, I've been doing this:

fmt = '%dB' % len(source)
s = struct.unpack(fmt, source)
m = struct.unpack(fmt, xor_data)
final = struct.pack(fmt, *(a ^ b for a, b in izip(s, m)))

load and execute order of scripts

If you aren't dynamically loading scripts or marking them as defer or async, then scripts are loaded in the order encountered in the page. It doesn't matter whether it's an external script or an inline script - they are executed in the order they are encountered in the page. Inline scripts that come after external scripts are held until all external scripts that came before them have loaded and run.

Async scripts (regardless of how they are specified as async) load and run in an unpredictable order. The browser loads them in parallel and it is free to run them in whatever order it wants.

There is no predictable order among multiple async things. If one needed a predictable order, then it would have to be coded in by registering for load notifications from the async scripts and manually sequencing javascript calls when the appropriate things are loaded.

When a script tag is inserted dynamically, how the execution order behaves will depend upon the browser. You can see how Firefox behaves in this reference article. In a nutshell, the newer versions of Firefox default a dynamically added script tag to async unless the script tag has been set otherwise.

A script tag with async may be run as soon as it is loaded. In fact, the browser may pause the parser from whatever else it was doing and run that script. So, it really can run at almost any time. If the script was cached, it might run almost immediately. If the script takes awhile to load, it might run after the parser is done. The one thing to remember with async is that it can run anytime and that time is not predictable.

A script tag with defer waits until the entire parser is done and then runs all scripts marked with defer in the order they were encountered. This allows you to mark several scripts that depend upon one another as defer. They will all get postponed until after the document parser is done, but they will execute in the order they were encountered preserving their dependencies. I think of defer like the scripts are dropped into a queue that will be processed after the parser is done. Technically, the browser may be downloading the scripts in the background at any time, but they won't execute or block the parser until after the parser is done parsing the page and parsing and running any inline scripts that are not marked defer or async.

Here's a quote from that article:

script-inserted scripts execute asynchronously in IE and WebKit, but synchronously in Opera and pre-4.0 Firefox.

The relevant part of the HTML5 spec (for newer compliant browsers) is here. There is a lot written in there about async behavior. Obviously, this spec doesn't apply to older browsers (or mal-conforming browsers) whose behavior you would probably have to test to determine.

A quote from the HTML5 spec:

Then, the first of the following options that describes the situation must be followed:

If the element has a src attribute, and the element has a defer attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element must be added to the end of the list of scripts that will execute when the document has finished parsing associated with the Document of the parser that created the element.

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, and the element has been flagged as "parser-inserted", and the element does not have an async attribute The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

The task that the networking task source places on the task queue once the fetching algorithm has completed must set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element does not have a src attribute, and the element has been flagged as "parser-inserted", and the Document of the HTML parser or XML parser that created the script element has a style sheet that is blocking scripts The element is the pending parsing-blocking script of the Document of the parser that created the element. (There can only be one such script per Document at a time.)

Set the element's "ready to be parser-executed" flag. The parser will handle executing the script.

If the element has a src attribute, does not have an async attribute, and does not have the "force-async" flag set The element must be added to the end of the list of scripts that will execute in order as soon as possible associated with the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must run the following steps:

If the element is not now the first element in the list of scripts that will execute in order as soon as possible to which it was added above, then mark the element as ready but abort these steps without executing the script yet.

Execution: Execute the script block corresponding to the first script element in this list of scripts that will execute in order as soon as possible.

Remove the first element from this list of scripts that will execute in order as soon as possible.

If this list of scripts that will execute in order as soon as possible is still not empty and the first entry has already been marked as ready, then jump back to the step labeled execution.

If the element has a src attribute The element must be added to the set of scripts that will execute as soon as possible of the Document of the script element at the time the prepare a script algorithm started.

The task that the networking task source places on the task queue once the fetching algorithm has completed must execute the script block and then remove the element from the set of scripts that will execute as soon as possible.

Otherwise The user agent must immediately execute the script block, even if other scripts are already executing.


What about Javascript module scripts, type="module"?

Javascript now has support for module loading with syntax like this:

<script type="module">
  import {addTextToBody} from './utils.mjs';

  addTextToBody('Modules are pretty cool.');
</script>

Or, with src attribute:

<script type="module" src="http://somedomain.com/somescript.mjs">
</script>

All scripts with type="module" are automatically given the defer attribute. This downloads them in parallel (if not inline) with other loading of the page and then runs them in order, but after the parser is done.

Module scripts can also be given the async attribute which will run inline module scripts as soon as possible, not waiting until the parser is done and not waiting to run the async script in any particular order relative to other scripts.

There's a pretty useful timeline chart that shows fetch and execution of different combinations of scripts, including module scripts here in this article: Javascript Module Loading.

Can Mysql Split a column?

Here is another variant I posted on related question. The REGEX check to see if you are out of bounds is useful, so for a table column you would put it in the where clause.

SET @Array = 'one,two,three,four';
SET @ArrayIndex = 2;
SELECT CASE 
    WHEN @Array REGEXP CONCAT('((,).*){',@ArrayIndex,'}') 
    THEN SUBSTRING_INDEX(SUBSTRING_INDEX(@Array,',',@ArrayIndex+1),',',-1) 
    ELSE NULL
END AS Result;
  • SUBSTRING_INDEX(string, delim, n) returns the first n
  • SUBSTRING_INDEX(string, delim, -1) returns the last only
  • REGEXP '((delim).*){n}' checks if there are n delimiters (i.e. you are in bounds)

system("pause"); - Why is it wrong?

Here's one reason you shouldn't use it: it's going to piss off most anti-virus programs running on Windows if you're passing the program over to another machine because it's a security threat. Even if your program only consists of a simple cout << "hello world\n"; system("pause"); It's resource heavy and the program gets access to the cmd command, which anti viruses see as a threat.

Display HTML snippets in HTML

You could try:

_x000D_
_x000D_
Hello! Here is some code:_x000D_
_x000D_
<xmp>_x000D_
<div id="hello">_x000D_
_x000D_
</div>_x000D_
</xmp>
_x000D_
_x000D_
_x000D_

CSS How to set div height 100% minus nPx

Use an outer wrapper div set to 100% and then your inner wrapper div 100% should be now relative to that.

I thought for sure this used to work for me, but apparently not:

<html>
<body>
<div id="outerwrapper" style="border : 1px solid red ; height : 100%">
<div id="header" style="border : 1px solid blue ; height : 60px"></div>
<div id="wrapper"  style="border : 1px solid green ; height : 100% ; overflow : scroll ;">
  <div id="left" style="height : 100% ; width : 50% ; overflow : scroll; float : left ; clear : left ;">Some text 

on the left</div>
  <div id="right" style="height : 100% ; width 50% ; overflow : scroll; float : left ;">Some Text on the 

right</div>
</div>
</div>
</body>
</html>

Find the index of a dict within a list, by matching the dict's value

For a given iterable, more_itertools.locate yields positions of items that satisfy a predicate.

import more_itertools as mit


iterable = [
    {"id": "1234", "name": "Jason"},
    {"id": "2345", "name": "Tom"},
    {"id": "3456", "name": "Art"}
]

list(mit.locate(iterable, pred=lambda d: d["name"] == "Tom"))
# [1]

more_itertools is a third-party library that implements itertools recipes among other useful tools.

Creating a UIImage from a UIColor to use as a background image for UIButton

CGContextSetFillColorWithColor(context,[[UIColor colorWithRed:(255/255.f) green:(0/255.f) blue: (0/255.f) alpha:1] CGColor]);

twitter bootstrap autocomplete dropdown / combobox with Knockoutjs

Can i suggest http://www.jqueryscript.net/form/Twitter-Like-Mentions-Auto-Suggesting-Plugin-with-jQuery-Bootstrap-Suggest.html, works more like the twitter post suggestion where it gives you a list of users or topics based on @ or # tags,

view demo here: http://www.jqueryscript.net/demo/Twitter-Like-Mentions-Auto-Suggesting-Plugin-with-jQuery-Bootstrap-Suggest/

in this one you can easily change the @ and # to anything you want

How can I compile and run c# program without using visual studio?

If you have a project ready and just want to change some code and then build. Check out MSBuild which is located in the Microsoft.Net under windows directory.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild "C:\Projects\MyProject.csproj" /p:Configuration=Debug;DeployOnBuild=True;PackageAsSingleFile=False;outdir=C:\Projects\MyProjects\Publish\

(Please do not edit, leave as a single line)

... The line above broken up for readability

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild "C:\Projects\MyProject.csproj"
/p:Configuration=Debug;DeployOnBuild=True;PackageAsSingleFile=False;
outdir=C:\Projects\MyProjects\Publish\

phpmailer - The following SMTP Error: Data not accepted

I was using just

$mail->Body    = $message;

and for some sumbited forms the PHP was returning the error:

SMTP Error: data not accepted.SMTP server error: DATA END command failed Detail: This message was classified as SPAM and may not be delivered SMTP code: 550

I got it fixed adding this code after $mail->Body=$message :

$mail->MsgHTML = $message;
$mail->AltBody = $message;

Force "portrait" orientation mode

Set force Portrait or Landscape mode, Add lines respectively.

Import below line:

import android.content.pm.ActivityInfo;

Add Below line just above setContentView(R.layout.activity_main);

For Portrait:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//Set Portrait

For Landscap:

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//Set Landscape

This will definitely work.

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now

Just click first on that link and go to HTML page where actual downloads or mirrors are.

Its really misleading to have full link which ends in .tgz when it actually leads to HTML page where real download links are. I had this problem downloading Apache Spark and wget-ing it into Ubuntu.

https://spark.apache.org/downloads.html

How do I format a Microsoft JSON date?

The original example:

/Date(1224043200000)/  

does not reflect the formatting used by WCF when sending dates via WCF REST using the built-in JSON serialization. (at least on .NET 3.5, SP1)

I found the answer here helpful, but a slight edit to the regex is required, as it appears that the timezone GMT offset is being appended onto the number returned (since 1970) in WCF JSON.

In a WCF service I have:

[OperationContract]
[WebInvoke(
    RequestFormat = WebMessageFormat.Json,
    ResponseFormat = WebMessageFormat.Json,
    BodyStyle = WebMessageBodyStyle.WrappedRequest
    )]
ApptVisitLinkInfo GetCurrentLinkInfo( int appointmentsId );

ApptVisitLinkInfo is defined simply:

public class ApptVisitLinkInfo {
    string Field1 { get; set; }
    DateTime Field2 { get; set; }
    ...
}

When "Field2" is returned as Json from the service the value is:

/Date(1224043200000-0600)/

Notice the timezone offset included as part of the value.

The modified regex:

/\/Date\((.*?)\)\//gi

It's slightly more eager and grabs everything between the parens, not just the first number. The resulting time sinze 1970, plus timezone offset can all be fed into the eval to get a date object.

The resulting line of JavaScript for the replace is:

replace(/\/Date\((.*?)\)\//gi, "new Date($1)");

twig: IF with multiple conditions

If I recall correctly Twig doesn't support || and && operators, but requires or and and to be used respectively. I'd also use parentheses to denote the two statements more clearly although this isn't technically a requirement.

{%if ( fields | length > 0 ) or ( trans_fields | length > 0 ) %}

Expressions

Expressions can be used in {% blocks %} and ${ expressions }.

Operator    Description
==          Does the left expression equal the right expression?
+           Convert both arguments into a number and add them.
-           Convert both arguments into a number and substract them.
*           Convert both arguments into a number and multiply them.
/           Convert both arguments into a number and divide them.
%           Convert both arguments into a number and calculate the rest of the integer division.
~           Convert both arguments into a string and concatenate them.
or          True if the left or the right expression is true.
and         True if the left and the right expression is true.
not         Negate the expression.

For more complex operations, it may be best to wrap individual expressions in parentheses to avoid confusion:

{% if (foo and bar) or (fizz and (foo + bar == 3)) %}

Simple jQuery, PHP and JSONP example?

First of all you can't make a POST request using JSONP.

What basically is happening is that dynamically a script tag is inserted to load your data. Therefore only GET requests are possible.

Furthermore your data has to be wrapped in a callback function which is called after the request is finished to load the data in a variable.

This whole process is automated by jQuery for you. Just using $.getJSON on an external domain doesn't always work though. I can tell out of personal experience.

The best thing to do is adding &callback=? to you url.

At the server side you've got to make sure that your data is wrapped in this callback function.

ie.

echo $_GET['callback'] . '(' . $data . ')';

EDIT:

Don't have enough rep yet to comment on Liam's answer so therefore the solution over here.

Replace Liam's line

 echo "{'fullname' : 'Jeff Hansen'}";

with

 echo $_GET['callback'] . '(' . "{'fullname' : 'Jeff Hansen'}" . ')';

Parse JSON in TSQL

I developed my own SQL Server 2016+ JSON parser a while ago. I use this in all my projects - very good performance. I hope it can help someone else too.

Full code of the function:

ALTER FUNCTION [dbo].[SmartParseJSON] (@json NVARCHAR(MAX))
RETURNS @Parsed TABLE (Parent NVARCHAR(MAX),Path NVARCHAR(MAX),Level INT,Param NVARCHAR(4000),Type NVARCHAR(255),Value NVARCHAR(MAX),GenericPath NVARCHAR(MAX))
AS
BEGIN
    -- Author: Vitaly Borisov
    -- Create date: 2018-03-23
    ;WITH crData AS (
        SELECT CAST(NULL AS NVARCHAR(4000)) COLLATE DATABASE_DEFAULT AS [Parent]
            ,j.[Key] AS [Param],j.Value,j.Type
            ,j.[Key] AS [Path],0 AS [Level]
            ,j.[Key] AS [GenericPath]
        FROM OPENJSON(@json) j
        UNION ALL
        SELECT CAST(d.Path AS NVARCHAR(4000)) COLLATE DATABASE_DEFAULT AS [Parent]
            ,j.[Key] AS [Param],j.Value,j.Type 
            ,d.Path + CASE d.Type WHEN 5 THEN '.' WHEN 4 THEN '[' ELSE '' END + j.[Key] + CASE d.Type WHEN 4 THEN ']' ELSE '' END AS [Path]
            ,d.Level+1
            ,d.GenericPath + CASE d.Type WHEN 5 THEN '.' + j.[Key] ELSE '' END AS [GenericPath]
        FROM crData d 
        CROSS APPLY OPENJSON(d.Value) j
        WHERE ISJSON(d.Value) = 1
    )
    INSERT INTO @Parsed(Parent, Path, Level, Param, Type, Value, GenericPath)
    SELECT d.Parent,d.Path,d.Level,d.Param
        ,CASE d.Type 
            WHEN 1 THEN CASE WHEN TRY_CONVERT(UNIQUEIDENTIFIER,d.Value) IS NOT NULL THEN 'UNIQUEIDENTIFIER' ELSE 'NVARCHAR(MAX)' END 
            WHEN 2 THEN 'INT' 
            WHEN 3 THEN 'BIT' 
            WHEN 4 THEN 'Array' 
            WHEN 5 THEN 'Object' 
                ELSE 'NVARCHAR(MAX)'
         END AS [Type]
        ,CASE 
            WHEN d.Type = 3 AND d.Value = 'true' THEN '1'
            WHEN d.Type = 3 AND d.Value = 'false' THEN '0'
                ELSE d.Value
         END AS [Value]
        ,d.GenericPath
    FROM crData d
    OPTION(MAXRECURSION 1000) /*Limit to 1000 levels deep*/
    ;
    RETURN;
END
GO

Example of use:

DECLARE @json NVARCHAR(MAX) = '{"Objects":[{"SomeKeyID":1,"Value":3}],"SomeParam":"Lalala"}';
SELECT j.Parent, j.Path, j.Level, j.Param, j.Type, j.Value, j.GenericPath 
FROM dbo.SmartParseJSON(@json) j;

Example of multilevel use:

DECLARE @json NVARCHAR(MAX) = '{"Objects":[{"SomeKeyID":1,"Value":3}],"SomeParam":"Lalala"}';
DROP TABLE IF EXISTS #ParsedData;
SELECT j.Parent, j.Path, j.Level, j.Param, j.Type, j.Value, j.GenericPath 
INTO #ParsedData
FROM dbo.SmartParseJSON(@json) j;

SELECT COALESCE(p2.GenericPath,p.GenericPath) AS [GenericPath]
    ,COALESCE(p2.Param,p.Param) AS [Param]
    ,COALESCE(p2.Value,p.Value) AS [Value]
FROM #ParsedData p
LEFT JOIN #ParsedData p1 ON p1.Parent = p.Path AND p1.Level = 1
LEFT JOIN #ParsedData p2 ON p2.Parent = p1.Path AND p2.Level = 2
WHERE p.Level = 0
;
DROP TABLE IF EXISTS #ParsedData;

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

A different take with a simple jQuery plugin

Even though answers to this question are long overdue, but I'm still posting a nice solution that I came with some time ago and makes it really simple to send complex JSON to Asp.net MVC controller actions so they are model bound to whatever strong type parameters.

This plugin supports dates just as well, so they get converted to their DateTime counterpart without a problem.

You can find all the details in my blog post where I examine the problem and provide code necessary to accomplish this.

All you have to do is to use this plugin on the client side. An Ajax request would look like this:

$.ajax({
    type: "POST",
    url: "SomeURL",
    data: $.toDictionary(yourComplexJSONobject),
    success: function() { ... },
    error: function() { ... }
});

But this is just part of the whole problem. Now we are able to post complex JSON back to server, but since it will be model bound to a complex type that may have validation attributes on properties things may fail at that point. I've got a solution for it as well. My solution takes advantage of jQuery Ajax functionality where results can be successful or erroneous (just as shown in the upper code). So when validation would fail, error function would get called as it's supposed to be.

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

AngularJS passing data to $http.get request

You can pass params directly to $http.get() The following works fine

$http.get(user.details_path, {
    params: { user_id: user.id }
});

Adding a new value to an existing ENUM Type

If you are using Postgres 12 you can just run ALTER TYPE ... ADD VALUE inside of transaction (documentation).

If ALTER TYPE ... ADD VALUE (the form that adds a new value to an enum type) is executed inside a transaction block, the new value cannot be used until after the transaction has been committed.

So no hacks needed in migrations.

UPD: here is an example (thanks to Nick for it)

ALTER TYPE enum_type ADD VALUE 'new_value';

Get Value of Row in Datatable c#

for (int i=0; i<dt_pattern.Rows.Count; i++)
{
    DataRow dr = dt_pattern.Rows[i];
}

In the loop, you can now reference row i+1 (assuming there is an i+1)

How to set margin of ImageView using code, not xml

sample code is here ,its very easy

LayoutParams params1 = (LayoutParams)twoLetter.getLayoutParams();//twoletter-imageview
                params1.height = 70;
                params1.setMargins(0, 210, 0, 0);//top margin -210 here
                twoLetter.setLayoutParams(params1);//setting layout params
                twoLetter.setImageResource(R.drawable.oo);

How do I alias commands in git?

For those looking to execute shell commands in a git alias, for example:

$ git pof

In my terminal will push force the current branch to my origin repo:

[alias]
    pof = !git push origin -f $(git branch | grep \\* | cut -d ' ' -f2)

Where the

$(git branch | grep \\* | cut -d ' ' -f2)

command returns the current branch.

So this is a shortcut for manually typing the branch name:

git push origin -f <current-branch>

Which comes first in a 2D array, rows or columns?

All depends on your visualization of the array. Rows and Columns are properties of visualization (probably in your imagination) of the array, not the array itself.

It's exactly the same as asking is number "5" red or green?

I could draw it red, I could draw it greed right? Color is not an integral property of a number. In the same way representing 2D array as a grid of rows and columns is not necessary for existence of this array.

2D array has just first dimention and second dimention, everything related to visualizing those is purely your flavour.

When I have char array char[80][25], I may like to print it on console rotated so that I have 25 rows of 80 characters that fits the screen without scroll.

I'll try to provide viable example when representing 2D array as rows and columns doesn't make sense at all: Let's say I need an array of 1 000 000 000 integers. My machine has 8GB of RAM, so I have enough memory for this, but if you try executing var a = new int[1000000000], you'll most likely get OutOfMemory exception. That's because of memory fragmentation - there is no consecutive block of memory of this size. Instead you you can create 2D array 10 000 x 100 000 with your values. Logically it is 1D array, so you'd like to draw and imagine it as a single sequence of values, but due to technical implementation it is 2D.

Flutter: RenderBox was not laid out

The problem is that you are placing the ListView inside a Column/Row. The text in the exception gives a good explanation of the error.

To avoid the error you need to provide a size to the ListView inside.

I propose you this code that uses an Expanded to inform the horizontal size (maximum available) and the SizedBox (Could be a Container) for the height:

    new Row(
      children: <Widget>[
        Expanded(
          child: SizedBox(
            height: 200.0,
            child: new ListView.builder(
              scrollDirection: Axis.horizontal,
              itemCount: products.length,
              itemBuilder: (BuildContext ctxt, int index) {
                return new Text(products[index]);
              },
            ),
          ),
        ),
        new IconButton(
          icon: Icon(Icons.remove_circle),
          onPressed: () {},
        ),
      ],
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
    )

,

How to find/identify large commits in git history?

I was unable to make use of the most popular answer because the --batch-check command-line switch to Git 1.8.3 (that I have to use) does not accept any arguments. The ensuing steps have been tried on CentOS 6.5 with Bash 4.1.2

Key Concepts

In Git, the term blob implies the contents of a file. Note that a commit might change the contents of a file or pathname. Thus, the same file could refer to a different blob depending on the commit. A certain file could be the biggest in the directory hierarchy in one commit, while not in another. Therefore, the question of finding large commits instead of large files, puts matters in the correct perspective.

For The Impatient

Command to print the list of blobs in descending order of size is:

git cat-file --batch-check < <(git rev-list --all --objects  | \
awk '{print $1}')  | grep blob  | sort -n -r -k 3

Sample output:

3a51a45e12d4aedcad53d3a0d4cf42079c62958e blob 305971200
7c357f2c2a7b33f939f9b7125b155adbd7890be2 blob 289163620

To remove such blobs, use the BFG Repo Cleaner, as mentioned in other answers. Given a file blobs.txt that just contains the blob hashes, for example:

3a51a45e12d4aedcad53d3a0d4cf42079c62958e
7c357f2c2a7b33f939f9b7125b155adbd7890be2

Do:

java -jar bfg.jar -bi blobs.txt <repo_dir>

The question is about finding the commits, which is more work than finding blobs. To know, please read on.

Further Work

Given a commit hash, a command that prints hashes of all objects associated with it, including blobs, is:

git ls-tree -r --full-tree <commit_hash>

So, if we have such outputs available for all commits in the repo, then given a blob hash, the bunch of commits are the ones that match any of the outputs. This idea is encoded in the following script:

#!/bin/bash
DB_DIR='trees-db'

find_commit() {
    cd ${DB_DIR}
    for f in *; do
        if grep -q $1 ${f}; then
            echo ${f}
        fi
    done
    cd - > /dev/null
}

create_db() {
    local tfile='/tmp/commits.txt'
    mkdir -p ${DB_DIR} && cd ${DB_DIR}
    git rev-list --all > ${tfile}

    while read commit_hash; do
        if [[ ! -e ${commit_hash} ]]; then
            git ls-tree -r --full-tree ${commit_hash} > ${commit_hash}
        fi
    done < ${tfile}
    cd - > /dev/null
    rm -f ${tfile}
}

create_db

while read id; do
    find_commit ${id};
done

If the contents are saved in a file named find-commits.sh then a typical invocation will be as under:

cat blobs.txt | find-commits.sh

As earlier, the file blobs.txt lists blob hashes, one per line. The create_db() function saves a cache of all commit listings in a sub-directory in the current directory.

Some stats from my experiments on a system with two Intel(R) Xeon(R) CPU E5-2620 2.00GHz processors presented by the OS as 24 virtual cores:

  • Total number of commits in the repo = almost 11,000
  • File creation speed = 126 files/s. The script creates a single file per commit. This occurs only when the cache is being created for the first time.
  • Cache creation overhead = 87 s.
  • Average search speed = 522 commits/s. The cache optimization resulted in 80% reduction in running time.

Note that the script is single threaded. Therefore, only one core would be used at any one time.

What's the best way to center your HTML email content in the browser window (or email client preview pane)?

Align the table to center.

<table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td align="center">
            Your Content
        </td>
    </tr>
</table>

Where you have "your content" if it is a table, set it to the desired width and you will have centred content.

How do I make a Mac Terminal pop-up/alert? Applescript?

If you're using any Mac OS X version which has Notification Center, you can use the terminal-notifier gem. First install it (you may need sudo):

gem install terminal-notifier

and then simply:

terminal-notifier -message "Hello, this is my message" -title "Message Title"

See also this OS X Daily post.

How to fill the whole canvas with specific color?

If you want to do the background explicitly, you must be certain that you draw behind the current elements on the canvas.

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
// Add behind elements.
ctx.globalCompositeOperation = 'destination-over'
// Now draw!
ctx.fillStyle = "blue";
ctx.fillRect(0, 0, canvas.width, canvas.height);

error: resource android:attr/fontVariationSettings not found

error: resource android:attr/fontVariationSettings not found

I got this error when i added ButterKnife library but upgrading compileSdkVersion to 28 and targetSdk to 28 solved my issue.

Javascript getElementById based on a partial string

querySelectorAll with modern enumeration

polls = document.querySelectorAll('[id ^= "poll-"]');
Array.prototype.forEach.call(polls, callback);

function callback(element, iterator) {
    console.log(iterator, element.id);
}

The first line selects all elements which id starts with the string poll-. The second line evokes the enumeration and a callback function.

Dynamically display a CSV file as an HTML table on a web page

The previously linked solution is a horrible piece of code; nearly every line contains a bug. Use fgetcsv instead:

<?php
echo "<html><body><table>\n\n";
$f = fopen("so-csv.csv", "r");
while (($line = fgetcsv($f)) !== false) {
        echo "<tr>";
        foreach ($line as $cell) {
                echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";

Understanding the difference between Object.create() and new SomeFunction()

Here are the steps that happen internally for both calls:
(Hint: the only difference is in step 3)


new Test():

  1. create new Object() obj
  2. set obj.__proto__ to Test.prototype
  3. return Test.call(obj) || obj; // normally obj is returned but constructors in JS can return a value

Object.create( Test.prototype )

  1. create new Object() obj
  2. set obj.__proto__ to Test.prototype
  3. return obj;

So basically Object.create doesn't execute the constructor.

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

Use:

date.format("MM/DD/YYYY") or date.format("MM-DD-YYYY")}

Other Supported formats for reference:

Months:

M 1 2 ... 11 12

Mo 1st 2nd ... 11th 12th

MM 01 02 ... 11 12

MMM Jan Feb ... Nov Dec

MMMM January February ... November December

Day:

d 0 1 ... 5 6

do 0th 1st ... 5th 6th

dd Su Mo ... Fr Sa

ddd Sun Mon ... Fri Sat

dddd Sunday Monday ... Friday Saturday

Year:

YY 70 71 ... 29 30

YYYY 1970 1971 ... 2029 2030

Y 1970 1971 ... 9999 +10000 +10001

How to access pandas groupby dataframe by key

gb = df.groupby(['A'])

gb_groups = grouped_df.groups

If you are looking for selective groupby objects then, do: gb_groups.keys(), and input desired key into the following key_list..

gb_groups.keys()

key_list = [key1, key2, key3 and so on...]

for key, values in gb_groups.iteritems():
    if key in key_list:
        print df.ix[values], "\n"

Launch an app on OS X with command line

An application bundle (a .app file) is actually a bunch of directories. Instead of using open and the .app name, you can actually move in to it and start the actual binary. For instance:

$ cd /Applications/LittleSnapper.app/
$ ls
Contents
$ cd Contents/MacOS/
$ ./LittleSnapper

That is the actual binary that might accept arguments (or not, in LittleSnapper's case).

Pandas split column of lists into multiple columns

Based on the previous answers, here is another solution which returns the same result as df2.teams.apply(pd.Series) with a much faster run time:

pd.DataFrame([{x: y for x, y in enumerate(item)} for item in df2['teams'].values.tolist()], index=df2.index)

Timings:

In [1]:
import pandas as pd
d1 = {'teams': [['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],
                ['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG'],['SF', 'NYG']]}
df2 = pd.DataFrame(d1)
df2 = pd.concat([df2]*1000).reset_index(drop=True)

In [2]: %timeit df2['teams'].apply(pd.Series)

8.27 s ± 2.73 s per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [3]: %timeit pd.DataFrame([{x: y for x, y in enumerate(item)} for item in df2['teams'].values.tolist()], index=df2.index)

35.4 ms ± 5.22 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

How to restore default perspective settings in Eclipse IDE

Alt+w-->or click on window tab -->ResetPerspective

How do I disable fail_on_empty_beans in Jackson?

You can do this per class or globally, I believe.

For per class, try @JsonSerialize above class declaration.

For a mapper, here's one example:

ObjectMapper mapper = new ObjectMapper();
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
// do various things, perhaps:
String someJsonString = mapper.writeValueAsString(someClassInstance);
SomeClass someClassInstance = mapper.readValue(someJsonString, SomeClass.class)

The StackOverflow link below also has an example for a Spring project.

For REST with Jersey, I don't remember off the top off my head, but I believe it's similar.


Couple of links I dug up: (edited 1st link due to Codehaus shutting down).

Store JSON object in data attribute in HTML jQuery

For the record, I found the following code works. It enables you to retrieve the array from the data tag, push a new element on, and store it back in the data tag in the correct JSON format. The same code can therefore be used again to add further elements to the array if desired. I found that $('#my-data-div').attr('data-namesarray', names_string); correctly stores the array, but $('#my-data-div').data('namesarray', names_string); doesn't work.

<div id="my-data-div" data-namesarray='[]'></div>

var names_array = $('#my-data-div').data('namesarray');
names_array.push("Baz Smith");
var names_string = JSON.stringify(names_array);
$('#my-data-div').attr('data-namesarray', names_string);

Proper Linq where clauses

The second one would be more efficient as it just has one predicate to evaluate against each item in the collection where as in the first one, it's applying the first predicate to all items first and the result (which is narrowed down at this point) is used for the second predicate and so on. The results get narrowed down every pass but still it involves multiple passes.

Also the chaining (first method) will work only if you are ANDing your predicates. Something like this x.Age == 10 || x.Fat == true will not work with your first method.

How to make the division of 2 ints produce a float instead of another int?

You can cast the numerator or the denominator to float...

int operations usually return int, so you have to change one of the operanding numbers.

docker entrypoint running bash script gets "permission denied"

This is an old question asked two years prior to my answer, I am going to post what worked for me anyways.

In my working directory I have two files: Dockerfile & provision.sh

Dockerfile:

FROM centos:6.8

# put the script in the /root directory of the container
COPY provision.sh /root

# execute the script inside the container
RUN /root/provision.sh

EXPOSE 80

# Default command
CMD ["/bin/bash"]

provision.sh:

#!/usr/bin/env bash

yum upgrade

I was able to make the file in the docker container executable by setting the file outside the container as executable chmod 700 provision.sh then running docker build . .

Javascript, Change google map marker color

I suggest using the Google Charts API because you can specify the text, text color, fill color and outline color, all using hex color codes, e.g. #FF0000 for red. You can call it as follows:

function getIcon(text, fillColor, textColor, outlineColor) {
  if (!text) text = '•'; //generic map dot
  var iconUrl = "http://chart.googleapis.com/chart?cht=d&chdp=mapsapi&chl=pin%27i\\%27[" + text + "%27-2%27f\\hv%27a\\]h\\]o\\" + fillColor + "%27fC\\" + textColor + "%27tC\\" + outlineColor + "%27eC\\Lauto%27f\\&ext=.png";
  return iconUrl;
}

Then, when you create your marker you just set the icon property as such, where the myColor variables are hex values (minus the hash sign):

var marker = new google.maps.Marker({
  position: new google.maps.LatLng(locations[i][1], locations[i][2]),
  animation: google.maps.Animation.DROP,
  map: map,
  icon: getIcon(null, myColor, myColor2, myColor3)
});

You can use http://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=•|FF0000, which is a bit easier to decipher, as an alternate URL if you only need to set text and fill color.

khurram's answer refers to a 3rd party site that redirects to the Google Charts API. This means if that person takes down their server you're hosed. I prefer having the flexibility the Google API offers as well as the reliability of going directly to Google. Just make sure you specify a value for each of the colors or it won't work.

How to change folder with git bash?

To move from c drive to other drive(D or E)use this command----->

cd "your path" Now hit enter. Check your path using $pwd. Your path has been change from one directory to other.

Ex---> cd "D:\WEB_DEV\HTML_CSS_projects\TouristVisitors_LandingPage". note - this is my path, your path should be different.

pass parameter by link_to ruby on rails

The above did not work for me but this did

<%= link_to "text_to_show_in_url", action_controller_path(:gender => "male", :param2=> "something_else") %>

T-SQL Substring - Last 3 Characters

declare @newdata varchar(30)
set @newdata='IDS_ENUM_Change_262147_190'
select REVERSE(substring(reverse(@newdata),0,charindex('_',reverse(@newdata))))

=== Explanation ===

I found it easier to read written like this:

SELECT
    REVERSE( --4.
        SUBSTRING( -- 3.
            REVERSE(<field_name>),
            0,
            CHARINDEX( -- 2.
                '<your char of choice>',
                REVERSE(<field_name>) -- 1.
            )
        )
    )
FROM
    <table_name>
  1. Reverse the text
  2. Look for the first occurrence of a specif char (i.e. first occurrence FROM END of text). Gets the index of this char
  3. Looks at the reversed text again. searches from index 0 to index of your char. This gives the string you are looking for, but in reverse
  4. Reversed the reversed string to give you your desired substring

create table with sequence.nextval in oracle

You can use Oracle's SQL Developer tool to do that (My Oracle DB version is 11). While creating a table choose Advanced option and click on the Identity Column tab at the bottom and from there choose Column Sequence. This will generate a AUTO_INCREMENT column (Corresponding Trigger and Squence) for you.

Strip / trim all strings of a dataframe

You can try:

df[0] = df[0].str.strip()

or more specifically for all string columns

non_numeric_columns = list(set(df.columns)-set(df._get_numeric_data().columns))
df[non_numeric_columns] = df[non_numeric_columns].apply(lambda x : str(x).strip())

GUI-based or Web-based JSON editor that works like property explorer

Generally when I want to create a JSON or YAML string, I start out by building the Perl data structure, and then running a simple conversion on it. You could put a UI in front of the Perl data structure generation, e.g. a web form.

Converting a structure to JSON is very straightforward:

use strict;
use warnings;
use JSON::Any;

my $data = { arbitrary structure in here };
my $json_handler = JSON::Any->new(utf8=>1);
my $json_string = $json_handler->objToJson($data);

T-SQL split string based on delimiter

These all helped me get to this. I am still on 2012 but now have something quick that will allow me to split a string, even if string has varying numbers of delimiters, and grab the nth substring from that string. It's quick too. I know this post is old, but it took me forever to find something so hopefully this will help someone else.

CREATE FUNCTION [dbo].[SplitsByIndex]
(@separator VARCHAR(20)  = ' ', 
 @string    VARCHAR(MAX), 
 @position  INT
)
RETURNS VARCHAR(MAX)
AS
     BEGIN
     DECLARE @results TABLE
     (id   INT IDENTITY(1, 1), 
      chrs VARCHAR(8000)
     );
     DECLARE @outResult VARCHAR(8000);
     WITH X(N)
          AS (SELECT 'Table1'
              FROM(VALUES(0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0), (0)) T(C)),
          Y(N)
          AS (SELECT 'Table2'
              FROM X A1, 
                   X A2, 
                   X A3, 
                   X A4, 
                   X A5, 
                   X A6, 
                   X A7, 
                   X A8), -- Up to 16^8 = 4 billion
          T(N)
          AS (SELECT TOP (ISNULL(LEN(@string), 0)) ROW_NUMBER() OVER(
                                                   ORDER BY
              (
                  SELECT NULL
              )) - 1 N
              FROM Y),
          Delim(Pos)
          AS (SELECT t.N
              FROM T
              WHERE(SUBSTRING(@string, t.N, LEN(@separator + 'x') - 1) LIKE @separator
                    OR t.N = 0)),
          Separated(value)
          AS (SELECT SUBSTRING(@string, d.Pos + LEN(@separator + 'x') - 1, LEAD(d.Pos, 1, 2147483647) OVER(
                     ORDER BY
              (
                  SELECT NULL
              ))-d.Pos - LEN(@separator))
              FROM Delim d
              WHERE @string IS NOT NULL)
          INSERT INTO @results(chrs)
                 SELECT s.value
                 FROM Separated s
                 WHERE s.value <> @separator;
     SELECT @outResult =
     (
         SELECT chrs
         FROM @results
         WHERE id = @position
     );
     RETURN @outResult;
 END;

This can be used like this:

SELECT [dbo].[SplitsByIndex](' ',fieldname,2) 
from tablename

Set initial value in datepicker with jquery?

I'm not entirely sure if I understood your question, but it seems that you're trying to set value for an input type Date.

If you want to set a value for an input type 'Date', then it has to be formatted as "yyyy-MM-dd" (Note: capital MM for Month, lower case mm for minutes). Otherwise, it will clear the value and leave the datepicker empty.

Let's say you have a button called "DateChanger" and you want to set your datepicker to "22 Dec 2012" when you click it.

<script>
    $(document).ready(function () {
        $('#DateChanger').click(function() {
             $('#dtFrom').val("2012-12-22");
        });
    });
</script>
<input type="date" id="dtFrom" name="dtFrom" />
<button id="DateChanger">Click</button>

Remember to include JQuery reference.

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

That combination of username, host, and password is not allowed to connect to the server. Verify the permission tables (reloading grants if required) on the server and that you're connecting to the correct server.

C# "No suitable method found to override." -- but there is one

Probably your base class is a different one with the same name. Check by right click on the extended class and go to the definition. Check if the class is correct one.

Get names of all files from a folder with Ruby

this code returns only filenames with their extension (without a global path)

Dir.children("/path/to/search/")

What in layman's terms is a Recursive Function using PHP

This is a very simple example of factorial with Recursion:

Factorials are a very easy maths concept. They are written like 5! and this means 5 * 4 * 3 * 2 * 1. So 6! is 720 and 4! is 24.

function factorial($number) { 

    if ($number < 2) { 
        return 1; 
    } else { 
        return ($number * factorial($number-1)); 
    } 
}

hope this is usefull for you. :)

Finding the position of the max element

You can use max_element() function to find the position of the max element.

int main()
{
    int num, arr[10];
    int x, y, a, b;

    cin >> num;

    for (int i = 0; i < num; i++)
    {
        cin >> arr[i];
    }

    cout << "Max element Index: " << max_element(arr, arr + num) - arr;

    return 0;
}

C compiling - "undefined reference to"?

Make sure your declare the tolayer5 function as a prototype, or define the full function definition, earlier in the file where you use it.

How to show alert message in mvc 4 controller?

TempData["msg"] = "<script>alert('Change succesfully');</script>";
@Html.Raw(TempData["msg"])

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

Using NickW's suggestion, I was able to get this working using things = JSON.stringify({ 'things': things }); Here is the complete code.

$(document).ready(function () {
    var things = [
        { id: 1, color: 'yellow' },
        { id: 2, color: 'blue' },
        { id: 3, color: 'red' }
    ];      

    things = JSON.stringify({ 'things': things });

    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '/Home/PassThings',
        data: things,
        success: function () {          
            $('#result').html('"PassThings()" successfully called.');
        },
        failure: function (response) {          
            $('#result').html(response);
        }
    }); 
});


public void PassThings(List<Thing> things)
{
    var t = things;
}

public class Thing
{
    public int Id { get; set; }
    public string Color { get; set; }
}

There are two things I learned from this:

  1. The contentType and dataType settings are absolutely necessary in the ajax() function. It won't work if they are missing. I found this out after much trial and error.

  2. To pass in an array of objects to an MVC controller method, simply use the JSON.stringify({ 'things': things }) format.

I hope this helps someone else!

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

For anyone looking for a UI option using IIS Manager.

  1. Open the Website in IIS Manager
  2. Go To Request Filtering and open the Request Filtering Window.
  3. Go to Verbs Tab and Add HTTP Verbs to "Allow Verb..." or "Deny Verb...". This allow to add the HTTP Verbs in the "Deny Verb.." Collection.

Request Filtering Window in IIS Manager Request Filtering Window in IIS Manager

Add Verb... or Deny Verb... enter image description here

Good font for code presentations?

I use DejaVu Sans Mono at Size 16.

UPDATE : I have switched to Envy Code R for coding and Anonymous Pro for terminal

Android - Get value from HashMap

HashMap<String, String> meMap = new HashMap<String, String>();
meMap.put("Color1", "Red");
meMap.put("Color2", "Blue");
meMap.put("Color3", "Green");
meMap.put("Color4", "White");

Iterator myVeryOwnIterator = meMap.values().iterator();
while(myVeryOwnIterator.hasNext()) {
    Toast.makeText(getBaseContext(), myVeryOwnIterator.next(), Toast.LENGTH_SHORT).show();
}

What is the difference between C++ and Visual C++?

C++ is a programming language and Visual C++ is an IDE for developing with languages such as C and C++.

VC++ contains tools for, amongst others, developing against the .net framework and the Windows API.

How to refresh app upon shaking the device?

I am developing a motion-detection and shake-detection app for my university project.

Besides the original target of the application, I am splitting the library part (responsible for motion and shake detection) from the app. The code is free, available on SourceForge with the project name "BenderCatch". Documentation I am producing will be ready around mid-september. http://sf.net/projects/bendercatch

It uses a more precise way to detect shake: watches BOTH the difference of force between SensorEvents AND the oscillations present in X and Y axis when you perform a shake. It can even make a sound (or vibrate) on each oscillation of the shake.

Feel free to ask me more by e-mail at raffaele [at] terzigno [dot] com

Why in C++ do we use DWORD rather than unsigned int?

SDK developers prefer to define their own types using typedef. This allows changing underlying types only in one place, without changing all client code. It is important to follow this convention. DWORD is unlikely to be changed, but types like DWORD_PTR are different on different platforms, like Win32 and x64. So, if some function has DWORD parameter, use DWORD and not unsigned int, and your code will be compiled in all future windows headers versions.