Programs & Examples On #Pdl

PDL ("Perl Data Language") gives standard Perl the ability to compactly store and speedily manipulate the large N-dimensional data arrays which are the bread and butter of scientific computing.

How to run html file using node js

Move your HTML file in a folder "www". Create a file "server.js" with code :

var express = require('express');
var app = express();

app.use(express.static(__dirname + '/www'));

app.listen('3000');
console.log('working on 3000');

After creation of file, run the command "node server.js"

Cannot open Windows.h in Microsoft Visual Studio

The right combination of Windows SDK Version and Platform Toolset needs to be selected Depends of course what toolset you have currently installed

SDK Version and Platform Toolset

Save the plots into a PDF

import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
    plt.figure(figsize=(3, 3))
    plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
    plt.title('Page One')
    pdf.savefig()  # saves the current figure into a pdf page
    plt.close()

    plt.rc('text', usetex=True)
    plt.figure(figsize=(8, 6))
    x = np.arange(0, 5, 0.1)
    plt.plot(x, np.sin(x), 'b-')
    plt.title('Page Two')
    pdf.savefig()
    plt.close()

    plt.rc('text', usetex=False)
    fig = plt.figure(figsize=(4, 5))
    plt.plot(x, x*x, 'ko')
    plt.title('Page Three')
    pdf.savefig(fig)  # or you can pass a Figure object to pdf.savefig
    plt.close()

    # We can also set the file's metadata via the PdfPages object:
    d = pdf.infodict()
    d['Title'] = 'Multipage PDF Example'
    d['Author'] = u'Jouni K. Sepp\xe4nen'
    d['Subject'] = 'How to create a multipage pdf file and set its metadata'
    d['Keywords'] = 'PdfPages multipage keywords author title subject'
    d['CreationDate'] = datetime.datetime(2009, 11, 13)
    d['ModDate'] = datetime.datetime.today()

Confused about UPDLOCK, HOLDLOCK

Why would UPDLOCK block selects? The Lock Compatibility Matrix clearly shows N for the S/U and U/S contention, as in No Conflict.

As for the HOLDLOCK hint the documentation states:

HOLDLOCK: Is equivalent to SERIALIZABLE. For more information, see SERIALIZABLE later in this topic.

...

SERIALIZABLE: ... The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level...

and the Transaction Isolation Level topic explains what SERIALIZABLE means:

No other transactions can modify data that has been read by the current transaction until the current transaction completes.

Other transactions cannot insert new rows with key values that would fall in the range of keys read by any statements in the current transaction until the current transaction completes.

Therefore the behavior you see is perfectly explained by the product documentation:

  • UPDLOCK does not block concurrent SELECT nor INSERT, but blocks any UPDATE or DELETE of the rows selected by T1
  • HOLDLOCK means SERALIZABLE and therefore allows SELECTS, but blocks UPDATE and DELETES of the rows selected by T1, as well as any INSERT in the range selected by T1 (which is the entire table, therefore any insert).
  • (UPDLOCK, HOLDLOCK): your experiment does not show what would block in addition to the case above, namely another transaction with UPDLOCK in T2:
    SELECT * FROM dbo.Test WITH (UPDLOCK) WHERE ...
  • TABLOCKX no need for explanations

The real question is what are you trying to achieve? Playing with lock hints w/o an absolute complete 110% understanding of the locking semantics is begging for trouble...

After OP edit:

I would like to select rows from a table and prevent the data in that table from being modified while I am processing it.

The you should use one of the higher transaction isolation levels. REPEATABLE READ will prevent the data you read from being modified. SERIALIZABLE will prevent the data you read from being modified and new data from being inserted. Using transaction isolation levels is the right approach, as opposed to using query hints. Kendra Little has a nice poster exlaining the isolation levels.

Register DLL file on Windows Server 2008 R2

You need the full path to the regsvr32 so %windir$\system32\regsvr32 <*.dll>

Python base64 data decode

Interesting if maddening puzzle...but here's the best I could get:

The data seems to repeat every 8 bytes or so.

import struct
import base64

target = \
r'''Q5YACgAAAABDlgAbAAAAAEOWAC0AAAAAQ5YAPwAAAABDlgdNAAAAAEOWB18AAAAAQ5YH 
[snip.]
ZAAAAABExxniAAAAAETH/rQAAAAARMf/MwAAAABEx/+yAAAAAETIADEAAAAA''' 

data = base64.b64decode(target)

cleaned_data = []
struct_format = ">ff"
for i in range(len(data) // 8):
   cleaned_data.append(struct.unpack_from(struct_format, data, 8*i))

That gives output like the following (a sampling of lines from the first 100 or so):

(300.00030517578125, 0.0)
(300.05975341796875, 241.93943786621094)
(301.05612182617187, 0.0)
(301.05667114257812, 8.7439727783203125)
(326.9617919921875, 0.0)
(326.96826171875, 0.0)
(328.34432983398438, 280.55218505859375)

That first number does seem to monotonically increase through the entire set. If you plot it:

import matplotlib.pyplot as plt
f, ax = plt.subplots()
ax.plot(*zip(*cleaned_data))

enter image description here

format = 'hhhh' (possibly with various paddings/directions (e.g. '<hhhh', '<xhhhh') also might be worth a look (again, random lines):

(-27069, 2560, 0, 0)
(-27069, 8968, 0, 0)
(-27069, 13576, 3139, -18487)
(-27069, 18184, 31043, -5184)
(-27069, -25721, -25533, -8601)
(-27069, -7289, 0, 0)
(-25533, 31066, 0, 0)
(-25533, -29350, 0, 0)
(-25533, 25179, 0, 0)
(-24509, -1888, 0, 0)
(-24509, -4447, 0, 0)
(-23741, -14725, 32067, 27475)
(-23741, -3973, 0, 0)
(-23485, 4908, -29629, -20922)

SELECT FOR UPDATE with SQL Server

Try using:

SELECT * FROM <tablename> WITH ROWLOCK XLOCK HOLDLOCK

This should make the lock exclusive and hold it for the duration of the transaction.

Where/How to getIntent().getExtras() in an Android Fragment?

What I tend to do, and I believe this is what Google intended for developers to do too, is to still get the extras from an Intent in an Activity and then pass any extra data to fragments by instantiating them with arguments.

There's actually an example on the Android dev blog that illustrates this concept, and you'll see this in several of the API demos too. Although this specific example is given for API 3.0+ fragments, the same flow applies when using FragmentActivity and Fragment from the support library.

You first retrieve the intent extras as usual in your activity and pass them on as arguments to the fragment:

public static class DetailsActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // (omitted some other stuff)

        if (savedInstanceState == null) {
            // During initial setup, plug in the details fragment.
            DetailsFragment details = new DetailsFragment();
            details.setArguments(getIntent().getExtras());
            getSupportFragmentManager().beginTransaction().add(
                    android.R.id.content, details).commit();
        }
    }
}

In stead of directly invoking the constructor, it's probably easier to use a static method that plugs the arguments into the fragment for you. Such a method is often called newInstance in the examples given by Google. There actually is a newInstance method in DetailsFragment, so I'm unsure why it isn't used in the snippet above...

Anyways, all extras provided as argument upon creating the fragment, will be available by calling getArguments(). Since this returns a Bundle, its usage is similar to that of the extras in an Activity.

public static class DetailsFragment extends Fragment {
    /**
     * Create a new instance of DetailsFragment, initialized to
     * show the text at 'index'.
     */
    public static DetailsFragment newInstance(int index) {
        DetailsFragment f = new DetailsFragment();

        // Supply index input as an argument.
        Bundle args = new Bundle();
        args.putInt("index", index);
        f.setArguments(args);

        return f;
    }

    public int getShownIndex() {
        return getArguments().getInt("index", 0);
    }

    // (other stuff omitted)

}

Deploying my application at the root in Tomcat

In my server I am using this and root autodeploy works just fine:

   <Host name="mysite" autoDeploy="true" appBase="webapps" unpackWARs="true" deployOnStartup="true">
        <Alias>www.mysite.com</Alias>
        <Valve className="org.apache.catalina.valves.RemoteIpValve" protocolHeader="X-Forwarded-Proto"/>
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="mysite_access_log." suffix=".txt"
           pattern="%h %l %u %t &quot;%r&quot; %s %b"/>
        <Context path="/mysite" docBase="mysite" reloadable="true"/>
    </Host>

How do I get the coordinate position after using jQuery drag and drop?

Had the same problem. My solution is next:

$("#element").droppable({
    drop: function( event, ui ) {

        // position of the draggable minus position of the droppable
        // relative to the document
        var $newPosX = ui.offset.left - $(this).offset().left;
        var $newPosY = ui.offset.top - $(this).offset().top;

    }
});

update query with join on two tables

update addresses set cid=id where id in (select id from customers)

Reflection - get attribute name and value on property

If you just want one specific Attribute value For instance Display Attribute you can use the following code:

var pInfo = typeof(Book).GetProperty("Name")
                             .GetCustomAttribute<DisplayAttribute>();
var name = pInfo.Name;

How do I efficiently iterate over each entry in a Java Map?

public class abcd{
    public static void main(String[] args)
    {
       Map<Integer, String> testMap = new HashMap<Integer, String>();
        testMap.put(10, "a");
        testMap.put(20, "b");
        testMap.put(30, "c");
        testMap.put(40, "d");
        for (Integer key:testMap.keySet()) {
            String value=testMap.get(key);
            System.out.println(value);
        }
    }
}

OR

public class abcd {
    public static void main(String[] args)
    {
       Map<Integer, String> testMap = new HashMap<Integer, String>();
        testMap.put(10, "a");
        testMap.put(20, "b");
        testMap.put(30, "c");
        testMap.put(40, "d");
        for (Entry<Integer, String> entry : testMap.entrySet()) {
            Integer key=entry.getKey();
            String value=entry.getValue();
        }
    }
}

How to implement an STL-style iterator and avoid common pitfalls?

The iterator_facade documentation from Boost.Iterator provides what looks like a nice tutorial on implementing iterators for a linked list. Could you use that as a starting point for building a random-access iterator over your container?

If nothing else, you can take a look at the member functions and typedefs provided by iterator_facade and use it as a starting point for building your own.

JQuery add class to parent element

$(this.parentNode).addClass('newClass');

Animate element to auto height with jQuery

Here's one that works with BORDER-BOX ...

Hi guys. Here is a jQuery plugin I wrote to do the same, but also account for the height differences that will occur when you have box-sizing set to border-box.

I also included a "yShrinkOut" plugin that hides the element by shrinking it along the y-axis.


// -------------------------------------------------------------------
// Function to show an object by allowing it to grow to the given height value.
// -------------------------------------------------------------------
$.fn.yGrowIn = function (growTo, duration, whenComplete) {

    var f = whenComplete || function () { }, // default function is empty
        obj = this,
        h = growTo || 'calc', // default is to calculate height
        bbox = (obj.css('box-sizing') == 'border-box'), // check box-sizing
        d = duration || 200; // default duration is 200 ms

    obj.css('height', '0px').removeClass('hidden invisible');
    var padTop = 0 + parseInt(getComputedStyle(obj[0], null).paddingTop), // get the starting padding-top
        padBottom = 0 + parseInt(getComputedStyle(obj[0], null).paddingBottom), // get the starting padding-bottom
        padLeft = 0 + parseInt(getComputedStyle(obj[0], null).paddingLeft), // get the starting padding-left
        padRight = 0 + parseInt(getComputedStyle(obj[0], null).paddingRight); // get the starting padding-right
    obj.css('padding-top', '0px').css('padding-bottom', '0px'); // Set the padding to 0;

    // If no height was given, then calculate what the height should be.
    if(h=='calc'){ 
        var p = obj.css('position'); // get the starting object "position" style. 
        obj.css('opacity', '0'); // Set the opacity to 0 so the next actions aren't seen.
        var cssW = obj.css('width') || 'auto'; // get the CSS width if it exists.
        var w = parseInt(getComputedStyle(obj[0], null).width || 0) // calculate the computed inner-width with regard to box-sizing.
            + (!bbox ? parseInt((getComputedStyle(obj[0], null).borderRightWidth || 0)) : 0) // remove these values if using border-box.
            + (!bbox ? parseInt((getComputedStyle(obj[0], null).borderLeftWidth || 0)) : 0) // remove these values if using border-box.
            + (!bbox ? (padLeft + padRight) : 0); // remove these values if using border-box.
        obj.css('position', 'fixed'); // remove the object from the flow of the document.
        obj.css('width', w); // make sure the width remains the same. This prevents content from throwing off the height.
        obj.css('height', 'auto'); // set the height to auto for calculation.
        h = parseInt(0); // calculate the auto-height
        h += obj[0].clientHeight // calculate the computed height with regard to box-sizing.
            + (bbox ? parseInt((getComputedStyle(obj[0], null).borderTopWidth || 0)) : 0) // add these values if using border-box.
            + (bbox ? parseInt((getComputedStyle(obj[0], null).borderBottomWidth || 0)) : 0) // add these values if using border-box.
            + (bbox ? (padTop + padBottom) : 0); // add these values if using border-box.
        obj.css('height', '0px').css('position', p).css('opacity','1'); // reset the height, position, and opacity.
    };

    // animate the box. 
    //  Note: the actual duration of the animation will change depending on the box-sizing.
    //      e.g., the duration will be shorter when using padding and borders in box-sizing because
    //      the animation thread is growing (or shrinking) all three components simultaneously.
    //      This can be avoided by retrieving the calculated "duration per pixel" based on the box-sizing type,
    //      but it really isn't worth the effort.
    obj.animate({ 'height': h, 'padding-top': padTop, 'padding-bottom': padBottom }, d, 'linear', (f)());
};

// -------------------------------------------------------------------
// Function to hide an object by shrinking its height to zero.
// -------------------------------------------------------------------
$.fn.yShrinkOut = function (d,whenComplete) {
    var f = whenComplete || function () { },
        obj = this,
        padTop = 0 + parseInt(getComputedStyle(obj[0], null).paddingTop),
        padBottom = 0 + parseInt(getComputedStyle(obj[0], null).paddingBottom),
        begHeight = 0 + parseInt(obj.css('height'));

    obj.animate({ 'height': '0px', 'padding-top': 0, 'padding-bottom': 0 }, d, 'linear', function () {
            obj.addClass('hidden')
                .css('height', 0)
                .css('padding-top', padTop)
                .css('padding-bottom', padBottom);
            (f)();
        });
};

Any of the parameters I used can be omitted or set to null in order to accept default values. The parameters I used:

  • growTo: If you want to override all the calculations and set the CSS height to which the object will grow, use this parameter.
  • duration: The duration of the animation (obviously).
  • whenComplete: A function to run when the animation is complete.

Easiest way to convert month name to month number in JS ? (Jan = 01)

Just for fun I did this:

function getMonthFromString(mon){
   return new Date(Date.parse(mon +" 1, 2012")).getMonth()+1
}

Bonus: it also supports full month names :-D Or the new improved version that simply returns -1 - change it to throw the exception if you want (instead of returning -1):

function getMonthFromString(mon){

   var d = Date.parse(mon + "1, 2012");
   if(!isNaN(d)){
      return new Date(d).getMonth() + 1;
   }
   return -1;
 }

Sry for all the edits - getting ahead of myself

Can you write virtual functions / methods in Java?

From wikipedia

In Java, all non-static methods are by default "virtual functions." Only methods marked with the keyword final, which cannot be overridden, along with private methods, which are not inherited, are non-virtual.

Storing data into list with class

You need to create an instance of the class to add:

lstemail.Add(new EmailData
                 {
                     FirstName = "JOhn",
                     LastName = "Smith",
                     Location = "Los Angeles"
                 });

See How to: Initialize Objects by Using an Object Initializer (C# Programming Guide)


Alternatively you could declare a constructor for you EmailData object and use that to create the instance.

OpenSSL Command to check if a server is presenting a certificate

I was getting the below as well trying to get out to github.com as our proxy re-writes the HTTPS connection with their self-signed cert:

no peer certificate available No client certificate CA names sent

In my output there was also:

Protocol : TLSv1.3

I added -tls1_2 and it worked fine and now I can see which CA it is using on the outgoing request. e.g.:
openssl s_client -connect github.com:443 -tls1_2

Mock HttpContext.Current in Test Init Method

Below Test Init will also do the job.

[TestInitialize]
public void TestInit()
{
  HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
  YourControllerToBeTestedController = GetYourToBeTestedController();
}

ScriptManager.RegisterStartupScript code not working - why?

Try this code...

ScriptManager.RegisterClientScriptBlock(UpdatePanel1, this.GetType(), "script", "alert('Hi');", true);

Where UpdatePanel1 is the id for Updatepanel on your page

Calling a Sub in VBA

Try -

Call CatSubProduktAreakum(Stattyp, Daty + UBound(SubCategories) + 2)

As for the reason, this from MSDN via this question - What does the Call keyword do in VB6?

You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded.

Difference between ProcessBuilder and Runtime.exec()

Yes there is a difference.

  • The Runtime.exec(String) method takes a single command string that it splits into a command and a sequence of arguments.

  • The ProcessBuilder constructor takes a (varargs) array of strings. The first string is the command name and the rest of them are the arguments. (There is an alternative constructor that takes a list of strings, but none that takes a single string consisting of the command and arguments.)

So what you are telling ProcessBuilder to do is to execute a "command" whose name has spaces and other junk in it. Of course, the operating system can't find a command with that name, and the command execution fails.

Can scripts be inserted with innerHTML?

Here a solution that does not use eval, and works with scripts, linked scripts , as well as with modules.

The function accepts 3 parameters :

  • html : String with the html code to insert
  • dest : reference to the target element
  • append : boolean flag to enable appending at the end of the target element html
function insertHTML(html, dest, append=false){
    // if no append is requested, clear the target element
    if(!append) dest.innerHTML = '';
    // create a temporary container and insert provided HTML code
    let container = document.createElement('div');
    container.innerHTML = html;
    // cache a reference to all the scripts in the container
    let scripts = container.querySelectorAll('script');
    // get all child elements and clone them in the target element
    let nodes = container.childNodes;
    for( let i=0; i< nodes.length; i++) dest.appendChild( nodes[i].cloneNode(true) );
    // force the found scripts to execute...
    for( let i=0; i< scripts.length; i++){
        let script = document.createElement('script');
        script.type = scripts[i].type || 'text/javascript';
        if( scripts[i].hasAttribute('src') ) script.src = scripts[i].src;
        script.innerHTML = scripts[i].innerHTML;
        document.head.appendChild(script);
        document.head.removeChild(script);
    }
    // done!
    return true;
}

VBA test if cell is in a range

If the two ranges to be tested (your given cell and your given range) are not in the same Worksheet, then Application.Intersect throws an error. Thus, a way to avoid it is with something like

Sub test_inters(rng1 As Range, rng2 As Range)
    If (rng1.Parent.Name = rng2.Parent.Name) Then
        Dim ints As Range
        Set ints = Application.Intersect(rng1, rng2)
        If (Not (ints Is Nothing)) Then
            ' Do your job
        End If
    End If
End Sub

Does a foreign key automatically create an index?

Not to my knowledge. A foreign key only adds a constraint that the value in the child key also be represented somewhere in the parent column. It's not telling the database that the child key also needs to be indexed, only constrained.

When to use dynamic vs. static libraries

Others have adequately explained what a static library is, but I'd like to point out some of the caveats of using static libraries, at least on Windows:

  • Singletons: If something needs to be global/static and unique, be very careful about putting it in a static library. If multiple DLLs are linked against that static library they will each get their own copy of the singleton. However, if your application is a single EXE with no custom DLLs, this may not be a problem.

  • Unreferenced code removal: When you link against a static library, only the parts of the static library that are referenced by your DLL/EXE will get linked into your DLL/EXE.

    For example, if mylib.lib contains a.obj and b.obj and your DLL/EXE only references functions or variables from a.obj, the entirety of b.obj will get discarded by the linker. If b.obj contains global/static objects, their constructors and destructors will not get executed. If those constructors/destructors have side effects, you may be disappointed by their absence.

    Likewise, if the static library contains special entrypoints you may need to take care that they are actually included. An example of this in embedded programming (okay, not Windows) would be an interrupt handler that is marked as being at a specific address. You also need to mark the interrupt handler as an entrypoint to make sure it doesn't get discarded.

    Another consequence of this is that a static library may contain object files that are completely unusable due to unresolved references, but it won't cause a linker error until you reference a function or variable from those object files. This may happen long after the library is written.

  • Debug symbols: You may want a separate PDB for each static library, or you may want the debug symbols to be placed in the object files so that they get rolled into the PDB for the DLL/EXE. The Visual C++ documentation explains the necessary options.

  • RTTI: You may end up with multiple type_info objects for the same class if you link a single static library into multiple DLLs. If your program assumes that type_info is "singleton" data and uses &typeid() or type_info::before(), you may get undesirable and surprising results.

How to install trusted CA certificate on Android device?

The guide linked here will probably answer the original question without the need for programming a custom SSL connector.

Found a very detailed how-to guide on importing root certificates that actually steps you through installing trusted CA certificates on different versions of Android devices (among other devices).

Basically you'll need to:

  1. Download: the cacerts.bks file from your phone.

    adb pull /system/etc/security/cacerts.bks cacerts.bks

  2. Download the .crt file from the certifying authority you want to allow.

  3. Modify the cacerts.bks file on your computer using the BouncyCastle Provider

  4. Upload the cacerts.bks file back to your phone and reboot.

Here is a more detailed step by step to update earlier android phones: How to update HTTPS security certificate authority keystore on pre-android-4.0 device

What is the difference between required and ng-required?

AngularJS form elements look for the required attribute to perform validation functions. ng-required allows you to set the required attribute depending on a boolean test (for instance, only require field B - say, a student number - if the field A has a certain value - if you selected "student" as a choice)

As an example, <input required> and <input ng-required="true"> are essentially the same thing

If you are wondering why this is this way, (and not just make <input required="true"> or <input required="false">), it is due to the limitations of HTML - the required attribute has no associated value - its mere presence means (as per HTML standards) that the element is required - so angular needs a way to set/unset required value (required="false" would be invalid HTML)

How do I view the SQL generated by the Entity Framework?

Well, I am using Express profiler for that purpose at the moment, the drawback is that it only works for MS SQL Server. You can find this tool here: https://expressprofiler.codeplex.com/

How to make spring inject value into a static field

You have two possibilities:

  1. non-static setter for static property/field;
  2. using org.springframework.beans.factory.config.MethodInvokingFactoryBean to invoke a static setter.

In the first option you have a bean with a regular setter but instead setting an instance property you set the static property/field.

public void setTheProperty(Object value) {
    foo.bar.Class.STATIC_VALUE = value;
}

but in order to do this you need to have an instance of a bean that will expose this setter (its more like an workaround).

In the second case it would be done as follows:

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="foo.bar.Class.setTheProperty"/>
    <property name="arguments">
        <list>
            <ref bean="theProperty"/>
        </list>
   </property>
</bean>

On you case you will add a new setter on the Utils class:

public static setDataBaseAttr(Properties p)

and in your context you will configure it with the approach exemplified above, more or less like:

<bean class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
    <property name="staticMethod" value="foo.bar.Utils.setDataBaseAttr"/>
    <property name="arguments">
        <list>
            <ref bean="dataBaseAttr"/>
        </list>
   </property>
</bean>

Android: how to handle button click

Question#1 - These are the only way to handle view clicks.

Question#2 -
Option#1/Option#4 - There's not much difference between option#1 and option#4. The only difference I see is in one case activity is implementing the OnClickListener, whereas, in the other case, there'd be an anonymous implementation.

Option#2 - In this method an anonymous class will be generated. This method is a bit cumborsome, as, you'd need to do it multiple times, if you have multiple buttons. For Anonymous classes, you have to be careful for handling memory leaks.

Option#3 - Though, this is a easy way. Usually, Programmers try not to use any method until they write it, and hence this method is not widely used. You'd see mostly people use Option#4. Because it is cleaner in term of code.

Delete dynamically-generated table row using jQuery

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

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

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

How to get the client IP address in PHP

$_SERVER['REMOTE_ADDR'] may not actually contain real client IP addresses, as it will give you a proxy address for clients connected through a proxy, for example. That may well be what you really want, though, depending what your doing with the IPs. Someone's private RFC1918 address may not do you any good if you're say, trying to see where your traffic is originating from, or remembering what IP the user last connected from, where the public IP of the proxy or NAT gateway might be the more appropriate to store.

There are several HTTP headers like X-Forwarded-For which may or may not be set by various proxies. The problem is that those are merely HTTP headers which can be set by anyone. There's no guarantee about their content. $_SERVER['REMOTE_ADDR'] is the actual physical IP address that the web server received the connection from and that the response will be sent to. Anything else is just arbitrary and voluntary information. There's only one scenario in which you can trust this information: you are controlling the proxy that sets this header. Meaning only if you know 100% where and how the header was set should you heed it for anything of importance.

Having said that, here's some sample code:

if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
    $ip = $_SERVER['HTTP_CLIENT_IP'];
} elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else {
    $ip = $_SERVER['REMOTE_ADDR'];
}

Editor's note: Using the above code has security implications. The client can set all HTTP header information (ie. $_SERVER['HTTP_...) to any arbitrary value it wants. As such it's far more reliable to use $_SERVER['REMOTE_ADDR'], as this cannot be set by the user.

From: http://roshanbh.com.np/2007/12/getting-real-ip-address-in-php.html

Call an activity method from a fragment

This is From Fragment class...

((KidsStoryDashboard)getActivity()).values(title_txt,bannerImgUrl);

This Code From Activity Class...

 public void values(String title_txts, String bannerImgUrl) {
    if (!title_txts.isEmpty()) {

//Do something to set text 
    }
    imageLoader.displayImage(bannerImgUrl, htab_header_image, doption);
}

Android get image path from drawable as string

I think you cannot get it as String but you can get it as int by get resource id:

int resId = this.getResources().getIdentifier("imageNameHere", "drawable", this.getPackageName());

Copying sets Java

Java 8+:

Set<String> copy = new HashSet<>(mySet); 

PHP cURL HTTP PUT

Just been doing that myself today... here is code I have working for me...

$data = array("a" => $a);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "PUT");
curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));

$response = curl_exec($ch);

if (!$response) 
{
    return false;
}

src: http://www.lornajane.net/posts/2009/putting-data-fields-with-php-curl

Reset push notification settings for app

After hours of searching, and no luck with the suggestions above, this worked like to a charm for 3.x+

override func viewDidLoad() {
        super.viewDidLoad()


            requestAuthorization()

}

func requestAuthorization() {

        if #available(iOS 10.0, *) {

            UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
                print("Access granted: \(granted.description)")
            }

        } else {
            // Fallback on earlier versions
        }

    }

Ways to iterate over a list in Java

You could always switch out the first and third examples with a while loop and a little more code. This gives you the advantage of being able to use the do-while:

int i = 0;
do{
 E element = list.get(i);
 i++;
}
while (i < list.size());

Of course, this kind of thing might cause a NullPointerException if the list.size() returns 0, becuase it always gets executed at least once. This can be fixed by testing if element is null before using its attributes / methods tho. Still, it's a lot simpler and easier to use the for loop

Why would I use dirname(__FILE__) in an include or include_once statement?

I might have even a simpler explanation to this question compared to the accepted answer so I'm going to give it a go: Assume this is the structure of the files and directories of a project:

Project root directory:
                       file1.php
                       file3.php
                       dir1/
                            file2.php

(dir1 is a directory and file2.php is inside it)

And this is the content of each of the three files above:

//file1.php:
<?php include "dir1/file2.php"

//file2.php:
<?php include "../file3.php"

//file3.php:
<?php echo "Hello, Test!";

Now run file1.php and try to guess what should happen. You might expect to see "Hello, Test!", however, it won't be shown! What you'll get instead will be an error indicating that the file you have requested(file3.php) does not exist!

The reason is that, inside file1.php when you include file2.php, the content of it is getting copied and then pasted back directly into file1.php which is inside the root directory, thus this part "../file3.php" runs from the root directory and thus goes one directory up the root! (and obviously it won't find the file3.php).

Now, what should we do ?!

Relative paths of course have the problem above, so we have to use absolute paths. However, absolute paths have also one problem. If you (for example) copy the root folder (containing your whole project) and paste it in anywhere else on your computer, the paths will be invalid from that point on! And that'll be a REAL MESS!

So we kind of need paths that are both absolute and dynamic(Each file dynamically finds the absolute path of itself wherever we place it)!

The way we do that is by getting help from PHP, and dirname() is the function to go for, which gives the absolute path to the directory in which a file exists in. And each file name could also be easily accessed using the __FILE__ constant. So dirname(__FILE__) would easily give you the absolute (while dynamic!) path to the file we're typing in the above code. Now move your whole project to a new place, or even a new system, and tada! it works!

So now if we turn the project above to this:

//file1.php:
<?php include(dirname(__FILE__)."/dir1/file2.php");

//file2.php:
<?php include(dirname(__FILE__)."/../file3.php");

//file3.php:
<?php echo "Hello, Test!";

if you run it, you'll see the almighty Hello, Test!! (hopefully, if you've not done anything else wrong).

It's also worth mentioning that from PHP5, a nicer way(with regards to readability and preventing eye boilage!) has been provided by PHP as well which is the constant __DIR__ which does exactly the same thing as dirname(__FILE__)!

Hope that helps.

How do I best silence a warning about unused variables?

First off the warning is generated by the variable definition in the source file not the header file. The header can stay pristine and should, since you might be using something like doxygen to generate the API-documentation.

I will assume that you have completely different implementation in source files. In these cases you can either comment out the offending parameter or just write the parameter.

Example:

func(int a, int b)
{
    b;
    foo(a);
}

This might seem cryptic, so defined a macro like UNUSED. The way MFC did it is:

#ifdef _DEBUG
#define UNUSED(x)
#else
#define UNUSED(x) x
#endif

Like this you see the warning still in debug builds, might be helpful.

What determines the monitor my app runs on?

Important note: If you remember the position of your application and shutdown and then start up again at that position, keep in mind that the user's monitor configuration may have changed while your application was closed.

Laptop users, for example, frequently change their display configuration. When docked there may be a 2nd monitor that disappears when undocked. If the user closes an application that was running on the 2nd monitor and the re-opens the application when the monitor is disconnected, restoring the window to the previous coordinates will leave it completely off-screen.

To figure out how big the display really is, check out GetSystemMetrics.

Installing a specific version of angular with angular cli

npm i -g @angular/[email protected]

x,y,z--> ur desired version number

convert '1' to '0001' in JavaScript

I use the following object:

function Padder(len, pad) {
  if (len === undefined) {
    len = 1;
  } else if (pad === undefined) {
    pad = '0';
  }

  var pads = '';
  while (pads.length < len) {
    pads += pad;
  }

  this.pad = function (what) {
    var s = what.toString();
    return pads.substring(0, pads.length - s.length) + s;
  };
}

With it you can easily define different "paddings":

var zero4 = new Padder(4);
zero4.pad(12); // "0012"
zero4.pad(12345); // "12345"
zero4.pad("xx"); // "00xx"
var x3 = new Padder(3, "x");
x3.pad(12); // "x12"

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

Solution is you need to add json file extension type in MIME Types

Method 1

Go to IIS, Select your application and Find MIME Types

enter image description here

Click on Add from Right panel

File Name Extension = .json

MIME Type = application/json

enter image description here

After adding .json file type in MIME Types, Restart IIS and try to access json file


Method 2

Go to web.config of that application and add this lines in it

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

BATCH file asks for file or folder

The real trick is: Use a Backslash at the end of the target path where to copy the file. The /Y is for overwriting existing files, if you want no warnings.

Example:

xcopy /Y "C:\file\from\here.txt" "C:\file\to\here\"

Why am I getting an error "Object literal may only specify known properties"?

As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.

Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash is incorrect and should have been callbackOnLocationHash (note the mis-spelling of "Location").

This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.

Example:

interface TextOptions {
    alignment?: string;
    color?: string;
    padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'

But I meant to do that

There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes

Type-checking only some properties

Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v or v as T) do not check for extra properties, so you can use them in place of a type annotation:

interface Options {
    x?: string;
    y?: number;
}

// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;

These properties and maybe more

Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking

Before

interface Model {
  name: string;
}
function createModel(x: Model) { ... }

// Error
createModel({name: 'hello', length: 100});

After

interface Model {
  name: string;
  [others: string]: any;
}
function createModel(x: Model) { ... }

// OK
createModel({name: 'hello', length: 100});

This is a dog or a cat or a horse, not sure yet

interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }

let x: Animal;
if(...) {
  x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
  x = { move: 'catwalk', meow: 'mrar' };
} else {
  x = { move: 'gallop', neigh: 'wilbur' };
}

Two good solutions come to mind here

Specify a closed set for x

// Removes all errors
let x: Dog|Cat|Horse;

or Type assert each thing

// For each initialization
  x = { move: 'doggy paddle', woof: 'bark' } as Dog;

This type is sometimes open and sometimes not

A clean solution to the "data model" problem using intersection types:

interface DataModelOptions {
  name?: string;
  id?: number;
}
interface UserProperties {
  [key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
 /* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
 /* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });

See also https://github.com/Microsoft/TypeScript/issues/3755

Node.js: Difference between req.query[] and req.params

Suppose you have defined your route name like this:

https://localhost:3000/user/:userid

which will become:

https://localhost:3000/user/5896544

Here, if you will print: request.params

{
userId : 5896544
}

so

request.params.userId = 5896544

so request.params is an object containing properties to the named route

and request.query comes from query parameters in the URL eg:

https://localhost:3000/user?userId=5896544 

request.query

{

userId: 5896544

}

so

request.query.userId = 5896544

Android View shadow

Create card_background.xml in the res/drawable folder with the following code:

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

<item>
    <shape android:shape="rectangle">
        <solid android:color="#BDBDBD"/>
        <corners android:radius="5dp"/>
    </shape>
</item>

<item
    android:left="0dp"
    android:right="0dp"
    android:top="0dp"
    android:bottom="2dp">
    <shape android:shape="rectangle">
        <solid android:color="#ffffff"/>
        <corners android:radius="5dp"/>
    </shape>
</item>
</layer-list>

Then add the following code to the element to which you want the card layout

android:background="@drawable/card_background"

the following line defines the color of the shadow for the card

<solid android:color="#BDBDBD"/>

How to read a value from the Windows registry

Since Windows >=Vista/Server 2008, RegGetValue is available, which is a safer function than RegQueryValueEx. No need for RegOpenKeyEx, RegCloseKey or NUL termination checks of string values (REG_SZ, REG_MULTI_SZ, REG_EXPAND_SZ).

#include <iostream>
#include <string>
#include <exception>
#include <windows.h>

/*! \brief                          Returns a value from HKLM as string.
    \exception  std::runtime_error  Replace with your error handling.
*/
std::wstring GetStringValueFromHKLM(const std::wstring& regSubKey, const std::wstring& regValue)
{
    size_t bufferSize = 0xFFF; // If too small, will be resized down below.
    std::wstring valueBuf; // Contiguous buffer since C++11.
    valueBuf.resize(bufferSize);
    auto cbData = static_cast<DWORD>(bufferSize * sizeof(wchar_t));
    auto rc = RegGetValueW(
        HKEY_LOCAL_MACHINE,
        regSubKey.c_str(),
        regValue.c_str(),
        RRF_RT_REG_SZ,
        nullptr,
        static_cast<void*>(valueBuf.data()),
        &cbData
    );
    while (rc == ERROR_MORE_DATA)
    {
        // Get a buffer that is big enough.
        cbData /= sizeof(wchar_t);
        if (cbData > static_cast<DWORD>(bufferSize))
        {
            bufferSize = static_cast<size_t>(cbData);
        }
        else
        {
            bufferSize *= 2;
            cbData = static_cast<DWORD>(bufferSize * sizeof(wchar_t));
        }
        valueBuf.resize(bufferSize);
        rc = RegGetValueW(
            HKEY_LOCAL_MACHINE,
            regSubKey.c_str(),
            regValue.c_str(),
            RRF_RT_REG_SZ,
            nullptr,
            static_cast<void*>(valueBuf.data()),
            &cbData
        );
    }
    if (rc == ERROR_SUCCESS)
    {
        cbData /= sizeof(wchar_t);
        valueBuf.resize(static_cast<size_t>(cbData - 1)); // remove end null character
        return valueBuf;
    }
    else
    {
        throw std::runtime_error("Windows system error code: " + std::to_string(rc));
    }
}

int main()
{
    std::wstring regSubKey;
#ifdef _WIN64 // Manually switching between 32bit/64bit for the example. Use dwFlags instead.
    regSubKey = L"SOFTWARE\\WOW6432Node\\Company Name\\Application Name\\";
#else
    regSubKey = L"SOFTWARE\\Company Name\\Application Name\\";
#endif
    std::wstring regValue(L"MyValue");
    std::wstring valueFromRegistry;
    try
    {
        valueFromRegistry = GetStringValueFromHKLM(regSubKey, regValue);
    }
    catch (std::exception& e)
    {
        std::cerr << e.what();
    }
    std::wcout << valueFromRegistry;
}

Its parameter dwFlags supports flags for type restriction, filling the value buffer with zeros on failure (RRF_ZEROONFAILURE) and 32/64bit registry access (RRF_SUBKEY_WOW6464KEY, RRF_SUBKEY_WOW6432KEY) for 64bit programs.

Python 3 Online Interpreter / Shell

Ideone supports Python 2.6 and Python 3

Is it possible to cherry-pick a commit from another git repository?

You can do it, but it requires two steps. Here's how:

git fetch <remote-git-url> <branch> && git cherry-pick FETCH_HEAD

Replace <remote-git-url> with the url or path to the repository you want cherry-pick from.

Replace <branch> with the branch or tag name you want to cherry-pick from the remote repository.

You can replace FETCH_HEAD with a git SHA from the branch.

Updated: modified based on @pkalinow's feedback.

How can I align the columns of tables in Bash?

To have the exact same output as you need, you need to format the file like that :

a very long string..........\t     112232432\t     anotherfield\n
a smaller string\t      123124343\t     anotherfield\n

And then using :

$ column -t -s $'\t' FILE
a very long string..........  112232432  anotherfield
a smaller string              123124343  anotherfield

ArrayAdapter in android to create simple listview

You don't need to use id for textview. You can learn more from android arrayadapter. The below code initializes the arrayadapter.

ArrayAdapter arrayAdapter = new ArrayAdapter(this, R.layout.single_item, eatables);

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

  1. Download gecko driver from the seleniumhq website (Now it is on GitHub and you can download it from Here) .
    1. You will have a zip (or tar.gz) so extract it.
    2. After extraction you will have geckodriver.exe file (appropriate executable in linux).
    3. Create Folder in C: named SeleniumGecko (Or appropriate)
    4. Copy and Paste geckodriver.exe to SeleniumGecko
    5. Set the path for gecko driver as below

.

System.setProperty("webdriver.gecko.driver","C:\\geckodriver-v0.10.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();

#1062 - Duplicate entry for key 'PRIMARY'

I solved it by changing the "lock" property from "shared" to "exclusive":

ALTER TABLE `table` 
CHANGE COLUMN `ID` `ID` INT(11) NOT NULL AUTO_INCREMENT COMMENT '' , LOCK = EXCLUSIVE;

Enums in Javascript with ES6

Here is my approach, including some helper methods

export default class Enum {

    constructor(name){
        this.name = name;
    }

    static get values(){
        return Object.values(this);
    }

    static forName(name){
        for(var enumValue of this.values){
            if(enumValue.name === name){
                return enumValue;
            }
        }
        throw new Error('Unknown value "' + name + '"');
    }

    toString(){
        return this.name;
    }
}

-

import Enum from './enum.js';

export default class ColumnType extends Enum {  

    constructor(name, clazz){
        super(name);        
        this.associatedClass = clazz;
    }
}

ColumnType.Integer = new ColumnType('Integer', Number);
ColumnType.Double = new ColumnType('Double', Number);
ColumnType.String = new ColumnType('String', String);

Comparing mongoose _id and strings

ObjectIDs are objects so if you just compare them with == you're comparing their references. If you want to compare their values you need to use the ObjectID.equals method:

if (results.userId.equals(AnotherMongoDocument._id)) {
    ...
}

How to store an array into mysql?

You can always serialize the array and store that in the database.
PHP Serialize

You can then unserialize the array when needed.

Center text in table cell

How about simply (Please note, come up with a better name for the class name this is simply an example):

.centerText{
   text-align: center;
}


<div>
   <table style="width:100%">
   <tbody>
   <tr>
      <td class="centerText">Cell 1</td>
      <td>Cell 2</td>
    </tr>
    <tr>
      <td class="centerText">Cell 3</td>
      <td>Cell 4</td>
    </tr>
    </tbody>
    </table>
</div>

Example here

You can place the css in a separate file, which is recommended. In my example, I created a file called styles.css and placed my css rules in it. Then include it in the html document in the <head> section as follows:

<head>
    <link href="styles.css" rel="stylesheet" type="text/css">
</head>

The alternative, not creating a seperate css file, not recommended at all... Create <style> block in your <head> in the html document. Then just place your rules there.

<head>
 <style type="text/css">
   .centerText{
       text-align: center;
    }
 </style>
</head>

How to replace url parameter with javascript/jquery?

Here is modified stenix's code, it's not perfect but it handles cases where there is a param in url that contains provided parameter, like:

/search?searchquery=text and 'query' is provided.

In this case searchquery param value is changed.

Code:

function replaceUrlParam(url, paramName, paramValue){
    var pattern = new RegExp('(\\?|\\&)('+paramName+'=).*?(&|$)')
    var newUrl=url
    if(url.search(pattern)>=0){
        newUrl = url.replace(pattern,'$1$2' + paramValue + '$3');
    }
    else{
        newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
    }
    return newUrl
}

Setting a max character length in CSS

This post is for a CSS solution, but the post is quite old, so just in case others stumble on this and are using a modern JS framework such as Angular 4+, there is a simple way to do this through Angular Pipes without having to mess around with CSS.

There are probably "React" or "Vue" ways of doing this as well. This is just to showcase how it could be done within a framework.

truncate-text.pipe.ts

/**
 * Helper to truncate text using JS in view only.
 *
 * This is pretty difficult to do reliably with CSS, especially when there are
 * multiple lines.
 *
 * Example: {{ value | truncateText:maxLength }} or {{ value | truncateText:45 }}
 *
 * If maxLength is not provided, the value will be returned without any truncating. If the
 * text is shorter than the maxLength, the text will be returned untouched. If the text is greater
 * than the maxLength, the text will be returned with 3 characters less than the max length plus
 * some ellipsis at the end to indicate truncation.
 *
 * For example: some really long text I won't bother writing it all ha...
 */
@Pipe({ name: 'truncateText' })
export class TruncateTextPipe implements PipeTransform {
  transform(value: string, ...args: any[]): any {
    const maxLength = args[0]
    const maxLengthNotProvided = !maxLength
    const isShorterThanMaximumLength = value.length < maxLength
    if (maxLengthNotProvided || isShorterThanMaximumLength) {
      return value
    }
    const shortenedString = value.substr(0, maxLength - 3)
    return `${shortenedString}...`
  }
}

app.component.html

<h1>{{ application.name | truncateText:45 }}</h1>

ansible: lineinfile for several lines?

I was able to do that by using \n in the line parameter.

It is specially useful if the file can be validated, and adding a single line generates an invalid file.

In my case, I was adding AuthorizedKeysCommand and AuthorizedKeysCommandUser to sshd_config, with the following command:

- lineinfile: dest=/etc/ssh/sshd_config line='AuthorizedKeysCommand /etc/ssh/ldap-keys\nAuthorizedKeysCommandUser nobody' validate='/usr/sbin/sshd -T -f %s'

Adding only one of the options generates a file that fails validation.

Getting the filenames of all files in a folder

Here's how to look in the documentation.

First, you're dealing with IO, so look in the java.io package.

There are two classes that look interesting: FileFilter and FileNameFilter. When I clicked on the first, it showed me that there was a a listFiles() method in the File class. And the documentation for that method says:

Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.

Scrolling up in the File JavaDoc, I see the constructors. And that's really all I need to be able to create a File instance and call listFiles() on it. Scrolling still further, I can see some information about how files are named in different operating systems.

SQL DELETE with JOIN another table for WHERE condition

How about:

DELETE guide_category  
  WHERE id_guide_category IN ( 

        SELECT id_guide_category 
          FROM guide_category AS gc
     LEFT JOIN guide AS g 
            ON g.id_guide = gc.id_guide
         WHERE g.title IS NULL

  )

VNC viewer with multiple monitors

Real VNC Viewer (5.0.3) - Free :

Options->Expert->UseAllMonitors = True

Using CSS how to change only the 2nd column of a table

To change only the second column of a table use the following:

General Case:

table td + td{  /* this will go to the 2nd column of a table directly */

background:red

}

Your case:

.countTable table table td + td{ 

background: red

}

Note: this works for all browsers (Modern and old ones) that's why I added my answer to an old question

Is there a regular expression to detect a valid regular expression?

Though it is perfectly possible to use a recursive regex as MizardX has posted, for this kind of things it is much more useful a parser. Regexes were originally intended to be used with regular languages, being recursive or having balancing groups is just a patch.

The language that defines valid regexes is actually a context free grammar, and you should use an appropriate parser for handling it. Here is an example for a university project for parsing simple regexes (without most constructs). It uses JavaCC. And yes, comments are in Spanish, though method names are pretty self-explanatory.

SKIP :
{
    " "
|   "\r"
|   "\t"
|   "\n"
}
TOKEN : 
{
    < DIGITO: ["0" - "9"] >
|   < MAYUSCULA: ["A" - "Z"] >
|   < MINUSCULA: ["a" - "z"] >
|   < LAMBDA: "LAMBDA" >
|   < VACIO: "VACIO" >
}

IRegularExpression Expression() :
{
    IRegularExpression r; 
}
{
    r=Alternation() { return r; }
}

// Matchea disyunciones: ER | ER
IRegularExpression Alternation() :
{
    IRegularExpression r1 = null, r2 = null; 
}
{
    r1=Concatenation() ( "|" r2=Alternation() )?
    { 
        if (r2 == null) {
            return r1;
        } else {
            return createAlternation(r1,r2);
        } 
    }
}

// Matchea concatenaciones: ER.ER
IRegularExpression Concatenation() :
{
    IRegularExpression r1 = null, r2 = null; 
}
{
    r1=Repetition() ( "." r2=Repetition() { r1 = createConcatenation(r1,r2); } )*
    { return r1; }
}

// Matchea repeticiones: ER*
IRegularExpression Repetition() :
{
    IRegularExpression r; 
}
{
    r=Atom() ( "*" { r = createRepetition(r); } )*
    { return r; }
}

// Matchea regex atomicas: (ER), Terminal, Vacio, Lambda
IRegularExpression Atom() :
{
    String t;
    IRegularExpression r;
}
{
    ( "(" r=Expression() ")" {return r;}) 
    | t=Terminal() { return createTerminal(t); }
    | <LAMBDA> { return createLambda(); }
    | <VACIO> { return createEmpty(); }
}

// Matchea un terminal (digito o minuscula) y devuelve su valor
String Terminal() :
{
    Token t;
}
{
    ( t=<DIGITO> | t=<MINUSCULA> ) { return t.image; }
}

Count immediate child div elements using jQuery

$('#foo').children('div').length

C# getting its own class name

Get Current class name of Asp.net

string CurrentClass = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name.ToString();

case in sql stored procedure on SQL Server

CASE isn't used for flow control... for this, you would need to use IF...

But, there's a set-based solution to this problem instead of the procedural approach:

UPDATE tblEmployee
SET 
  InOffice = CASE WHEN @NewStatus = 'InOffice' THEN -1 ELSE InOffice END,
  OutOffice = CASE WHEN @NewStatus = 'OutOffice' THEN -1 ELSE OutOffice END,
  Home = CASE WHEN @NewStatus = 'Home' THEN -1 ELSE Home END
WHERE EmpID = @EmpID

Note that the ELSE will preserves the original value if the @NewStatus condition isn't met.

The tilde operator in Python

I was solving this leetcode problem and I came across this beautiful solution by a user named Zitao Wang.

The problem goes like this for each element in the given array find the product of all the remaining numbers without making use of divison and in O(n) time

The standard solution is:

Pass 1: For all elements compute product of all the elements to the left of it
Pass 2: For all elements compute product of all the elements to the right of it
        and then multiplying them for the final answer 

His solution uses only one for loop by making use of. He computes the left product and right product on the fly using ~

def productExceptSelf(self, nums):
    res = [1]*len(nums)
    lprod = 1
    rprod = 1
    for i in range(len(nums)):
        res[i] *= lprod
        lprod *= nums[i]
        res[~i] *= rprod
        rprod *= nums[~i]
    return res

Syntax for a single-line Bash infinite while loop

It's also possible to use sleep command in while's condition. Making one-liner looking more clean imho.

while sleep 2; do echo thinking; done

Entity Framework Migrations renaming tables and columns

Nevermind. I was making this way more complicated than it really needed to be.

This was all that I needed. The rename methods just generate a call to the sp_rename system stored procedure and I guess that took care of everything, including the foreign keys with the new column name.

public override void Up()
{
    RenameTable("ReportSections", "ReportPages");
    RenameTable("ReportSectionGroups", "ReportSections");
    RenameColumn("ReportPages", "Group_Id", "Section_Id");
}

public override void Down()
{
    RenameColumn("ReportPages", "Section_Id", "Group_Id");
    RenameTable("ReportSections", "ReportSectionGroups");
    RenameTable("ReportPages", "ReportSections");
}

How do I print colored output with Python 3?

For windows just do this:

import os
os.system("color 01")
print('hello friends')

Where it says "01" that is saying background black, and text color blue. Go into CMD Prompt and type color help for a list of colors.

How to mount a single file in a volume

The way that worked for me is to use a bind mount

  version: "3.7"    
  services:
  app:
    image: app:latest
    volumes:
      - type: bind
        source: ./sourceFile.yaml
        target: /location/targetFile.yaml

Thanks mike breed for the answer over at: Mount single file from volume using docker-compose

You need to use the "long syntax" to express a bind mount using the volumes key: https://docs.docker.com/compose/compose-file/#long-syntax-3

Java getHours(), getMinutes() and getSeconds()

For a time difference, note that the calendar starts at 01.01.1970, 01:00, not at 00:00. If you're using java.util.Date and java.text.SimpleDateFormat, you will have to compensate for 1 hour:

long start = System.currentTimeMillis();
long end = start + (1*3600 + 23*60 + 45) * 1000 + 678; // 1 h 23 min 45.678 s
Date timeDiff = new Date(end - start - 3600000); // compensate for 1h in millis
SimpleDateFormat timeFormat = new SimpleDateFormat("H:mm:ss.SSS");
System.out.println("Duration: " + timeFormat.format(timeDiff));

This will print:

Duration: 1:23:45.678

Pandas read in table without headers

Previous answers were good and correct, but in my opinion, an extra names parameter will make it perfect, and it should be the recommended way, especially when the csv has no headers.

Solution

Use usecols and names parameters

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])

Additional reading

or use header=None to explicitly tells people that the csv has no headers (anyway both lines are identical)

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)

So that you can retrieve your data by

# with `names` parameter
df['colA']
df['colB'] 

instead of

# without `names` parameter
df[0]
df[1]

Explain

Based on read_csv, when names are passed explicitly, then header will be behaving like None instead of 0, so one can skip header=None when names exist.

What is __stdcall?

__stdcall is the calling convention used for the function. This tells the compiler the rules that apply for setting up the stack, pushing arguments and getting a return value.

There are a number of other calling conventions, __cdecl, __thiscall, __fastcall and the wonderfully named __declspec(naked). __stdcall is the standard calling convention for Win32 system calls.

Wikipedia covers the details.

It primarily matters when you are calling a function outside of your code (e.g. an OS API) or the OS is calling you (as is the case here with WinMain). If the compiler doesn't know the correct calling convention then you will likely get very strange crashes as the stack will not be managed correctly.

How to pip or easy_install tkinter on Windows

When you install python for Windows, use the standard option or install everything it asks. I got the error because I deselected tcl.

CSS scale down image to fit in containing div, without specifing original size

I use:

object-fit: cover;
-o-object-fit: cover;

to place images in a container with a fixed height and width, this also works great for my sliders. It will however cut of parts of the image depending on it's.

PHP __get and __set magic methods

Drop the public $bar; declaration and it should work as expected.

How to store an output of shell script to a variable in Unix?

Two simple examples to capture output the pwd command:

$ b=$(pwd)
$ echo $b
/home/user1

or

$ a=`pwd`
$ echo $a
/home/user1

The first way is preferred. Note that there can't be any spaces after the = for this to work.

Example using a short script:

#!/bin/bash

echo "hi there"

then:

$ ./so.sh
hi there
$ a=$(so.sh)
$ echo $a
hi there

In general a more flexible approach would be to return an exit value from the command and use it for further processing, though sometimes we just may want to capture the simple output from a command.

How to do a HTTP HEAD request from the windows command line?

1) See the headers that come back from a GET request

wget --server-response -O /dev/null http://....

1a) Save the headers that come back from a GET request

wget --server-response -o headers -O /dev/null http://....

2) See the headers that come back from GET HEAD request

wget --server-response --spider http://....

2a) Save the headers that come back from a GET HEAD request

wget --server-response --spider -o headers http://....
  • David

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

CREATE FUNCTION [dbo].[_ICAN_FN_IntToTime](@Num INT)
  RETURNS NVARCHAR(13)
AS
-------------------------------------------------------------------------------------------------------------------
--INVENTIVE:Keyvan ARYAEE-MOEEN
-------------------------------------------------------------------------------------------------------------------
  BEGIN
    DECLARE @Hour VARCHAR(10)=CAST(@Num/3600 AS  VARCHAR(2))
    DECLARE @Minute VARCHAR(10)=CAST((@Num-@Hour*3600)/60 AS  VARCHAR(2))
    DECLARE @Time VARCHAR(13)=CASE WHEN @Hour<10 THEN '0'+@Hour ELSE @Hour END+':'+CASE WHEN @Minute<10 THEN '0'+@Minute ELSE @Minute END+':00.000'
    RETURN @Time
  END
-------------------------------------------------------------------------------------------------------------------
--SELECT dbo._ICAN_FN_IntToTime(25500)
-------------------------------------------------------------------------------------------------------------------

How do I use checkboxes in an IF-THEN statement in Excel VBA 2010?

I found that I could access the checkbox directly using Worksheets("SheetName").CB_Checkboxname.value directly without relating to additional objects.

isPrime Function for Python Language

With n**.5, you are not squaring n, but taking the square root.

Consider the number 20; the integer factors are 1, 2, 4, 5, 10, and 20. When you divide 20 by 2 and get 10, you know that it is also divisible by 10, without having to check. When you divide it by 4 and get 5, you know it is divisible by both 4 and 5, without having to check for 5.

After reaching this halfway point in the factors, you will have no more numbers to check which you haven't already recognized as factors earlier. Therefore, you only need to go halfway to see if something is prime, and this halfway point can be found by taking the number's square root.

Also, the reason 1 isn't a prime number is because prime numbers are defined as having 2 factors, 1 and itself. i.e 2 is 1*2, 3 is 1*3, 5 is 1*5. But 1 (1*1) only has 1 factor, itself. Therefore, it doesn't meet this definition.

How to select last two characters of a string

var member = "my name is maanu";

var answer=member.substring(0,member.length - 2);

alert(answer);

NodeJS/express: Cache and 304 status code

Try using private browsing in Safari or deleting your entire cache/cookies.

I've had some similar issues using chrome when the browser thought it had the website in its cache but actually had not.

The part of the http request that makes the server respond a 304 is the etag. Seems like Safari is sending the right etag without having the corresponding cache.

Pretty printing XML in Python

I found this question while looking for "how to pretty print html"

Using some of the ideas in this thread I adapted the XML solutions to work for XML or HTML:

from xml.dom.minidom import parseString as string_to_dom

def prettify(string, html=True):
    dom = string_to_dom(string)
    ugly = dom.toprettyxml(indent="  ")
    split = list(filter(lambda x: len(x.strip()), ugly.split('\n')))
    if html:
        split = split[1:]
    pretty = '\n'.join(split)
    return pretty

def pretty_print(html):
    print(prettify(html))

When used this is what it looks like:

html = """\
<div class="foo" id="bar"><p>'IDK!'</p><br/><div class='baz'><div>
<span>Hi</span></div></div><p id='blarg'>Try for 2</p>
<div class='baz'>Oh No!</div></div>
"""

pretty_print(html)

Which returns:

<div class="foo" id="bar">
  <p>'IDK!'</p>
  <br/>
  <div class="baz">
    <div>
      <span>Hi</span>
    </div>
  </div>
  <p id="blarg">Try for 2</p>
  <div class="baz">Oh No!</div>
</div>

The Eclipse executable launcher was unable to locate its companion launcher jar windows

just add -vm C:\Java\JDK\1.6\bin\javaw.exe before -vmarg in eclipse.ini this works for me.Hope this will help you good luck...

Accessing elements by type in javascript

If you are lucky and need to care only for recent browsers, you can use:

document.querySelectorAll('input[type=text]')

"recent" means not IE6 and IE7

String MinLength and MaxLength validation don't work (asp.net mvc)

MaxLength is used for the Entity Framework to decide how large to make a string value field when it creates the database.

From MSDN:

Specifies the maximum length of array or string data allowed in a property.

StringLength is a data annotation that will be used for validation of user input.

From MSDN:

Specifies the minimum and maximum length of characters that are allowed in a data field.

Non Customized

Use [String Length]

[RegularExpression(@"^.{3,}$", ErrorMessage = "Minimum 3 characters required")]
[Required(ErrorMessage = "Required")]
[StringLength(30, MinimumLength = 3, ErrorMessage = "Maximum 30 characters")]

30 is the Max Length
Minimum length = 3

Customized StringLengthAttribute Class

public class MyStringLengthAttribute : StringLengthAttribute
{
    public MyStringLengthAttribute(int maximumLength)
        : base(maximumLength)
    {
    }

    public override bool IsValid(object value)
    {
        string val = Convert.ToString(value);
        if (val.Length < base.MinimumLength)
            base.ErrorMessage = "Minimum length should be 3";
        if (val.Length > base.MaximumLength)
            base.ErrorMessage = "Maximum length should be 6";
        return base.IsValid(value);
    }
}

public class MyViewModel
{
    [MyStringLength(6, MinimumLength = 3)]
    public String MyProperty { get; set; }
}

How to put a UserControl into Visual Studio toolBox

There are a couple of ways.

  1. In your original Project, choose File|Export template
    Then select ItemTemplate and follow the wizard.

  2. Move your UserControl to a separate ClassLibrary (and fix namespaces etc).
    Add a ref to the classlibrary from Projects that need it. Don't bother with the GAC or anything, just the DLL file.

I would not advice putting a UserControl in the normal ToolBox, but it can be done. See the answer from @Arseny

Calling the base constructor in C#

public class MyException : Exception
{
    public MyException() { }
    public MyException(string msg) : base(msg) { }
    public MyException(string msg, Exception inner) : base(msg, inner) { }
}

What is the argument for printf that formats a long?

It depends, if you are referring to unsigned long the formatting character is "%lu". If you're referring to signed long the formatting character is "%ld".

Is there a better way to run a command N times in bash?

All of the existing answers appear to require bash, and don't work with a standard BSD UNIX /bin/sh (e.g., ksh on OpenBSD).

The below code should work on any BSD:

$ echo {1..4}
{1..4}
$ seq 4
sh: seq: not found
$ for i in $(jot 4); do echo e$i; done
e1
e2
e3
e4
$

How can I add NSAppTransportSecurity to my info.plist file?

In mac shell command line , use the following command:

plutil -insert NSAppTransportSecurity -xml "<array><string> hidden </string></array>" [location of your xcode project]/Info.plist 

The command will add all the necessary values into your plist file.

Difference between string object and string literal

A String literal is a Java language concept. This is a String literal:

"a String literal"

A String object is an individual instance of the java.lang.String class.

String s1 = "abcde";
String s2 = new String("abcde");
String s3 = "abcde";

All are valid, but have a slight difference. s1 will refer to an interned String object. This means, that the character sequence "abcde" will be stored at a central place, and whenever the same literal "abcde" is used again, the JVM will not create a new String object but use the reference of the cached String.

s2 is guranteed to be a new String object, so in this case we have:

s1 == s2 // is false
s1 == s3 // is true
s1.equals(s2) // is true

Java - ignore exception and continue

LDAPService should contain method like LDAPService.isExists(String userName) use it to prevent NPE to be thrown. If is not - this could be a workaround, but use Logging to post some warning..

How to change sender name (not email address) when using the linux mail command for autosending mail?

mail -s "$(echo -e "This is the subject\nFrom: Paula <[email protected]>\n
Reply-to: [email protected]\nContent-Type: text/html\n")" 
[email protected] < htmlFileMessage.txt

the above is my solution..just replace the "Paula" with any name you want e.g Johny Bravo..any extra headers can be added just after the from and before the reply to...just make sure you know your headers syntax before adding them....this worked perfectly for me.

How can I count text lines inside an DOM element? Can I?

Check out the function getClientRects() which can be used to count the number of lines in an element. Here is an example of how to use it.

var message_lines = $("#message_container")[0].getClientRects();

It returns a javascript DOM object. The amount of lines can be known by doing this:

var amount_of_lines = message_lines.length;

It can return the height of each line, and more. See the full array of things it can do by adding this to your script, then looking in your console log.

console.log("");
console.log("message_lines");
console.log(".............................................");
console.dir(message_lines);
console.log("");

Though a few things to note is it only works if the containing element is inline, however you can surround the containing inline element with a block element to control the width like so:

<div style="width:300px;" id="block_message_container">
<div style="display:inline;" id="message_container">
..Text of the post..
</div>
</div>

Though I don't recommend hard coding the style like that. It's just for example purposes.

What is the difference between class and instance methods?

All the technical details have been nicely covered in the other answers. I just want to share a simple analogy that I think nicely illustrates the difference between a class and an instance:

enter image description here

A class is like the blueprint of a house: You only have one blueprint and (usually) you can't do that much with the blueprint alone.

enter image description here

An instance (or an object) is the actual house that you build based on the blueprint: You can build lots of houses from the same blueprint. You can then paint the walls a different color in each of the houses, just as you can independently change the properties of each instance of a class without affecting the other instances.

Show div on scrollDown after 800px

You've got a few things going on there. One, why a class? Do you actually have multiple of these on the page? The CSS suggests you can't. If not you should use an ID - it's faster to select both in CSS and jQuery:

<div id=bottomMenu>You read it all.</div>

Second you've got a few crazy things going on in that CSS - in particular the z-index is supposed to just be a number, not measured in pixels. It specifies what layer this tag is on, where each higher number is closer to the user (or put another way, on top of/occluding tags with lower z-indexes).

The animation you're trying to do is basically .fadeIn(), so just set the div to display: none; initially and use .fadeIn() to animate it:

$('#bottomMenu').fadeIn(2000);

.fadeIn() works by first doing display: (whatever the proper display property is for the tag), opacity: 0, then gradually ratcheting up the opacity.

Full working example:

http://jsfiddle.net/b9chris/sMyfT/

CSS:

#bottomMenu {
    display: none;
    position: fixed;
    left: 0; bottom: 0;
    width: 100%; height: 60px;
    border-top: 1px solid #000;
    background: #fff;
    z-index: 1;
}

JS:

var $win = $(window);

function checkScroll() {
    if ($win.scrollTop() > 100) {
        $win.off('scroll', checkScroll);
        $('#bottomMenu').fadeIn(2000);
    }
}

$win.scroll(checkScroll);

How do I reference a cell within excel named range?

There are a couple different ways I would do this:

1) Mimic Excel Tables Using with a Named Range

In your example, you named the range A10:A20 "Age". Depending on how you wanted to reference a cell in that range you could either (as @Alex P wrote) use =INDEX(Age, 5) or if you want to reference a cell in range "Age" that is on the same row as your formula, just use:

=INDEX(Age, ROW()-ROW(Age)+1)

This mimics the relative reference features built into Excel tables but is an alternative if you don't want to use a table.

If the named range is an entire column, the formula simplifies as:

=INDEX(Age, ROW())

2) Use an Excel Table

Alternatively if you set this up as an Excel table and type "Age" as the header title of the Age column, then your formula in columns to the right of the Age column can use a formula like this:

=[@[Age]]

How to fix Subversion lock error

Refresh/Cleanup did not work for me. What worked:

1) File -> Switch workspace - choose a different workspace
2) afterwards switch back to the original workspace

How to load a xib file in a UIView

You could try:

UIView *firstViewUIView = [[[NSBundle mainBundle] loadNibNamed:@"firstView" owner:self options:nil] firstObject];
[self.view.containerView addSubview:firstViewUIView];

How to use querySelectorAll only for elements that have a specific attribute set?

With your example:

<input type="checkbox" id="c2" name="c2" value="DE039230952"/>

Replace $$ with document.querySelectorAll in the examples:

$$('input') //Every input
$$('[id]') //Every element with id
$$('[id="c2"]') //Every element with id="c2"
$$('input,[id]') //Every input + every element with id
$$('input[id]') //Every input including id
$$('input[id="c2"]') //Every input including id="c2"
$$('input#c2') //Every input including id="c2" (same as above)
$$('input#c2[value="DE039230952"]') //Every input including id="c2" and value="DE039230952"
$$('input#c2[value^="DE039"]') //Every input including id="c2" and value has content starting with DE039
$$('input#c2[value$="0952"]') //Every input including id="c2" and value has content ending with 0952
$$('input#c2[value*="39230"]') //Every input including id="c2" and value has content including 39230

Use the examples directly with:

const $$ = document.querySelectorAll.bind(document);

Some additions:

$$(.) //The same as $([class])
$$(div > input) //div is parent tag to input
document.querySelector() //equals to $$()[0] or $()

find first sequence item that matches a criterion

If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

next(obj for obj in objs if obj.val == 5)

This is however faster than a complete list comprehension. Compare these two:

[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

How to add header row to a pandas DataFrame

You can use names directly in the read_csv

names : array-like, default None List of column names to use. If file contains no header row, then you should explicitly pass header=None

Cov = pd.read_csv("path/to/file.txt", 
                  sep='\t', 
                  names=["Sequence", "Start", "End", "Coverage"])

C# looping through an array

Your for loop doesn't need to just add one. You can loop by three.

for(int i = 0; i < theData.Length; i+=3)
{
  string value1 = theData[i];
  string value2 = theData[i+1];
  string value3 = theData[i+2];
}

Basically, you are just using indexes to grab the values in your array. One point to note here, I am not checking to see if you go past the end of your array. Make sure you are doing bounds checking!

Scale Image to fill ImageView width and keep aspect ratio

Without using any custom classes or libraries:

<ImageView
    android:id="@id/img"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:adjustViewBounds="true"
    android:scaleType="fitCenter" />

scaleType="fitCenter" (default when omitted)

  • will make it as wide as the parent allows and up/down-scale as needed keeping aspect ratio.

scaleType="centerInside"

  • if the intrinsic width of src is smaller than parent width
    will center the image horizontally
  • if the intrinsic width of src is larger than parent width
    will make it as wide as the parent allows and down-scale keeping aspect ratio.

It doesn't matter if you use android:src or ImageView.setImage* methods and the key is probably the adjustViewBounds.

Bootstrap 3: how to make head of dropdown link clickable in navbar

Add disabled Class in your anchor, following are js:

$('.navbar .dropdown-toggle').hover(function() {
  $(this).addClass('disabled');
});

But this is not mobile friendly so you need to remove disabled class for mobile, so updated js code is following:

$('.navbar .dropdown-toggle').hover(function() {
  if (document.documentElement.clientWidth > 769) { $(this).addClass('disabled');}
  else { $(this).removeClass('disabled'); }
});

How to export SQL Server database to MySQL?

I use sqlyog to migrate from mssql to mysql. I tried Migration toolkit and workbench but liked sqlyog for its SJA. I could schedule the import process and could do incremental import using WHERE clause.

enter image description here

How to find out the MySQL root password

thanks to @thusharaK I could reset the root password without knowing the old password.

On ubuntu I did the following:

sudo service mysql stop
sudo mysqld_safe --skip-grant-tables --skip-syslog --skip-networking

Then run mysql in a new terminal:

mysql -u root

And run the following queries to change the password:

UPDATE mysql.user SET authentication_string=PASSWORD('password') WHERE User='root';
FLUSH PRIVILEGES;

In MySQL 5.7, the password field in mysql.user table field was removed, now the field name is 'authentication_string'.

Quit the mysql safe mode and start mysql service by:

mysqladmin shutdown
sudo service mysql start

Cannot add or update a child row: a foreign key constraint fails

This took me a while to figure out. Simply put, the table that references the other table already has data in it and one or more of its values does not exist in the parent table.

e.g. Table2 has the following data:

UserID    PostID    Title    Summary
5         1         Lorem    Ipsum dolor sit

Table1

UserID    Password    Username    Email
9         ********    JohnDoe     [email protected]

If you try to ALTER table2 and add a foreign key then the query will fail because UserID=5 doesn't exist in Table1.

Javascript form validation with password confirming

add this to your form:

<form  id="regform" action="insert.php" method="post">

add this to your function:

<script>
    function myFunction() {
        var pass1 = document.getElementById("pass1").value;
        var pass2 = document.getElementById("pass2").value;
        if (pass1 != pass2) {
            //alert("Passwords Do not match");
            document.getElementById("pass1").style.borderColor = "#E34234";
            document.getElementById("pass2").style.borderColor = "#E34234";
        }
        else {
            alert("Passwords Match!!!");
            document.getElementById("regForm").submit();
        }
    }
</script>

What does "The following object is masked from 'package:xxx'" mean?

I have the same problem. I avoid it with remove.packages("Package making this confusion") and it works. In my case, I don't need the second package, so that is not a very good idea.

'this' is undefined in JavaScript class methods

I just wanted to point out that sometimes this error happens because a function has been used as a high order function (passed as an argument) and then the scope of this got lost. In such cases, I would recommend passing such function bound to this. E.g.

this.myFunction.bind(this);

How do I view / replay a chrome network debugger har file saved with content?

There is an HAR Viewer developed by Jan Odvarko that you can use. You either use the online version at

Or download the source-code at https://github.com/janodvarko/harviewer.

EDIT: Chrome 62 DevTools include HAR import functionality. https://developers.google.com/web/updates/2017/08/devtools-release-notes#har-imports

Delete all rows in table

Truncate table is faster than delete * from XXX. Delete is slow because it works one row at a time. There are a few situations where truncate doesn't work, which you can read about on MSDN.

NSString with \n or line break

I found that when I was reading strings in from a .plist file, occurrences of "\n" were parsed as "\\n". The solution for me was to replace occurrences of "\\n" with "\n". For example, given an instance of NSString named myString read in from my .plist file, I had to call...

myString = [myString stringByReplacingOccurrencesOfString:@"\\n" withString:@"\n"];

... before assigning it to my UILabel instance...

myLabel.text = myString;

C# Public Enums in Classes

Just declare it outside class definition.

If your namespace's name is X, you will be able to access the enum's values by X.card_suit

If you have not defined a namespace for this enum, just call them by card_suit.Clubs etc.

How to add an element to the beginning of an OrderedDict?

There's no built-in method for doing this in Python 2. If you need this, you need to write a prepend() method/function that operates on the OrderedDict internals with O(1) complexity.

For Python 3.2 and later, you should use the move_to_end method. The method accepts a last argument which indicates whether the element will be moved to the bottom (last=True) or the top (last=False) of the OrderedDict.

Finally, if you want a quick, dirty and slow solution, you can just create a new OrderedDict from scratch.

Details for the four different solutions:


Extend OrderedDict and add a new instance method

from collections import OrderedDict

class MyOrderedDict(OrderedDict):

    def prepend(self, key, value, dict_setitem=dict.__setitem__):

        root = self._OrderedDict__root
        first = root[1]

        if key in self:
            link = self._OrderedDict__map[key]
            link_prev, link_next, _ = link
            link_prev[1] = link_next
            link_next[0] = link_prev
            link[0] = root
            link[1] = first
            root[1] = first[0] = link
        else:
            root[1] = first[0] = self._OrderedDict__map[key] = [root, first, key]
            dict_setitem(self, key, value)

Demo:

>>> d = MyOrderedDict([('a', '1'), ('b', '2')])
>>> d
MyOrderedDict([('a', '1'), ('b', '2')])
>>> d.prepend('c', 100)
>>> d
MyOrderedDict([('c', 100), ('a', '1'), ('b', '2')])
>>> d.prepend('a', d['a'])
>>> d
MyOrderedDict([('a', '1'), ('c', 100), ('b', '2')])
>>> d.prepend('d', 200)
>>> d
MyOrderedDict([('d', 200), ('a', '1'), ('c', 100), ('b', '2')])

Standalone function that manipulates OrderedDict objects

This function does the same thing by accepting the dict object, key and value. I personally prefer the class:

from collections import OrderedDict

def ordered_dict_prepend(dct, key, value, dict_setitem=dict.__setitem__):
    root = dct._OrderedDict__root
    first = root[1]

    if key in dct:
        link = dct._OrderedDict__map[key]
        link_prev, link_next, _ = link
        link_prev[1] = link_next
        link_next[0] = link_prev
        link[0] = root
        link[1] = first
        root[1] = first[0] = link
    else:
        root[1] = first[0] = dct._OrderedDict__map[key] = [root, first, key]
        dict_setitem(dct, key, value)

Demo:

>>> d = OrderedDict([('a', '1'), ('b', '2')])
>>> ordered_dict_prepend(d, 'c', 100)
>>> d
OrderedDict([('c', 100), ('a', '1'), ('b', '2')])
>>> ordered_dict_prepend(d, 'a', d['a'])
>>> d
OrderedDict([('a', '1'), ('c', 100), ('b', '2')])
>>> ordered_dict_prepend(d, 'd', 500)
>>> d
OrderedDict([('d', 500), ('a', '1'), ('c', 100), ('b', '2')])

Use OrderedDict.move_to_end() (Python >= 3.2)

Python 3.2 introduced the OrderedDict.move_to_end() method. Using it, we can move an existing key to either end of the dictionary in O(1) time.

>>> d1 = OrderedDict([('a', '1'), ('b', '2')])
>>> d1.update({'c':'3'})
>>> d1.move_to_end('c', last=False)
>>> d1
OrderedDict([('c', '3'), ('a', '1'), ('b', '2')])

If we need to insert an element and move it to the top, all in one step, we can directly use it to create a prepend() wrapper (not presented here).


Create a new OrderedDict - slow!!!

If you don't want to do that and performance is not an issue then easiest way is to create a new dict:

from itertools import chain, ifilterfalse
from collections import OrderedDict


def unique_everseen(iterable, key=None):
    "List unique elements, preserving order. Remember all elements ever seen."
    # unique_everseen('AAAABBBCCDAABBB') --> A B C D
    # unique_everseen('ABBCcAD', str.lower) --> A B C D
    seen = set()
    seen_add = seen.add
    if key is None:
        for element in ifilterfalse(seen.__contains__, iterable):
            seen_add(element)
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

d1 = OrderedDict([('a', '1'), ('b', '2'),('c', 4)])
d2 = OrderedDict([('c', 3), ('e', 5)])   #dict containing items to be added at the front
new_dic = OrderedDict((k, d2.get(k, d1.get(k))) for k in \
                                           unique_everseen(chain(d2, d1)))
print new_dic

output:

OrderedDict([('c', 3), ('e', 5), ('a', '1'), ('b', '2')])

Firebug-like debugger for Google Chrome

Firebug Lite supports to inspect HTML elements, computed CSS style, and a lot more. Since it's pure JavaScript, it works in many different browsers. Just include the script in your source, or add the bookmarklet to your bookmark bar to include it on any page with a single click.

http://getfirebug.com/lite.html

CSS Div width percentage and padding without breaking layout

Try removing the position from header and add overflow to container:

#container {
    position:relative;
    width:80%;
    height:auto;
    overflow:auto;
}
#header {
    width:80%;
    height:50px;
    padding:10px;
}

Understanding esModuleInterop in tsconfig file

in your tsconfig you have to add: "esModuleInterop": true - it should help.

Clearing content of text file using C#

Another short version:

System.IO.File.WriteAllBytes(path, new byte[0]);

Add item to array in VBScript

Based on Charles Clayton's answer, but slightly simplified...

' add item to array
Sub ArrayAdd(arr, val)
    ReDim Preserve arr(UBound(arr) + 1)
    arr(UBound(arr)) = val
End Sub

Used like so

a = Array()
AddItem(a, 5)
AddItem(a, "foo")

src absolute path problem

You should be referencing it as localhost. Like this:

<img src="http:\\localhost\site\img\mypicture.jpg"/>

JavaScript: How to find out if the user browser is Chrome?

Check this: How to detect Safari, Chrome, IE, Firefox and Opera browser?

In your case:

var isChrome = (window.chrome.webstore || window.chrome.runtime) && !!window.chrome;

Getting Chrome to accept self-signed localhost certificate

If you're on a mac and not seeing the export tab or how to get the certificate this worked for me:

  1. Click the lock before the https://
  2. Go to the "Connection" tab
  3. Click "Certificate Information"

    Now you should see this: Different information of course and yours should be marked as trusted yet (otherwise      you probably wouldn't be here)

  4. Drag that little certificate icon do your desktop (or anywhere).

  5. Double click the .cer file that was downloaded, this should import it into your keychain and open Keychain Access to your list of certificates.

    In some cases, this is enough and you can now refresh the page.

    Otherwise:

  6. Double click the newly added certificate.
  7. Under the trust drop down change the "When using this certificate" option to "Always Trust"

Now reload the page in question and it should be problem solved! Hope this helps.


Edit from Wolph

To make this a little easier you can use the following script (source):

  1. Save the following script as whitelist_ssl_certificate.ssh:

    #!/usr/bin/env bash -e
    
    SERVERNAME=$(echo "$1" | sed -E -e 's/https?:\/\///' -e 's/\/.*//')
    echo "$SERVERNAME"
    
    if [[ "$SERVERNAME" =~ .*\..* ]]; then
        echo "Adding certificate for $SERVERNAME"
        echo -n | openssl s_client -connect $SERVERNAME:443 | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' | tee /tmp/$SERVERNAME.cert
        sudo security add-trusted-cert -d -r trustRoot -k "/Library/Keychains/System.keychain" /tmp/$SERVERNAME.cert
    else
        echo "Usage: $0 www.site.name"
        echo "http:// and such will be stripped automatically"
    fi
    
  2. Make the script executable (from the shell):

    chmod +x whitelist_ssl_certificate.ssh
    
  3. Run the script for the domain you want (simply copy/pasting the full url works):

    ./whitelist_ssl_certificate.ssh https://your_website/whatever
    

How can I convert a Unix timestamp to DateTime and vice versa?

DateTime unixEpoch = DateTime.ParseExact("1970-01-01", "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture);
DateTime convertedTime = unixEpoch.AddMilliseconds(unixTimeInMillisconds);

Of course, one can make unixEpoch a global static, so it only needs to appear once in your project, and one can use AddSeconds if the UNIX time is in seconds.

To go the other way:

double unixTimeInMilliseconds = timeToConvert.Subtract(unixEpoch).TotalMilliseconds;

Truncate to Int64 and/or use TotalSeconds as needed.

how to prevent adding duplicate keys to a javascript array

A better alternative is provided in ES6 using Sets. So, instead of declaring Arrays, it is recommended to use Sets if you need to have an array that shouldn't add duplicates.

var array = new Set();
array.add(1);
array.add(2);
array.add(3);

console.log(array);
// Prints: Set(3) {1, 2, 3}

array.add(2); // does not add any new element

console.log(array);
// Still Prints: Set(3) {1, 2, 3}

Why can't I make a vector of references?

boost::ptr_vector<int> will work.

Edit: was a suggestion to use std::vector< boost::ref<int> >, which will not work because you can't default-construct a boost::ref.

How can I access a hover state in reactjs?

ReactJs defines the following synthetic events for mouse events:

onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseOut onMouseOver onMouseUp

As you can see there is no hover event, because browsers do not define a hover event natively.

You will want to add handlers for onMouseEnter and onMouseLeave for hover behavior.

ReactJS Docs - Events

How to add and get Header values in WebApi

try these line of codes working in my case:

IEnumerable<string> values = new List<string>();
this.Request.Headers.TryGetValues("Authorization", out values);

max(length(field)) in mysql

Use CHAR_LENGTH() instead-of LENGTH() as suggested in: MySQL - length() vs char_length()

SELECT name, CHAR_LENGTH(name) AS mlen FROM mytable ORDER BY mlen DESC LIMIT 1

How to use split?

If it is the basic JavaScript split function, look at documentation, JavaScript split() Method.

Basically, you just do this:

var array = myString.split(' -- ')

Then your two values are stored in the array - you can get the values like this:

var firstValue = array[0];
var secondValue = array[1];

How to compare DateTime in C#?

MuSTaNG's answer says it all, but I am still adding it to make it a little more elaborate, with links and all.


The conventional operators

are available for DateTime since .NET Framework 1.1. Also, addition and subtraction of DateTime objects are also possible using conventional operators + and -.

One example from MSDN:

Equality:
System.DateTime april19 = new DateTime(2001, 4, 19);
System.DateTime otherDate = new DateTime(1991, 6, 5);

// areEqual gets false.
bool areEqual = april19 == otherDate;

otherDate = new DateTime(2001, 4, 19);
// areEqual gets true.
areEqual = april19 == otherDate;

Other operators can be used likewise.

Here is the list all operators available for DateTime.

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

You need to give the user table an alias the second time you join to it

e.g.

SELECT article . * , section.title, category.title, user.name, u2.name 
FROM article 
INNER JOIN section ON article.section_id = section.id 
INNER JOIN category ON article.category_id = category.id 
INNER JOIN user ON article.author_id = user.id 
LEFT JOIN user u2 ON article.modified_by = u2.id 
WHERE article.id = '1'

How do I format a date in Jinja2?

There are two ways to do it. The direct approach would be to simply call (and print) the strftime() method in your template, for example

{{ car.date_of_manufacture.strftime('%Y-%m-%d') }}

Another, sightly better approach would be to define your own filter, e.g.:

from flask import Flask
import babel

app = Flask(__name__)

@app.template_filter()
def format_datetime(value, format='medium'):
    if format == 'full':
        format="EEEE, d. MMMM y 'at' HH:mm"
    elif format == 'medium':
        format="EE dd.MM.y HH:mm"
    return babel.dates.format_datetime(value, format)

(This filter is based on babel for reasons regarding i18n, but you can use strftime too). The advantage of the filter is, that you can write

{{ car.date_of_manufacture|datetime }}
{{ car.date_of_manufacture|datetime('full') }}

which looks nicer and is more maintainable. Another common filter is also the "timedelta" filter, which evaluates to something like "written 8 minutes ago". You can use babel.dates.format_timedelta for that, and register it as filter similar to the datetime example given here.

SQL Server default character encoding

SELECT DATABASEPROPERTYEX('DBName', 'Collation') SQLCollation;

Where DBName is your database name.

How to validate Google reCAPTCHA v3 on server side?

I'm not a fan of any of these solutions. I use this instead:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
    'secret' => $privatekey,
    'response' => $_POST['g-recaptcha-response'],
    'remoteip' => $_SERVER['REMOTE_ADDR']
]);

$resp = json_decode(curl_exec($ch));
curl_close($ch);

if ($resp->success) {
    // Success
} else {
    // failure
}

I'd argue that this is superior because you ensure it is being POSTed to the server and it's not making an awkward 'file_get_contents' call. This is compatible with recaptcha 2.0 described here: https://developers.google.com/recaptcha/docs/verify

I find this cleaner. I see most solutions are file_get_contents, when I feel curl would suffice.

how to get current datetime in SQL?

For SQL Server use GetDate() or current_timestamp. You can format the result with the Convert(dataType,value,format). Tag your question with the correct Database Server.

The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer

I was facing the same issue. After many tries below solution worked for me.

Before installing VC++ install your windows updates. 1. Go to Start - Control Panel - Windows Update 2. Check for the updates. 3. Install all updates. 4. Restart your system.

After that you can follow the below steps.

@ABHI KUMAR

Download the Visual C++ Redistributable 2015

Visual C++ Redistributable for Visual Studio 2015 (64-bit)

Visual C++ Redistributable for Visual Studio 2015 (32-bit)

(Reinstal if already installed) then restart your computer or use windows updates for download auto.

For link download https://www.microsoft.com/de-de/download/details.aspx?id=48145.

set initial viewcontroller in appdelegate - swift

Code for Swift 4.2 and 5 code:

var window: UIWindow?


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 
     self.window = UIWindow(frame: UIScreen.main.bounds)

     let storyboard = UIStoryboard(name: "Main", bundle: nil)

     let initialViewController = storyboard.instantiateViewController(withIdentifier: "dashboardVC")

     self.window?.rootViewController = initialViewController
     self.window?.makeKeyAndVisible()
}

And for Xcode 11+ and for Swift 5+ :

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

     var window: UIWindow?

     func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
         if let windowScene = scene as? UIWindowScene {
             let window = UIWindow(windowScene: windowScene)

              window.rootViewController = // Your RootViewController in here

              self.window = window
              window.makeKeyAndVisible()
         }
    }
}

How can I add spaces between two <input> lines using CSS?

You don't need to wrap everything in a DIV to achieve basic styling on inputs.

input[type="text"] {margin: 0 0 10px 0;}

will do the trick in most cases.

Semantically, one <br/> tag is okay between elements to position them. When you find yourself using multiple <br/>'s (which are semantic elements) to achieve cosmetic effects, that's a flag that you're mixing responsibilities, and you should consider getting back to basics.

HTTP response code for POST when resource already exists

According to RFC 7231, a 303 See Other MAY be used If the result of processing a POST would be equivalent to a representation of an existing resource.

How to get the filename without the extension in Java?

The fluent way:

public static String fileNameWithOutExt (String fileName) {
    return Optional.of(fileName.lastIndexOf(".")).filter(i-> i >= 0)
            .map(i-> fileName.substring(0, i)).orElse(fileName);
}

The performance impact of using instanceof in Java

I have got same question, but because i did not find 'performance metrics' for use case similar to mine, i've done some more sample code. On my hardware and Java 6 & 7, the difference between instanceof and switch on 10mln iterations is

for 10 child classes - instanceof: 1200ms vs switch: 470ms
for 5 child classes  - instanceof:  375ms vs switch: 204ms

So, instanceof is really slower, especially on huge number of if-else-if statements, however difference will be negligible within real application.

import java.util.Date;

public class InstanceOfVsEnum {

    public static int c1, c2, c3, c4, c5, c6, c7, c8, c9, cA;

    public static class Handler {
        public enum Type { Type1, Type2, Type3, Type4, Type5, Type6, Type7, Type8, Type9, TypeA }
        protected Handler(Type type) { this.type = type; }
        public final Type type;

        public static void addHandlerInstanceOf(Handler h) {
            if( h instanceof H1) { c1++; }
            else if( h instanceof H2) { c2++; }
            else if( h instanceof H3) { c3++; }
            else if( h instanceof H4) { c4++; }
            else if( h instanceof H5) { c5++; }
            else if( h instanceof H6) { c6++; }
            else if( h instanceof H7) { c7++; }
            else if( h instanceof H8) { c8++; }
            else if( h instanceof H9) { c9++; }
            else if( h instanceof HA) { cA++; }
        }

        public static void addHandlerSwitch(Handler h) {
            switch( h.type ) {
                case Type1: c1++; break;
                case Type2: c2++; break;
                case Type3: c3++; break;
                case Type4: c4++; break;
                case Type5: c5++; break;
                case Type6: c6++; break;
                case Type7: c7++; break;
                case Type8: c8++; break;
                case Type9: c9++; break;
                case TypeA: cA++; break;
            }
        }
    }

    public static class H1 extends Handler { public H1() { super(Type.Type1); } }
    public static class H2 extends Handler { public H2() { super(Type.Type2); } }
    public static class H3 extends Handler { public H3() { super(Type.Type3); } }
    public static class H4 extends Handler { public H4() { super(Type.Type4); } }
    public static class H5 extends Handler { public H5() { super(Type.Type5); } }
    public static class H6 extends Handler { public H6() { super(Type.Type6); } }
    public static class H7 extends Handler { public H7() { super(Type.Type7); } }
    public static class H8 extends Handler { public H8() { super(Type.Type8); } }
    public static class H9 extends Handler { public H9() { super(Type.Type9); } }
    public static class HA extends Handler { public HA() { super(Type.TypeA); } }

    final static int cCycles = 10000000;

    public static void main(String[] args) {
        H1 h1 = new H1();
        H2 h2 = new H2();
        H3 h3 = new H3();
        H4 h4 = new H4();
        H5 h5 = new H5();
        H6 h6 = new H6();
        H7 h7 = new H7();
        H8 h8 = new H8();
        H9 h9 = new H9();
        HA hA = new HA();

        Date dtStart = new Date();
        for( int i = 0; i < cCycles; i++ ) {
            Handler.addHandlerInstanceOf(h1);
            Handler.addHandlerInstanceOf(h2);
            Handler.addHandlerInstanceOf(h3);
            Handler.addHandlerInstanceOf(h4);
            Handler.addHandlerInstanceOf(h5);
            Handler.addHandlerInstanceOf(h6);
            Handler.addHandlerInstanceOf(h7);
            Handler.addHandlerInstanceOf(h8);
            Handler.addHandlerInstanceOf(h9);
            Handler.addHandlerInstanceOf(hA);
        }
        System.out.println("Instance of - " + (new Date().getTime() - dtStart.getTime()));

        dtStart = new Date();
        for( int i = 0; i < cCycles; i++ ) {
            Handler.addHandlerSwitch(h1);
            Handler.addHandlerSwitch(h2);
            Handler.addHandlerSwitch(h3);
            Handler.addHandlerSwitch(h4);
            Handler.addHandlerSwitch(h5);
            Handler.addHandlerSwitch(h6);
            Handler.addHandlerSwitch(h7);
            Handler.addHandlerSwitch(h8);
            Handler.addHandlerSwitch(h9);
            Handler.addHandlerSwitch(hA);
        }
        System.out.println("Switch of - " + (new Date().getTime() - dtStart.getTime()));
    }
}

How to do a scatter plot with empty circles in Python?

Would these work?

plt.scatter(np.random.randn(100), np.random.randn(100), facecolors='none')

example image

or using plot()

plt.plot(np.random.randn(100), np.random.randn(100), 'o', mfc='none')

example image

Adding an .env file to React Project

If in case you are getting the values as undefined, then you should consider restarting the node server and recompile again.

How to call function on child component on parent events

Give the child component a ref and use $refs to call a method on the child component directly.

html:

<div id="app">
  <child-component ref="childComponent"></child-component>
  <button @click="click">Click</button>  
</div>

javascript:

var ChildComponent = {
  template: '<div>{{value}}</div>',
  data: function () {
    return {
      value: 0
    };
  },
  methods: {
    setValue: function(value) {
        this.value = value;
    }
  }
}

new Vue({
  el: '#app',
  components: {
    'child-component': ChildComponent
  },
  methods: {
    click: function() {
        this.$refs.childComponent.setValue(2.0);
    }
  }
})

For more info, see Vue documentation on refs.

How to pass a vector to a function?

You're passing in a pointer *random but you're using it like a reference &random

The pointer (what you have) says "This is the address in memory that contains the address of random"

The reference says "This is the address of random"

jquery - Check for file extension before uploading

I would like to thank the person who posted the answer, but he has deleted the post. We can do it like this.

$("#yourElem").uploadify({
   'uploader': ...,
   'script': ...
    'fileExt' : '*.jpg;*.gif;', //add allowed extensions
    .....,
    'onSelect': function(e, q, f) {
        var validExtensions = ['jpg','gif']; //array of valid extensions
        var fileName = f.name;
        var fileNameExt = fileName.substr(fileName.lastIndexOf('.') + 1);
        if ($.inArray(fileNameExt, validExtensions) == -1){
           alert("Invalid file type");
           $("#yourElem").uploadifyCancel(q);
           return false;
        }
    }
});

Thanks for the answer, it really worked...

Can I send a ctrl-C (SIGINT) to an application on Windows?

Somehow GenerateConsoleCtrlEvent() return error if you call it for another process, but you can attach to another console application and send event to all child processes.

void SendControlC(int pid)
{
    AttachConsole(pid); // attach to process console
    SetConsoleCtrlHandler(NULL, TRUE); // disable Control+C handling for our app
    GenerateConsoleCtrlEvent(CTRL_C_EVENT, 0); // generate Control+C event
}

Django Cookies, how can I set them?

Using Django's session framework should cover most scenarios, but Django also now provide direct cookie manipulation methods on the request and response objects (so you don't need a helper function).

Setting a cookie:

def view(request):
  response = HttpResponse('blah')
  response.set_cookie('cookie_name', 'cookie_value')

Retrieving a cookie:

def view(request):
  value = request.COOKIES.get('cookie_name')
  if value is None:
    # Cookie is not set

  # OR

  try:
    value = request.COOKIES['cookie_name']
  except KeyError:
    # Cookie is not set

Creating a mock HttpServletRequest out of a url string?

Simplest ways to mock an HttpServletRequest:

  1. Create an anonymous subclass:

    HttpServletRequest mock = new HttpServletRequest ()
    {
        private final Map<String, String[]> params = /* whatever */
    
        public Map<String, String[]> getParameterMap()
        {
            return params;
        }
    
        public String getParameter(String name)
        {
            String[] matches = params.get(name);
            if (matches == null || matches.length == 0) return null;
            return matches[0];
        }
    
        // TODO *many* methods to implement here
    };
    
  2. Use jMock, Mockito, or some other general-purpose mocking framework:

    HttpServletRequest mock = context.mock(HttpServletRequest.class); // jMock
    HttpServletRequest mock2 = Mockito.mock(HttpServletRequest.class); // Mockito
    
  3. Use HttpUnit's ServletUnit and don't mock the request at all.

JavaScript check if variable exists (is defined/initialized)

Try-catch

If variable was not defined at all, you can check this without break code execution using try-catch block as follows (you don't need to use strict mode)

_x000D_
_x000D_
try{
  notDefinedVariable;
} catch(e) {
  console.log('detected: variable not exists');
}

console.log('but the code is still executed');

notDefinedVariable; // without try-catch wrapper code stops here

console.log('code execution stops. You will NOT see this message on console');
_x000D_
_x000D_
_x000D_

BONUS: (referring to other answers) Why === is more clear than == (source)

if( a == b )

Enter image description here

if( a === b )

Enter image description here

How to change UIButton image in Swift

in Swift 4, (Xcode 9) example to turn picture of button to On or Off (btnRec):

var bRec:Bool = true

@IBOutlet weak var btnRec: UIButton!
@IBAction func btnRec(_ sender: Any) {
    bRec = !bRec
    if bRec {
        btnRec.setImage(UIImage(named: "MicOn.png"), for: .normal)
    } else {
        btnRec.setImage(UIImage(named: "MicOff.png"), for: .normal)
    }
}

Regex for string not ending with given suffix

Anything that matches something ending with a --- .*a$ So when you match the regex, negate the condition or alternatively you can also do .*[^a]$ where [^a] means anything which is not a

Pass parameters in setInterval function

You can use a library called underscore js. It gives a nice wrapper on the bind method and is a much cleaner syntax as well. Letting you execute the function in the specified scope.

http://underscorejs.org/#bind

_.bind(function, scope, *arguments)

Firefox and SSL: sec_error_unknown_issuer

If anyone else is experiencing this issue with an Ubuntu LAMP and "COMODO Positive SSL" try to build your own bundle from the certs in the compressed file.

cat AddTrustExternalCARoot.crt COMODORSAAddTrustCA.crt COMODORSADomainValidationSecureServerCA.crt > YOURDOMAIN.ca-bundle

Node.js Best Practice Exception Handling

nodejs domains is the most up to date way of handling errors in nodejs. Domains can capture both error/other events as well as traditionally thrown objects. Domains also provide functionality for handling callbacks with an error passed as the first argument via the intercept method.

As with normal try/catch-style error handling, is is usually best to throw errors when they occur, and block out areas where you want to isolate errors from affecting the rest of the code. The way to "block out" these areas are to call domain.run with a function as a block of isolated code.

In synchronous code, the above is enough - when an error happens you either let it be thrown through, or you catch it and handle there, reverting any data you need to revert.

try {  
  //something
} catch(e) {
  // handle data reversion
  // probably log too
}

When the error happens in an asynchronous callback, you either need to be able to fully handle the rollback of data (shared state, external data like databases, etc). OR you have to set something to indicate that an exception has happened - where ever you care about that flag, you have to wait for the callback to complete.

var err = null;
var d = require('domain').create();
d.on('error', function(e) {
  err = e;
  // any additional error handling
}
d.run(function() { Fiber(function() {
  // do stuff
  var future = somethingAsynchronous();
  // more stuff

  future.wait(); // here we care about the error
  if(err != null) {
    // handle data reversion
    // probably log too
  }

})});

Some of that above code is ugly, but you can create patterns for yourself to make it prettier, eg:

var specialDomain = specialDomain(function() {
  // do stuff
  var future = somethingAsynchronous();
  // more stuff

  future.wait(); // here we care about the error
  if(specialDomain.error()) {
    // handle data reversion
    // probably log too
  } 
}, function() { // "catch"
  // any additional error handling
});

UPDATE (2013-09):

Above, I use a future that implies fibers semantics, which allow you to wait on futures in-line. This actually allows you to use traditional try-catch blocks for everything - which I find to be the best way to go. However, you can't always do this (ie in the browser)...

There are also futures that don't require fibers semantics (which then work with normal, browsery JavaScript). These can be called futures, promises, or deferreds (I'll just refer to futures from here on). Plain-old-JavaScript futures libraries allow errors to be propagated between futures. Only some of these libraries allow any thrown future to be correctly handled, so beware.

An example:

returnsAFuture().then(function() {
  console.log('1')
  return doSomething() // also returns a future

}).then(function() {
  console.log('2')
  throw Error("oops an error was thrown")

}).then(function() {
  console.log('3')

}).catch(function(exception) {
  console.log('handler')
  // handle the exception
}).done()

This mimics a normal try-catch, even though the pieces are asynchronous. It would print:

1
2
handler

Note that it doesn't print '3' because an exception was thrown that interrupts that flow.

Take a look at bluebird promises:

Note that I haven't found many other libraries other than these that properly handle thrown exceptions. jQuery's deferred, for example, don't - the "fail" handler would never get the exception thrown an a 'then' handler, which in my opinion is a deal breaker.

How to properly validate input values with React.JS?

I recently spent a week studying lot of solutions to validate my forms in an app. I started with all the most stared one but I couldn't find one who was working as I was expected. After few days, I became quite frustrated until i found a very new and amazing plugin: https://github.com/kettanaito/react-advanced-form

The developper is very responsive and his solution, after my research, merit to become the most stared one from my perspective. I hope it could help and you'll appreciate.

Difference between application/x-javascript and text/javascript content types

mime-types starting with x- are not standardized. In case of javascript it's kind of outdated. Additional the second code snippet

<?Header('Content-Type: text/javascript');?>

requires short_open_tags to be enabled. you should avoid it.

<?php Header('Content-Type: text/javascript');?>

However, the completely correct mime-type for javascript is

application/javascript

http://www.iana.org/assignments/media-types/application/index.html

iPhone - Get Position of UIView within entire UIWindow

That's an easy one:

[aView convertPoint:localPosition toView:nil];

... converts a point in local coordinate space to window coordinates. You can use this method to calculate a view's origin in window space like this:

[aView.superview convertPoint:aView.frame.origin toView:nil];

2014 Edit: Looking at the popularity of Matt__C's comment it seems reasonable to point out that the coordinates...

  1. don't change when rotating the device.
  2. always have their origin in the top left corner of the unrotated screen.
  3. are window coordinates: The coordinate system ist defined by the bounds of the window. The screen's and device coordinate systems are different and should not be mixed up with window coordinates.

How To Show And Hide Input Fields Based On Radio Button Selection

Use display:none/block, instead of visibility, and add a margin-top/bottom for the space you want to see ONLY when the inputs are shown

 function yesnoCheck() {
        if (document.getElementById('yesCheck').checked) {
           document.getElementById('ifYes').style.display = 'block';
        } else {
           document.getElementById('ifYes').style.display = 'none';
        }
    }

and your HTML line for the ifYes tag

<div id="ifYes" style="display:none;margin-top:3%;">If yes, explain:

failed to open stream: No such file or directory in

It's because you have included a leading / in your file path. The / makes it start at the top of your filesystem. Note: filesystem path, not Web site path (you're not accessing it over HTTP). You can use a relative path with include_once (one that doesn't start with a leading /).

You can change it to this:

include_once 'headerSite.php';

That will look first in the same directory as the file that's including it (i.e. C:\xampp\htdocs\PoliticalForum\ in your example.

Does delete on a pointer to a subclass call the base class destructor?

You should delete A yourself in the destructor of B.

How to run PowerShell in CMD

Try just:

powershell.exe -noexit D:\Work\SQLExecutor.ps1 -gettedServerName "MY-PC"

Search for a string in all tables, rows and columns of a DB

Or, you can use my query here, should be simpler then having to create sProcs for each DB you want to search: FullParam SQL Blog

/* Reto Egeter, fullparam.wordpress.com */

DECLARE @SearchStrTableName nvarchar(255), @SearchStrColumnName nvarchar(255), @SearchStrColumnValue nvarchar(255), @SearchStrInXML bit, @FullRowResult bit, @FullRowResultRows int
SET @SearchStrColumnValue = '%searchthis%' /* use LIKE syntax */
SET @FullRowResult = 1
SET @FullRowResultRows = 3
SET @SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET @SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET @SearchStrInXML = 0 /* Searching XML data may be slow */

IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256) = '',@ColumnName nvarchar(128),@ColumnType nvarchar(20), @QuotedSearchStrColumnValue nvarchar(110), @QuotedSearchStrColumnName nvarchar(110)
SET @QuotedSearchStrColumnValue = QUOTENAME(@SearchStrColumnValue,'''')
DECLARE @ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))

WHILE @TableName IS NOT NULL
BEGIN
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND TABLE_NAME LIKE COALESCE(@SearchStrTableName,TABLE_NAME)
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
    )
    IF @TableName IS NOT NULL
    BEGIN
        DECLARE @sql VARCHAR(MAX)
        SET @sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
                FROM    INFORMATION_SCHEMA.COLUMNS
                WHERE       TABLE_SCHEMA    = PARSENAME(''' + @TableName + ''', 2)
                AND TABLE_NAME  = PARSENAME(''' + @TableName + ''', 1)
                AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE @SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
                AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN @SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + @SearchStrColumnName + '''' END  + ',COLUMN_NAME)'
        INSERT INTO @ColumnNameTable
        EXEC (@sql)
        WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM @ColumnNameTable)
        BEGIN
            PRINT @ColumnName
            SELECT TOP 1 @ColumnName = COLUMN_NAME,@ColumnType = DATA_TYPE FROM @ColumnNameTable
            SET @sql = 'SELECT ''' + @TableName + ''',''' + @ColumnName + ''',' + CASE @ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + @ColumnName + ' AS nvarchar(MAX)), 4096),''' 
            WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + '),'''
            ELSE 'LEFT(' + @ColumnName + ', 4096),''' END + @ColumnType + ''' 
                    FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))' 
                    WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
                    ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
            INSERT INTO #Results
            EXEC(@sql)
            IF @@ROWCOUNT > 0 IF @FullRowResult = 1 
            BEGIN
                SET @sql = 'SELECT TOP ' + CAST(@FullRowResultRows AS VARCHAR(3)) + ' ''' + @TableName + ''' AS [TableFound],''' + @ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
                    ' FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))' 
                    WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
                    ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
                EXEC(@sql)
            END
            DELETE FROM @ColumnNameTable WHERE COLUMN_NAME = @ColumnName
        END 
    END
END
SET NOCOUNT OFF

SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results GROUP BY TableName, ColumnName, ColumnValue, ColumnType

Interface/enum listing standard mime-type constants

If you're on android you have multiple choices, where only the first is a kind of "enum":

For example

@Override
public String getType(Uri uri) {
    return URLConnection.getFileNameMap().getContentTypeFor(
            uri.getLastPathSegment());
}

How do I use DateTime.TryParse with a Nullable<DateTime>?

This is the one liner you're looking fo:

DateTime? d = DateTime.TryParse("some date text", out DateTime dt) ? dt : null;

If you want to make it a proper TryParse pseudo-extension method, you can do this:

public static bool TryParse(string text, out DateTime? dt)
{
    if (DateTime.TryParse(text, out DateTime date))
    {
        dt = date;
        return true;
    }
    else
    {
        dt = null;
        return false;
    }
}

How do I address unchecked cast warnings?

In the HTTP Session world you can't really avoid the cast, since the API is written that way (takes and returns only Object).

With a little bit of work you can easily avoid the unchecked cast, 'though. This means that it will turn into a traditional cast giving a ClassCastException right there in the event of an error). An unchecked exception could turn into a CCE at any point later on instead of the point of the cast (that's the reason why it's a separate warning).

Replace the HashMap with a dedicated class:

import java.util.AbstractMap;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class Attributes extends AbstractMap<String, String> {
    final Map<String, String> content = new HashMap<String, String>();

    @Override
    public Set<Map.Entry<String, String>> entrySet() {
        return content.entrySet();
    }

    @Override
    public Set<String> keySet() {
        return content.keySet();
    }

    @Override
    public Collection<String> values() {
        return content.values();
    }

    @Override
    public String put(final String key, final String value) {
        return content.put(key, value);
    }
}

Then cast to that class instead of Map<String,String> and everything will be checked at the exact place where you write your code. No unexpected ClassCastExceptions later on.

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator.

This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator") can be overriden via command line options and isn't as type safe as java.io.File.separator.

The last one, java.nio.file.FileSystems.getDefault().getSeparator(); was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.

So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.

MySQL: update a field only if condition is met

Another solution which, in my opinion, is easier to read would be:

UPDATE test 
    SET something = 1, field = IF(condition is true, 1, field) 
    WHERE id = 123

What this does is set 'field' to 1 (like OP used as example) if the condition is met and use the current value of 'field' if not met. Using the previous value is the same as not changing, so there you go.

Regular expression to extract numbers from a string

if you know for sure that there are only going to be 2 places where you have a list of digits in your string and that is the only thing you are going to pull out then you should be able to simply use

\d+

How to prevent http file caching in Apache httpd (MAMP)

Without mod_expires it will be harder to set expiration headers on your files. For anything generated you can certainly set some default headers on the answer, doing the job of mod_expires like that:

<?php header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 3600)); ?>

(taken from: Stack Overflow answer from @brianegge, where the mod_expires solution is also explained)

Now this won't work for static files, like your javascript files. As for static files there is only apache (without any expiration module) between the browser and the source file. To prevent caching of javascript files, which is done on your browser, you can use a random token at the end of the js url, something like ?rd=45642111, so the url looks like:

<script type="texte/javascript" src="my/url/myjs.js?rd=4221159546">

If this url on the page is generated by a PHP file you can simply add the random part with PHP. This way of randomizing url by simply appending random query string parameters is the base thing upôn no-cache setting of ajax jQuery request for example. The browser will never consider 2 url having different query strings to be the same, and will never use the cached version.

EDIT

Note that you should alos test mod_headers. If you have mod_headers you can maybe set the Expires headers directly with the Header keyword.

MySQL Insert into multiple tables? (Database normalization?)

fairly simple if you use stored procedures:

call insert_user_and_profile('f00','http://www.f00.com');

full script:

drop table if exists users;
create table users
(
user_id int unsigned not null auto_increment primary key,
username varchar(32) unique not null
)
engine=innodb;

drop table if exists user_profile;
create table user_profile
(
profile_id int unsigned not null auto_increment primary key,
user_id int unsigned not null,
homepage varchar(255) not null,
key (user_id)
)
engine=innodb;

drop procedure if exists insert_user_and_profile;

delimiter #

create procedure insert_user_and_profile
(
in p_username varchar(32),
in p_homepage varchar(255)
)
begin
declare v_user_id int unsigned default 0;

insert into users (username) values (p_username);
set v_user_id = last_insert_id(); -- save the newly created user_id

insert into user_profile (user_id, homepage) values (v_user_id, p_homepage);

end#

delimiter ;

call insert_user_and_profile('f00','http://www.f00.com');

select * from users;
select * from user_profile;

Make Adobe fonts work with CSS3 @font-face in IE9

I found eot file should be put beyond ttf. If it's under ttf, thought the font shows correctly, IE9 will still throw an error.

Recommend:

@font-face {
  font-family: 'Font-Name';
  src: url('../fonts/Font-Name.eot?#iefix') format('embedded-opentype');
  src: url('../fonts/Font-Name.ttf')  format('truetype');
}

Not Recommend:

@font-face {
  font-family: 'Font-Name';
  src: url('../fonts/Font-Name.ttf')  format('truetype');
  src: url('../fonts/Font-Name.eot?#iefix') format('embedded-opentype');
  }

Get the distance between two geo points

An approximated solution (based on an equirectangular projection), much faster (it requires only 1 trig and 1 square root).

This approximation is relevant if your points are not too far apart. It will always over-estimate compared to the real haversine distance. For example it will add no more than 0.05382 % to the real distance if the delta latitude or longitude between your two points does not exceed 4 decimal degrees.

The standard formula (Haversine) is the exact one (that is, it works for any couple of longitude/latitude on earth) but is much slower as it needs 7 trigonometric and 2 square roots. If your couple of points are not too far apart, and absolute precision is not paramount, you can use this approximate version (Equirectangular), which is much faster as it uses only one trigonometric and one square root.

// Approximate Equirectangular -- works if (lat1,lon1) ~ (lat2,lon2)
int R = 6371; // km
double x = (lon2 - lon1) * Math.cos((lat1 + lat2) / 2);
double y = (lat2 - lat1);
double distance = Math.sqrt(x * x + y * y) * R;

You can optimize this further by either:

  1. Removing the square root if you simply compare the distance to another (in that case compare both squared distance);
  2. Factoring-out the cosine if you compute the distance from one master point to many others (in that case you do the equirectangular projection centered on the master point, so you can compute the cosine once for all comparisons).

For more info see: http://www.movable-type.co.uk/scripts/latlong.html

There is a nice reference implementation of the Haversine formula in several languages at: http://www.codecodex.com/wiki/Calculate_Distance_Between_Two_Points_on_a_Globe

How to extend / inherit components?

Now that TypeScript 2.2 supports Mixins through Class expressions we have a much better way to express Mixins on Components. Mind you that you can also use Component inheritance since angular 2.3 (discussion) or a custom decorator as discussed in other answers here. However, I think Mixins have some properties that make them preferable for reusing behavior across components:

  • Mixins compose more flexibly, i.e. you can mix and match Mixins on existing components or combine Mixins to form new Components
  • Mixin composition remains easy to understand thanks to its obvious linearization to a class inheritance hierarchy
  • You can more easily avoid issues with decorators and annotations that plague component inheritance (discussion)

I strongly suggest you read the TypeScript 2.2 announcement above to understand how Mixins work. The linked discussions in angular GitHub issues provide additional detail.

You'll need these types:

export type Constructor<T> = new (...args: any[]) => T;

export class MixinRoot {
}

And then you can declare a Mixin like this Destroyable mixin that helps components keep track of subscriptions that need to be disposed in ngOnDestroy:

export function Destroyable<T extends Constructor<{}>>(Base: T) {
  return class Mixin extends Base implements OnDestroy {
    private readonly subscriptions: Subscription[] = [];

    protected registerSubscription(sub: Subscription) {
      this.subscriptions.push(sub);
    }

    public ngOnDestroy() {
      this.subscriptions.forEach(x => x.unsubscribe());
      this.subscriptions.length = 0; // release memory
    }
  };
}

To mixin Destroyable into a Component, you declare your component like this:

export class DashboardComponent extends Destroyable(MixinRoot) 
    implements OnInit, OnDestroy { ... }

Note that MixinRoot is only necessary when you want to extend a Mixin composition. You can easily extend multiple mixins e.g. A extends B(C(D)). This is the obvious linearization of mixins I was talking about above, e.g. you're effectively composing an inheritnace hierarchy A -> B -> C -> D.

In other cases, e.g. when you want to compose Mixins on an existing class, you can apply the Mixin like so:

const MyClassWithMixin = MyMixin(MyClass);

However, I found the first way works best for Components and Directives, as these also need to be decorated with @Component or @Directive anyway.

Determining Referer in PHP

There is no reliable way to check this. It's really under client's hand to tell you where it came from. You could imagine to use cookie or sessions informations put only on some pages of your website, but doing so your would break user experience with bookmarks.

How do I catch a numpy warning like it's an exception (not just for testing)?

To elaborate on @Bakuriu's answer above, I've found that this enables me to catch a runtime warning in a similar fashion to how I would catch an error warning, printing out the warning nicely:

import warnings

with warnings.catch_warnings():
    warnings.filterwarnings('error')
    try:
        answer = 1 / 0
    except Warning as e:
        print('error found:', e)

You will probably be able to play around with placing of the warnings.catch_warnings() placement depending on how big of an umbrella you want to cast with catching errors this way.

Margin between items in recycler view Android

  1. Find the attribute card_view:cardUseCompatPadding="true" in cards_layout.xml and delete it. Start app and you will find there is no margin between each cardview item.

  2. Add margin attributes you like. Ex:

    android:layout_marginTop="5dp"
    android:layout_marginBottom="5dp" 
    

Forcing anti-aliasing using css: Is this a myth?

I found a fix...

.text {
            font-size: 15px;  /* for firefox */
            *font-size: 90%; /* % restart the antialiasing for ie, note the * hack */
            font-weight: bold; /* needed, don't know why! */
        }  

Object of custom type as dictionary key

An alternative in Python 2.6 or above is to use collections.namedtuple() -- it saves you writing any special methods:

from collections import namedtuple
MyThingBase = namedtuple("MyThingBase", ["name", "location"])
class MyThing(MyThingBase):
    def __new__(cls, name, location, length):
        obj = MyThingBase.__new__(cls, name, location)
        obj.length = length
        return obj

a = MyThing("a", "here", 10)
b = MyThing("a", "here", 20)
c = MyThing("c", "there", 10)
a == b
# True
hash(a) == hash(b)
# True
a == c
# False

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Please check this link for the reason behind this issue and solution for the error:

http://support.microsoft.com/kb/312629/EN-US/

Microsoft Support Article:

PRB: ThreadAbortException Occurs If You Use Response.End, Response.Redirect, or Server.Transfer Print Print Email Email

To work around this problem, use one of the following methods: For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.

For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End.

For example: Response.Redirect ("nextpage.aspx", false);

If you use this workaround, the code that follows Response.Redirect is executed. For Server.Transfer, use the Server.Execute method instead.

PHP "php://input" vs $_POST

Simple example of how to use it

 <?php  
     if(!isset($_POST) || empty($_POST)) { 
     ?> 
        <form name="form1" method="post" action=""> 
          <input type="text" name="textfield"><br /> 
          <input type="submit" name="Submit" value="submit"> 
        </form> 
   <?php  
        } else { 
        $example = file_get_contents("php://input");
        echo $example;  }  
   ?>

Set Text property of asp:label in Javascript PROPER way

Instead of using a Label use a text input:

<script type="text/javascript">
    onChange = function(ctrl) {
        var txt = document.getElementById("<%= txtResult.ClientID %>");
        if (txt){
            txt.value = ctrl.value;
        }           
    }
</script>

<asp:TextBox ID="txtTest" runat="server" onchange="onChange(this);" />      

<!-- pseudo label that will survive postback -->  
<input type="text" id="txtResult" runat="server" readonly="readonly" tabindex="-1000" style="border:0px;background-color:transparent;" />        

<asp:Button ID="btnTest" runat="server" Text="Test" />

open program minimized via command prompt

I tried this commands in my PC.It is working fine....

To open notepad in minimized mode:

start /min "" "C:\Windows\notepad.exe"

To open MS word in minimized mode:

start /min "" "C:\Program Files\Microsoft Office\Office14\WINWORD.EXE"

How can I present a file for download from an MVC controller?

You can do the same in Razor or in the Controller, like so..

@{
    //do this on the top most of your View, immediately after `using` statement
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");
}

Or in the Controller..

public ActionResult Receipt() {
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");

    return View();
}

I tried this in Chrome and IE9, both is downloading the pdf file.

I probably should add I am using RazorPDF to generate my PDFs. Here is a blog about it: http://nyveldt.com/blog/post/Introducing-RazorPDF

Decode JSON with unknown structure

package main

import "encoding/json"

func main() {
    in := []byte(`{ "votes": { "option_A": "3" } }`)
    var raw map[string]interface{}
    if err := json.Unmarshal(in, &raw); err != nil {
        panic(err)
    }
    raw["count"] = 1
    out, err := json.Marshal(raw)
    if err != nil {
        panic(err)
    }
    println(string(out))
}

https://play.golang.org/p/o8ZwvgsQmoO

get parent's view from a layout

Check my answer here

The use of Layout Inspector tool can be very convenient when you have a complex view or you are using a third party library where you can't add an id to a view

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

I ran into the same issue and the above answers didn't help. I need to debug and find it.

 <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-common</artifactId>
        <version>2.6.0-cdh5.13.1</version>
        <exclusions>
            <exclusion>
                <artifactId>jsp-api</artifactId>
                <groupId>javax.servlet.jsp</groupId>
            </exclusion>
        </exclusions>
    </dependency>

After excluding the jsp-api, it worked for me.

excel vba getting the row,cell value from selection.address

Dim f as Range

Set f=ActiveSheet.Cells.Find(...)

If Not f Is Nothing then
    msgbox "Row=" & f.Row & vbcrlf & "Column=" & f.Column
Else
    msgbox "value not found!"
End If

How to make CSS width to fill parent?

So after research the following is discovered:

For a div#bar setting display:block; width: auto; causes the equivalent of outerWidth:100%;

For a table#bar you need to wrap it in a div with the rules stated below. So your structure becomes:

<div id="foo">
 <div id="barWrap" style="border....">
  <table id="bar" style="width: 100%; border: 0; padding: 0; margin: 0;">

This way the table takes up the parent div 100%, and #barWrap is used to add borders/margin/padding to the #bar table. Note that you will need to set the background of the whole thing in #barWrap and have #bar's background be transparent or the same as #barWrap.

For textarea#bar and input#bar you need to do the same thing as table#bar, the down side is that by removing the borders you stop native widget rendering of the input/textarea and the #barWrap's borders will look a bit different than everything else, so you will probably have to style all your inputs this way.

Deserialize JSON into C# dynamic object?

JsonFx can deserialize JSON content into dynamic objects.

Serialize to/from dynamic types (default for .NET 4.0):

var reader = new JsonReader(); var writer = new JsonWriter();

string input = @"{ ""foo"": true, ""array"": [ 42, false, ""Hello!"", null ] }";
dynamic output = reader.Read(input);
Console.WriteLine(output.array[0]); // 42
string json = writer.Write(output);
Console.WriteLine(json); // {"foo":true,"array":[42,false,"Hello!",null]}

Free Barcode API for .NET

There is a "3 of 9" control on CodeProject: Barcode .NET Control

Is there a way to use two CSS3 box shadows on one element?

You can comma-separate shadows:

box-shadow: inset 0 2px 0px #dcffa6, 0 2px 5px #000;