Programs & Examples On #Rendering

Rendering refers to a computer program formatting data for display or printing.

In Rails, how do you render JSON using a view?

You should be able to do something like this in your respond_to block:

respond_to do |format|
    format.json 
    render :partial => "users/show.json"
end

which will render the template in app/views/users/_show.json.erb.

How to render an ASP.NET MVC view as a string?

If you want to forgo MVC entirely, thereby avoiding all the HttpContext mess...

using RazorEngine;
using RazorEngine.Templating; // For extension methods.

string razorText = System.IO.File.ReadAllText(razorTemplateFileLocation);
string emailBody = Engine.Razor.RunCompile(razorText, "templateKey", typeof(Model), model);

This uses the awesome open source Razor Engine here: https://github.com/Antaris/RazorEngine

How to render string with html tags in Angular 4+?

Use one way flow syntax property binding:

<div [innerHTML]="comment"></div>

From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script> tag but keeps safe content such as the <b> element."

failed to resolve com.android.support:appcompat-v7:22 and com.android.support:recyclerview-v7:21.1.2

in support libraries you always need to add three numbers as version number

Suppose for 22 -> you need to write it as 22.0.0, not just 22

for 22.1 -> 22.1.0

So your dependencies should look like this

compile 'com.android.support:appcompat-v7:22.0.0'
compile 'com.android.support:support-v4:22.0.0'
compile 'com.android.support:cardview-v7:22.0.0'
compile 'com.android.support:recyclerview-v7:22.0.0'

I Programmers language you need to pad extra zeros.

Hope this solves your problem

How to render pdfs using C#

Here is my answer from a different question.

First you need to reference the Adobe Reader ActiveX Control

Adobe Acrobat Browser Control Type Library 1.0

%programfiles&\Common Files\Adobe\Acrobat\ActiveX\AcroPDF.dll

Then you just drag it into your Windows Form from the Toolbox.

And use some code like this to initialize the ActiveX Control.

private void InitializeAdobe(string filePath)
{
    try
    {
        this.axAcroPDF1.LoadFile(filePath);
        this.axAcroPDF1.src = filePath;
        this.axAcroPDF1.setShowToolbar(false);
        this.axAcroPDF1.setView("FitH");
        this.axAcroPDF1.setLayoutMode("SinglePage");
        this.axAcroPDF1.Show();
    }
    catch (Exception ex)
    {
        throw;
    }
}

Make sure when your Form closes that you dispose of the ActiveX Control

this.axAcroPDF1.Dispose();
this.axAcroPDF1 = null;

otherwise Acrobat might be left lying around.

Convert SVG to PNG in Python

A little extension on the answer of jsbueno:

#!/usr/bin/env python

import cairo
import rsvg
from xml.dom import minidom


def convert_svg_to_png(svg_file, output_file):
    # Get the svg files content
    with open(svg_file) as f:
        svg_data = f.read()

    # Get the width / height inside of the SVG
    doc = minidom.parse(svg_file)
    width = int([path.getAttribute('width') for path
                 in doc.getElementsByTagName('svg')][0])
    height = int([path.getAttribute('height') for path
                  in doc.getElementsByTagName('svg')][0])
    doc.unlink()

    # create the png
    img = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
    ctx = cairo.Context(img)
    handler = rsvg.Handle(None, str(svg_data))
    handler.render_cairo(ctx)
    img.write_to_png(output_file)

if __name__ == '__main__':
    from argparse import ArgumentParser

    parser = ArgumentParser()

    parser.add_argument("-f", "--file", dest="svg_file",
                        help="SVG input file", metavar="FILE")
    parser.add_argument("-o", "--output", dest="output", default="svg.png",
                        help="PNG output file", metavar="FILE")
    args = parser.parse_args()

    convert_svg_to_png(args.svg_file, args.output)

Unsupported major.minor version 52.0 when rendering in Android Studio

Changing to Java SDK to Java 8 worked for me. Android Studio settings: File -> other settings ->Default project structure -> JDK location -> jdk1.8.0_71.jdk/Contents/Home

Exporting PDF with jspdf not rendering CSS

You can get the example of css implemented html to pdf conversion using jspdf on following link: JSFiddle Link

This is sample code for the jspdf html to pdf download.

$('#print-btn').click(() => {
    var pdf = new jsPDF('p','pt','a4');
    pdf.addHTML(document.body,function() {
        pdf.save('web.pdf');
    });
})

Can a for loop increment/decrement by more than one?

The last part of the ternary operator allows you to specify the increment step size. For instance, i++ means increment by 1. i+=2 is same as i=i+2,... etc. Example:

let val= [];

for (let i = 0; i < 9; i+=2) {
  val = val + i+",";
}


console.log(val);

Expected results: "2,4,6,8"

'i' can be any floating point or whole number depending on the desired step size.

What version of JBoss I am running?

The version of JBoss should also be visible in the boot log file. Standard install would have that (for linux) in

/var/log/jboss/boot.log

$ head boot.log

08:30:07,477 INFO  [Server] Starting JBoss (MX MicroKernel)...
08:30:07,478 INFO  [Server] Release ID: JBoss [Trinity] 4.2.2.GA (build: SVNTag=JBoss_4_2_2_GA date=200710221139)
08:30:07,478 DEBUG [Server] Using config: org.jboss.system.server.ServerConfigImpl@4277158a
08:30:07,478 DEBUG [Server] Server type: class org.jboss.system.server.ServerImpl
08:30:07,478 DEBUG [Server] Server loaded through: org.jboss.system.server.NoAnnotationURLClassLoader
08:30:07,478 DEBUG [Server] Boot URLs:

so required info int the above case is

Release ID: JBoss [Trinity] 4.2.2.GA (build: SVNTag=JBoss_4_2_2_GA date=200710221139)

New og:image size for Facebook share?

Relying on the PDF that @CBroe posted earlier:

For best og:image results (retina ready & without being cropped) with the current Facebook Standard use:

Size: minimum 1200 x 630px

Ratio: 1.91:1

Pass a String from one Activity to another Activity in Android

In ActivityOne,

Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putExtra("data", somedata);
startActivity(intent);

In ActivityTwo,

Intent intent = getIntent();
String data = intent.getStringExtra("data");

How can I reference a commit in an issue comment on GitHub?

Answer above is missing an example which might not be obvious (it wasn't to me).

Url could be broken down into parts

https://github.com/liufa/Tuplinator/commit/f36e3c5b3aba23a6c9cf7c01e7485028a23c3811
                  \_____/\________/       \_______________________________________/
                   |        |                              |
            Account name    |                      Hash of revision
                        Project name              

Hash can be found here (you can click it and will get the url from browser).

enter image description here

Hope this saves you some time.

Handling the null value from a resultset in JAVA

I was able to do this:

String a;
if(rs.getString("column") != null)
{
    a = "Hello world!";
}
else
{
    a = "Bye world!";
}

Disable all gcc warnings

-w is the GCC-wide option to disable warning messages.

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

This is nice but doesn't answer the question:

"A VARCHAR should always be used instead of TINYTEXT." Tinytext is useful if you have wide rows - since the data is stored off the record. There is a performance overhead, but it does have a use.

How To Add An "a href" Link To A "div"?

Try creating a class named overlay and apply the following css to it:

a.overlay { width: 100%; height:100%; position: absolute; }

Make sure it is placed in a positioned element.

Now simply place an <a> tag with that class inside the div you want to be linkable:

<div id="buttonOne">
  <a class="overlay" href="......."></a>
    <div id="linkedinB">
       <img src="img/linkedinB.png" alt="never forget the alt tag" width="40" height="40"/>
    </div>
 </div>

PhilipK's suggestion might work but it won't validate because you can't place a block element (div) inside an inline element (a). And when your website doesn't validate the W3C Ninja's will come for you!

An other advice would be to try avoiding inline styling.

HTML meta tag for content language

<meta name="language" content="Spanish">

This isn't defined in any specification (including the HTML5 draft)

<meta http-equiv="content-language" content="es">

This is a poor man's version of a real HTTP header and should really be expressed in the headers. For example:

Content-language: es
Content-type: text/html;charset=UTF-8

It says that the document is intended for Spanish language speakers (it doesn't, however mean the document is written in Spanish; it could, for example, be written in English as part of a language course for Spanish speakers).

From the spec:

The Content-Language entity-header field describes the natural language(s) of the intended audience for the enclosed entity. Note that this might not be equivalent to all the languages used within the entity-body.

If you want to state that a document is written in Spanish then use:

<html lang="es">

Using crontab to execute script every minute and another every 24 hours

This is the format of /etc/crontab:

# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed

I recommend copy & pasting that into the top of your crontab file so that you always have the reference handy. RedHat systems are setup that way by default.

To run something every minute:

* * * * * username /var/www/html/a.php

To run something at midnight of every day:

0 0 * * * username /var/www/html/reset.php

You can either include /usr/bin/php in the command to run, or you can make the php scripts directly executable:

chmod +x file.php

Start your php file with a shebang so that your shell knows which interpreter to use:

#!/usr/bin/php
<?php
// your code here

A valid provisioning profile for this executable was not found for debug mode

This solution worked for me

  1. Go to Xcode --> Preferences --> Account.
  2. In the provisioning profiles section, right click and open with finder.
  3. Delete all provisioning profiles from the provisioning profile folder.
  4. Finally, go back to Xcode and click the refresh button.

I hope that helps!

Https to http redirect using htaccess

The difference between http and https is that https requests are sent over an ssl-encrypted connection. The ssl-encrypted connection must be established between the browser and the server before the browser sends the http request.

Https requests are in fact http requests that are sent over an ssl encrypted connection. If the server rejects to establish an ssl encrypted connection then the browser will have no connection to send the request over. The browser and the server will have no way of talking to each other. The browser will not be able to send the url that it wants to access and the server will not be able to respond with a redirect to another url.

So this is not possible. If you want to respond to https links, then you need an ssl certificate.

Getting around the Max String size in a vba function?

Excel only shows 255 characters but in fact if more than 255 characters are saved, to see the complete string, consult it in the immediate window

Press Crl + G and type ?RunWhat in the immediate window and press Enter

li:before{ content: "¦"; } How to Encode this Special Character as a Bullit in an Email Stationery?

You shouldn't use LIs in email. They are unpredictable across email clients. Instead you have to code each bullet point like this:

<table width="100%" cellspacing="0" border="0" cellpadding="0">
    <tr>
        <td align="left" valign="top" width="10" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">&bull;</td>
        <td align="left" valign="top" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">This is the first bullet point</td>
    </tr>
    <tr>
        <td align="left" valign="top" width="10" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">&bull;</td>
        <td align="left" valign="top" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">This is the second bullet point</td>
    </tr>
</table>

This will ensure that your bullets work in every email client.

The character encoding of the plain text document was not declared - mootool script

In my case in ASP MVC it was a method in controller that was returning null to View because of a wrong if statement.

if (condition)
{
    return null;
}

Condition fixed and I returned View, Problem fixed. There was nothing with encoding but I don't know why that was my error.

return View(result); // result is View's model

How do I return clean JSON from a WCF Service?

In your IServece.cs add the following tag : BodyStyle = WebMessageBodyStyle.Bare

 [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = "Getperson/{id}")]

    List<personClass> Getperson(string id);

Submit form without reloading page

You can't do this using forms the normal way. Instead, you want to use AJAX.

A sample function that will submit the data and alert the page response.

function submitForm() {
    var http = new XMLHttpRequest();
    http.open("POST", "<<whereverTheFormIsGoing>>", true);
    http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    var params = "search=" + <<get search value>>; // probably use document.getElementById(...).value
    http.send(params);
    http.onload = function() {
        alert(http.responseText);
    }
}

How to find the cumulative sum of numbers in a list?

Behold:

a = [4, 6, 12]
reduce(lambda c, x: c + [c[-1] + x], a, [0])[1:]

Will output (as expected):

[4, 10, 22]

Creating a zero-filled pandas data frame

Assuming having a template DataFrame, which one would like to copy with zero values filled here...

If you have no NaNs in your data set, multiplying by zero can be significantly faster:

In [19]: columns = ["col{}".format(i) for i in xrange(3000)]                                                                                       

In [20]: indices = xrange(2000)

In [21]: orig_df = pd.DataFrame(42.0, index=indices, columns=columns)

In [22]: %timeit d = pd.DataFrame(np.zeros_like(orig_df), index=orig_df.index, columns=orig_df.columns)
100 loops, best of 3: 12.6 ms per loop

In [23]: %timeit d = orig_df * 0.0
100 loops, best of 3: 7.17 ms per loop

Improvement depends on DataFrame size, but never found it slower.

And just for the heck of it:

In [24]: %timeit d = orig_df * 0.0 + 1.0
100 loops, best of 3: 13.6 ms per loop

In [25]: %timeit d = pd.eval('orig_df * 0.0 + 1.0')
100 loops, best of 3: 8.36 ms per loop

But:

In [24]: %timeit d = orig_df.copy()
10 loops, best of 3: 24 ms per loop

EDIT!!!

Assuming you have a frame using float64, this will be the fastest by a huge margin! It is also able to generate any value by replacing 0.0 to the desired fill number.

In [23]: %timeit d = pd.eval('orig_df > 1.7976931348623157e+308 + 0.0')
100 loops, best of 3: 3.68 ms per loop

Depending on taste, one can externally define nan, and do a general solution, irrespective of the particular float type:

In [39]: nan = np.nan
In [40]: %timeit d = pd.eval('orig_df > nan + 0.0')
100 loops, best of 3: 4.39 ms per loop

Is there any sizeof-like method in Java?

The Instrumentation class has a getObjectSize() method however, you shouldn't need to use it at runtime. The easiest way to examine memory usage is to use a profiler which is designed to help you track memory usage.

Finding the id of a parent div using Jquery

1.

$(this).parent().attr("id");

2.

There must be a large number of ways! One could be to hide an element that contains the answer, e.g.

<div>
    Volume = <input type="text" />
    <button type="button">Check answer</button>
    <span style="display: hidden">3.93e-6&lt;/span>
    <div></div>
</div>

And then have similar jQuery code to the above to grab that:

$("button").click(function () 
{
    var correct = Number($(this).parent().children("span").text());
    validate ($(this).siblings("input").val(),correct);
    $(this).siblings("div").html(feedback);
});

bear in mind that if you put the answer in client code then they can see it :) The best way to do this is to validate it server-side, but for an app with limited scope this may not be a problem.

How to handle-escape both single and double quotes in an SQL-Update statement

When SET QUOTED_IDENTIFIER is OFF, literal strings in expressions can be delimited by single or double quotation marks.

If a literal string is delimited by double quotation marks, the string can contain embedded single quotation marks, such as apostrophes.

ReportViewer Client Print Control "Unable to load client print control"?

I have had the same problem (on several different servers). Applying SP3 and Report Viewer SP1 has helped on some of the servers, allowing the client machines to connect and download the control with no problem. However, I have had one server that, even after applying the updates, when accessing the report viewer using a client machine, it was still giving me the error. On looking into the exact URL GET request that is being sent, I discovered that it is possible to force the client machine to connect directly to the Report Server to download the control.

The user would need to enter the following url:

http://reportservername/Reports/Reserved.ReportViewerWebControl.axd?ReportSession=51bjqv45xydgos2wghu5ceza&ControlID=7617dedbf0234f89b80cad8e64431014&Culture=2057&UICulture=9&ReportStack=1&OpType=PrintHtml

This should then pop up the required download/install prompt.

How do I set up NSZombieEnabled in Xcode 4?

On In Xcode 7

?<

or select Edit Scheme from Product > Scheme Menu

select Enable Zombie Objects form the Diagnostics tab

xcode 7 zombie flag

As alternative, if you prefer .xcconfig files you can read this article https://therealbnut.wordpress.com/2012/01/01/setting-xcode-4-0-environment-variables-from-a-script/

How to update Python?

I have always just installed the new version on top and never had any issues. Do make sure that your path is updated to point to the new version though.

RegEx for valid international mobile phone number

^\+[1-9]{1}[0-9]{7,11}$ 

The Regular Expression ^\+[1-9]{1}[0-9]{7,11}$ fails for "+290 8000" and similar valid numbers that are shorter than 8 digits.

The longest numbers could be something like 3 digit country code, 3 digit area code, 8 digit subscriber number, making 14 digits.

How to detect the swipe left or Right in Android?

the best answer is @Gal Rom 's. there is more information about it: touch event return's to child views first. and if you define onClick or onTouch listener for them, parnt view (for example fragment) will not receive any touch listener. So if you want define swipe listener for fragment in this situation, you must implement it in a new class:

    package com.neganet.QRelations.fragments;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.FrameLayout;

public class SwipeListenerFragment extends FrameLayout {
    private float x1,x2;
    static final int MIN_DISTANCE=150;
    private onSwipeEventDetected mSwipeDetectedListener;


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

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

    public SwipeListenerFragment(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean result=false;
        switch(ev.getAction())
        {
            case MotionEvent.ACTION_DOWN:
                x1 = ev.getX();
                break;
            case MotionEvent.ACTION_UP:
                x2 = ev.getX();
                float deltaX = x2 - x1;
                if (Math.abs(deltaX) > MIN_DISTANCE)
                {
                    if(deltaX<0)
                    {
                        result=true;
                        if(mSwipeDetectedListener!=null)
                            mSwipeDetectedListener.swipeLeftDetected();

                    }else if(deltaX>0){
                        result=true;
                        if(mSwipeDetectedListener!=null)
                            mSwipeDetectedListener.swipeRightDetected();
                    }
                }
                break;
        }
        return result;
    }

    public interface onSwipeEventDetected
    {
        public void swipeLeftDetected();
        public void swipeRightDetected();

    }

    public void registerToSwipeEvents(onSwipeEventDetected listener)
    {
        this.mSwipeDetectedListener=listener;
    }
}

I changed @Gal Rom 's class. So it can detect both right and left swipe and specially it returns onInterceptTouchEvent true after detect. its important because if we dont do it some times child views maybe receive event and both of Swipe for fragment and onClick for child view (for example) runs and cause some issues. after making this class, you must change your fragment xml file:

    <com.neganet.QRelations.fragments.SwipeListenerFragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:id="@+id/main_list_layout"
    android:clickable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:layout_height="match_parent" tools:context="com.neganet.QRelations.fragments.mainList"
    android:background="@color/main_frag_back">

    <!-- TODO: Update blank fragment layout -->
    <android.support.v7.widget.RecyclerView
        android:id="@+id/farazList"
        android:scrollbars="horizontal"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="left|center_vertical" />
</com.neganet.QRelations.fragments.SwipeListenerFragment>

you see that begin tag is the class that we made. now in fragment class:

            View view=inflater.inflate(R.layout.fragment_main_list, container, false);
        SwipeListenerFragment tdView=(SwipeListenerFragment) view;
        tdView.registerToSwipeEvents(this);


and then Implement SwipeListenerFragment.onSwipeEventDetected in it:

        @Override
    public void swipeLeftDetected() {
        Toast.makeText(getActivity(), "left", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void swipeRightDetected() {
        Toast.makeText(getActivity(), "right", Toast.LENGTH_SHORT).show();
    }

It's a little complicated but works perfect :)

Regular expression include and exclude special characters

[a-zA-Z0-9~@#\^\$&\*\(\)-_\+=\[\]\{\}\|\\,\.\?\s]*

This would do the matching, if you only want to allow that just wrap it in ^$ or any other delimiters that you see appropriate, if you do this no specific disallow logic is needed.

Creating an Instance of a Class with a variable in Python

Let's say you have three classes: Enemy1, Enemy2, Enemy3. This is how you instantiate them directly:

Enemy1()
Enemy2()
Enemy3()

but this will also work:

x = Enemy1
x()
x = Enemy2
x()
x = Enemy3
x()

Is this what you meant?

True/False vs 0/1 in MySQL

In MySQL TRUE and FALSE are synonyms for TINYINT(1).

So therefore its basically the same thing, but MySQL is converting to 0/1 - so just use a TINYINT if that's easier for you

P.S.
The performance is likely to be so minuscule (if at all), that if you need to ask on StackOverflow, then it won't affect your database :)

How to save RecyclerView's scroll position using RecyclerView.State?

On Android API Level 28, I simply ensure that I set up my LinearLayoutManager and RecyclerView.Adapter in my Fragment#onCreateView method, and everything Just Worked™?. I didn't need to do any onSaveInstanceState or onRestoreInstanceState work.

Eugen Pechanec's answer explains why this works.

Error in spring application context schema

I also faced this problem and fixed it by removing version part from the XSD name.

http://www.springframework.org/schema/beans/spring-beans-4.2.xsd to http://www.springframework.org/schema/beans/spring-beans.xsd

Versions less XSD's are mapped to the current version of the framework used in the application.

No tests found with test runner 'JUnit 4'

I was facing the same problem and I debugged it to bad examples on the web and internals of junit. Basically don't make your class extend TestCase as some examples show for Junit 4.x. Use some naming convention Test or if you want to have an annotation you can use @RunWith(JUnit4.class).

If you need access to assert methods extend Assert or use static imports.

If your class extends TestCase then even if you use Junit 4 Runner it will be run as 3. This is because in the initialization code there is detection:

See JUnit3Builder and the lines:

boolean isPre4Test(Class<?> testClass) {
    return junit.framework.TestCase.class.isAssignableFrom(testClass);
}

This returns true and the test for junit4 compatibility won't be tried.

Use grep to report back only line numbers

You're going to want the second field after the colon, not the first.

grep -n "text to find" file.txt | cut -f2 -d:

'cannot open git-upload-pack' error in Eclipse when cloning or pushing git repository

I added -Dhttps.protocols=TLSv1.1,TLSv1.2 to eclipse.ini and it's working. I use java 1.7

Highlight the difference between two strings in PHP

This is a nice one, also http://paulbutler.org/archives/a-simple-diff-algorithm-in-php/

Solving the problem is not as simple as it seems, and the problem bothered me for about a year before I figured it out. I managed to write my algorithm in PHP, in 18 lines of code. It is not the most efficient way to do a diff, but it is probably the easiest to understand.

It works by finding the longest sequence of words common to both strings, and recursively finding the longest sequences of the remainders of the string until the substrings have no words in common. At this point it adds the remaining new words as an insertion and the remaining old words as a deletion.

You can download the source here: PHP SimpleDiff...

href="javascript:" vs. href="javascript:void(0)"

It does not cause problems but it's a trick to do the same as PreventDefault

when you're way down in the page and an anchor as:

<a href="#" onclick="fn()">click here</a>

you will jump to the top and the URL will have the anchor # as well, to avoid this we simply return false; or use javascript:void(0);

regarding your examples

<a onclick="fn()">Does not appear as a link, because there's no href</a>

just do a {text-decoration:underline;} and you will have "link a-like"

<a href="javascript:void(0)" onclick="fn()">fn is called</a>
<a href="javascript:" onclick="fn()">fn is called too!</a>

it's ok, but in your function at the end, just return false; to prevent the default behavior, you don't need to do anything more.

How to convert Varchar to Double in sql?

This might be more desirable, that is use float instead

SELECT fullName, CAST(totalBal as float) totalBal FROM client_info ORDER BY totalBal DESC

Checking for multiple conditions using "when" on single task in ansible

You can use like this.

when: condition1 == "condition1" or condition2 == "condition2"

Link to official docs: The When Statement.

Also Please refer to this gist: https://gist.github.com/marcusphi/6791404

How to screenshot website in JavaScript client-side / how Google did it? (no need to access HDD)

I needed to snapshot a div on the page (for a webapp I wrote) that is protected by JWT's and makes very heavy use of Angular.

I had no luck with any of the above methods.

I ended up taking the outerHTML of the div I needed, cleaning it up a little (*) and then sending it to the server where I run wkhtmltopdf against it.

This is working very well for me.

(*) various input devices in my pages didn't render as checked or have their text values when viewed in the pdf... So I run a little bit of jQuery on the html before I send it up for rendering. ex: for text input items -- I copy their .val()'s into 'value' attributes, which then can be seen by wkhtmlpdf

Smart way to truncate long strings

Use following code

 function trancateTitle (title) {
    var length = 10;
    if (title.length > length) {
       title = title.substring(0, length)+'...';
    }
    return title;
}

PPT to PNG with transparent background

Import To Google Slides

Select desired slide and set background to solid transparent

the click "File->Download as PNG"

Deleting a SQL row ignoring all foreign keys and constraints

I wanted to delete all records from both tables because it was all test data. I used SSMS GUI to temporarily disable a FK constraint, then I ran a DELETE query on both tables, and finally I re-enabled the FK constraint.

To disable the FK constraint:

  1. expand the database object [1]
  2. expand the dependant table object [2]
  3. expand the 'Keys' folder
  4. right click on the foreign key
  5. choose the 'Modify' option
  6. change the 'Enforce Foreign Key Constraint' option to 'No'
  7. close the 'Foreign Key Relationships' window
  8. close the table designer tab
  9. when prompted confirm save changes
  10. run necessary delete queries
  11. re-enable foreign key constraint the same way you just disabled it.

[1] in the 'Object Explorer' pane, can be accessed via the 'View' menu option, or key F8

[2] if you're not sure which table is the dependant one, you can check by right clicking the table in question and selecting the 'View Dependencies' option.

Add/remove class with jquery based on vertical scroll?

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();

     //>=, not <=
    if (scroll >= 500) {
        //clearHeader, not clearheader - caps H
        $(".clearHeader").addClass("darkHeader");
    }
}); //missing );

Fiddle

Also, by removing the clearHeader class, you're removing the position:fixed; from the element as well as the ability of re-selecting it through the $(".clearHeader") selector. I'd suggest not removing that class and adding a new CSS class on top of it for styling purposes.

And if you want to "reset" the class addition when the users scrolls back up:

$(window).scroll(function() {    
    var scroll = $(window).scrollTop();

    if (scroll >= 500) {
        $(".clearHeader").addClass("darkHeader");
    } else {
        $(".clearHeader").removeClass("darkHeader");
    }
});

Fiddle

edit: Here's version caching the header selector - better performance as it won't query the DOM every time you scroll and you can safely remove/add any class to the header element without losing the reference:

$(function() {
    //caches a jQuery object containing the header element
    var header = $(".clearHeader");
    $(window).scroll(function() {
        var scroll = $(window).scrollTop();

        if (scroll >= 500) {
            header.removeClass('clearHeader').addClass("darkHeader");
        } else {
            header.removeClass("darkHeader").addClass('clearHeader');
        }
    });
});

Fiddle

How to get a Color from hexadecimal Color String

It's

int color =  Color.parseColor("colorstring");

How to start an application using android ADB tools?

adb shell am start -n '<appPackageName>/.<appActitivityName>

Ex:

adb shell am start -n 'com.android.settings/.wifi.WifiStatusTest'

You can use APK-INFO application to know the list of App Activities with respect to each App Package

Android: View.setID(int id) programmatically - how to avoid ID conflicts?

Also you can define ids.xml in res/values. You can see an exact example in android's sample code.

samples/ApiDemos/src/com/example/android/apis/RadioGroup1.java
samples/ApiDemp/res/values/ids.xml

How to convert a const char * to std::string

std::string the_string(c_string);
if(the_string.size() > max_length)
    the_string.resize(max_length);

UIBarButtonItem in navigation bar programmatically?

func viewDidLoad(){
let homeBtn: UIButton = UIButton(type: UIButtonType.custom)

        homeBtn.setImage(UIImage(named: "Home.png"), for: [])

        homeBtn.addTarget(self, action: #selector(homeAction), for: UIControlEvents.touchUpInside)

        homeBtn.frame = CGRect(x: 0, y: 0, width: 30, height: 30)

        let homeButton = UIBarButtonItem(customView: homeBtn)


        let backBtn: UIButton = UIButton(type: UIButtonType.custom)

        backBtn.setImage(UIImage(named: "back.png"), for: [])

        backBtn.addTarget(self, action: #selector(backAction), for: UIControlEvents.touchUpInside)

        backBtn.frame = CGRect(x: -10, y: 0, width: 30, height: 30)

        let backButton = UIBarButtonItem(customView: backBtn)
        self.navigationItem.setLeftBarButtonItems([backButton,homeButton], animated: true)
}

}

How do I center text horizontally and vertically in a TextView?

You need to set TextView Gravity (Center Horizontal & Center Vertical) like this:

android:layout_centerHorizontal="true"   

and

android:layout_centerVertical="true"

And dynamically using:

textview.setGravity(Gravity.CENTER);
textView.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);

Resolving ORA-4031 "unable to allocate x bytes of shared memory"

Don't forget about fragmentation. If you have a lot of traffic, your pools can be fragmented and even if you have several MB free, there could be no block larger than 4KB. Check size of largest free block with a query like:

 select
  '0 (<140)' BUCKET, KSMCHCLS, KSMCHIDX,
  10*trunc(KSMCHSIZ/10) "From",
  count(*) "Count" ,
  max(KSMCHSIZ) "Biggest",
  trunc(avg(KSMCHSIZ)) "AvgSize",
  trunc(sum(KSMCHSIZ)) "Total"
from
  x$ksmsp
where
  KSMCHSIZ<140
and
  KSMCHCLS='free'
group by
  KSMCHCLS, KSMCHIDX, 10*trunc(KSMCHSIZ/10)
UNION ALL
select
  '1 (140-267)' BUCKET,
  KSMCHCLS,
  KSMCHIDX,
  20*trunc(KSMCHSIZ/20) ,
  count(*) ,
  max(KSMCHSIZ) ,
  trunc(avg(KSMCHSIZ)) "AvgSize",
  trunc(sum(KSMCHSIZ)) "Total"
from
  x$ksmsp
where
  KSMCHSIZ between 140 and 267
and
  KSMCHCLS='free'
group by
  KSMCHCLS, KSMCHIDX, 20*trunc(KSMCHSIZ/20)
UNION ALL
select
  '2 (268-523)' BUCKET,
  KSMCHCLS,
  KSMCHIDX,
  50*trunc(KSMCHSIZ/50) ,
  count(*) ,
  max(KSMCHSIZ) ,
  trunc(avg(KSMCHSIZ)) "AvgSize",
  trunc(sum(KSMCHSIZ)) "Total"
from
  x$ksmsp
where
  KSMCHSIZ between 268 and 523
and
  KSMCHCLS='free'
group by
  KSMCHCLS, KSMCHIDX, 50*trunc(KSMCHSIZ/50)
UNION ALL
select
  '3-5 (524-4107)' BUCKET,
  KSMCHCLS,
  KSMCHIDX,
  500*trunc(KSMCHSIZ/500) ,
  count(*) ,
  max(KSMCHSIZ) ,
  trunc(avg(KSMCHSIZ)) "AvgSize",
  trunc(sum(KSMCHSIZ)) "Total"
from
  x$ksmsp
where
  KSMCHSIZ between 524 and 4107
and
  KSMCHCLS='free'
group by
  KSMCHCLS, KSMCHIDX, 500*trunc(KSMCHSIZ/500)
UNION ALL
select
  '6+ (4108+)' BUCKET,
  KSMCHCLS,
  KSMCHIDX,
  1000*trunc(KSMCHSIZ/1000) ,
  count(*) ,
  max(KSMCHSIZ) ,
  trunc(avg(KSMCHSIZ)) "AvgSize",
  trunc(sum(KSMCHSIZ)) "Total"
from
  x$ksmsp
where
  KSMCHSIZ >= 4108
and
  KSMCHCLS='free'
group by
  KSMCHCLS, KSMCHIDX, 1000*trunc(KSMCHSIZ/1000);

Code from

How can I remove Nan from list Python/NumPy

I noticed that Pandas for example will return 'nan' for blank values. Since it's not a string you need to convert it to one in order to match it. For example:

ulist = df.column1.unique() #create a list from a column with Pandas which 
for loc in ulist:
    loc = str(loc)   #here 'nan' is converted to a string to compare with if
    if loc != 'nan':
        print(loc)

Maven : error in opening zip file when running maven

Deleting the entire local m2 repo may not be advisable. As in my case I have hundreds and hundreds of jars in my local, I don't want to re-download them all just for one jar. Most of the above answers didn't work for me, here is what I did.

STEP:1: Ensure if you are downloading from the correct Maven repo in you settings.xml. In my case it was referring to http://central.maven.org/maven2/ as https://repo1.maven.org/maven2/. So it was getting corrupted or going otherwise?

STEP:2: Delete the folder containing the artifact and other details in your local machine.This will force it download it again upon next build

STEP:3: mvn clean install :).

Hope it helps.

Convert MySQL to SQlite

Here is a list of converters. (snapshot at archive.today)


An alternative method that would work even on windows but is rarely mentioned is: use an ORM class that abstracts specific database differences away for you. e.g. you get these in PHP (RedBean), Python (Django's ORM layer, Storm, SqlAlchemy), Ruby on Rails (ActiveRecord), Cocoa (CoreData) etc.

i.e. you could do this:

  1. Load data from source database using the ORM class.
  2. Store data in memory or serialize to disk.
  3. Store data into destination database using the ORM class.

How to write UTF-8 in a CSV file

For python2 you can use this code before csv_writer.writerows(rows)
This code will NOT convert integers to utf-8 strings

def encode_rows_to_utf8(rows):
    encoded_rows = []
    for row in rows:
        encoded_row = []
        for value in row:
            if isinstance(value, basestring):
                value = unicode(value).encode("utf-8")
            encoded_row.append(value)
        encoded_rows.append(encoded_row)
    return encoded_rows

Format cell if cell contains date less than today

=$W$4<=TODAY()

Returns true for dates up to and including today, false otherwise.

Understanding dispatch_async

All of the DISPATCH_QUEUE_PRIORITY_X queues are concurrent queues (meaning they can execute multiple tasks at once), and are FIFO in the sense that tasks within a given queue will begin executing using "first in, first out" order. This is in comparison to the main queue (from dispatch_get_main_queue()), which is a serial queue (tasks will begin executing and finish executing in the order in which they are received).

So, if you send 1000 dispatch_async() blocks to DISPATCH_QUEUE_PRIORITY_DEFAULT, those tasks will start executing in the order you sent them into the queue. Likewise for the HIGH, LOW, and BACKGROUND queues. Anything you send into any of these queues is executed in the background on alternate threads, away from your main application thread. Therefore, these queues are suitable for executing tasks such as background downloading, compression, computation, etc.

Note that the order of execution is FIFO on a per-queue basis. So if you send 1000 dispatch_async() tasks to the four different concurrent queues, evenly splitting them and sending them to BACKGROUND, LOW, DEFAULT and HIGH in order (ie you schedule the last 250 tasks on the HIGH queue), it's very likely that the first tasks you see starting will be on that HIGH queue as the system has taken your implication that those tasks need to get to the CPU as quickly as possible.

Note also that I say "will begin executing in order", but keep in mind that as concurrent queues things won't necessarily FINISH executing in order depending on length of time for each task.

As per Apple:

https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html

A concurrent dispatch queue is useful when you have multiple tasks that can run in parallel. A concurrent queue is still a queue in that it dequeues tasks in a first-in, first-out order; however, a concurrent queue may dequeue additional tasks before any previous tasks finish. The actual number of tasks executed by a concurrent queue at any given moment is variable and can change dynamically as conditions in your application change. Many factors affect the number of tasks executed by the concurrent queues, including the number of available cores, the amount of work being done by other processes, and the number and priority of tasks in other serial dispatch queues.

Basically, if you send those 1000 dispatch_async() blocks to a DEFAULT, HIGH, LOW, or BACKGROUND queue they will all start executing in the order you send them. However, shorter tasks may finish before longer ones. Reasons behind this are if there are available CPU cores or if the current queue tasks are performing computationally non-intensive work (thus making the system think it can dispatch additional tasks in parallel regardless of core count).

The level of concurrency is handled entirely by the system and is based on system load and other internally determined factors. This is the beauty of Grand Central Dispatch (the dispatch_async() system) - you just make your work units as code blocks, set a priority for them (based on the queue you choose) and let the system handle the rest.

So to answer your above question: you are partially correct. You are "asking that code" to perform concurrent tasks on a global concurrent queue at the specified priority level. The code in the block will execute in the background and any additional (similar) code will execute potentially in parallel depending on the system's assessment of available resources.

The "main" queue on the other hand (from dispatch_get_main_queue()) is a serial queue (not concurrent). Tasks sent to the main queue will always execute in order and will always finish in order. These tasks will also be executed on the UI Thread so it's suitable for updating your UI with progress messages, completion notifications, etc.

Writing sqlplus output to a file

Make sure you have the access to the directory you are trying to spool. I tried to spool to root and it did not created the file (e.g c:\test.txt). You can check where you are spooling by issuing spool command.

Case Insensitive String comp in C

As others have stated, there is no portable function that works on all systems. You can partially circumvent this with simple ifdef:

#include <stdio.h>

#ifdef _WIN32
#include <string.h>
#define strcasecmp _stricmp
#else // assuming POSIX or BSD compliant system
#include <strings.h>
#endif

int main() {
    printf("%d", strcasecmp("teSt", "TEst"));
}

How to convert datatype:object to float64 in python?

X = np.array(X, dtype=float)

You can use this to convert to array of float in python 3.7.6

JAXB: How to ignore namespace during unmarshalling XML document?

I believe you must add the namespace to your xml document, with, for example, the use of a SAX filter.

That means:

  • Define a ContentHandler interface with a new class which will intercept SAX events before JAXB can get them.
  • Define a XMLReader which will set the content handler

then link the two together:

public static Object unmarshallWithFilter(Unmarshaller unmarshaller,
java.io.File source) throws FileNotFoundException, JAXBException 
{
    FileReader fr = null;
    try {
        fr = new FileReader(source);
        XMLReader reader = new NamespaceFilterXMLReader();
        InputSource is = new InputSource(fr);
        SAXSource ss = new SAXSource(reader, is);
        return unmarshaller.unmarshal(ss);
    } catch (SAXException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } catch (ParserConfigurationException e) {
        //not technically a jaxb exception, but close enough
        throw new JAXBException(e);
    } finally {
        FileUtil.close(fr); //replace with this some safe close method you have
    }
}

Maximum Java heap size of a 32-bit JVM on a 64-bit OS

You can ask the Java Runtime:

public class MaxMemory {
    public static void main(String[] args) {
        Runtime rt = Runtime.getRuntime();
        long totalMem = rt.totalMemory();
        long maxMem = rt.maxMemory();
        long freeMem = rt.freeMemory();
        double megs = 1048576.0;

        System.out.println ("Total Memory: " + totalMem + " (" + (totalMem/megs) + " MiB)");
        System.out.println ("Max Memory:   " + maxMem + " (" + (maxMem/megs) + " MiB)");
        System.out.println ("Free Memory:  " + freeMem + " (" + (freeMem/megs) + " MiB)");
    }
}

This will report the "Max Memory" based upon default heap allocation. So you still would need to play with -Xmx (on HotSpot). I found that running on Windows 7 Enterprise 64-bit, my 32-bit HotSpot JVM can allocate up to 1577MiB:

[C:scratch]> java -Xmx1600M MaxMemory
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.
[C:scratch]> java -Xmx1590M MaxMemory
Total Memory: 2031616 (1.9375 MiB)
Max Memory:   1654456320 (1577.8125 MiB)
Free Memory:  1840872 (1.75559234619 MiB)
[C:scratch]>

Whereas with a 64-bit JVM on the same OS, of course it's much higher (about 3TiB)

[C:scratch]> java -Xmx3560G MaxMemory
Error occurred during initialization of VM
Could not reserve enough space for object heap
[C:scratch]> java -Xmx3550G MaxMemory
Total Memory: 94240768 (89.875 MiB)
Max Memory:   3388252028928 (3184151.84297 MiB)
Free Memory:  93747752 (89.4048233032 MiB)
[C:scratch]>

As others have already mentioned, it depends on the OS.

  • For 32-bit Windows: it'll be <2GB (Windows internals book says 2GB for user processes)
  • For 32-bit BSD / Linux: <3GB (from the Devil Book)
  • For 32-bit MacOS X: <4GB (from Mac OS X internals book)
  • Not sure about 32-bit Solaris, try the above code and let us know.

For a 64-bit host OS, if the JVM is 32-bit, it'll still depend, most likely like above as demonstrated.

-- UPDATE 20110905: I just wanted to point out some other observations / details:

  • The hardware that I ran this on was 64-bit with 6GB of actual RAM installed. The operating system was Windows 7 Enterprise, 64-bit
  • The actual amount of Runtime.MaxMemory that can be allocated also depends on the operating system's working set. I once ran this while I also had VirtualBox running and found I could not successfully start the HotSpot JVM with -Xmx1590M and had to go smaller. This also implies that you may get more than 1590M depending upon your working set size at the time (though I still maintain it'll be under 2GiB for 32-bit because of Windows' design)

Save attachments to a folder and rename them

See ReceivedTime Property

http://msdn.microsoft.com/en-us/library/office/aa171873(v=office.11).aspx

You added another \ to the end of C:\Temp\ in the SaveAs File line. Could be a problem. Do a test first before adding a path separator.

dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd H-mm")  
saveFolder = "C:\Temp"

You have not set objAtt so there is no need for "Set objAtt = Nothing". If there was it would be just before End Sub not in the loop.


Public Sub saveAttachtoDisk (itm As Outlook.MailItem) 
    Dim objAtt As Outlook.Attachment 
    Dim saveFolder As String Dim dateFormat
    dateFormat = Format(itm.ReceivedTime, "yyyy-mm-dd H-mm")  saveFolder = "C:\Temp"
    For Each objAtt In itm.Attachments
        objAtt.SaveAsFile saveFolder & "\" & dateFormat & objAtt.DisplayName
    Next
End Sub

Re: It worked the first day I started tinkering but after that it stopped saving files.

This is usually due to Security settings. It is a "trap" set for first time users to allow macros then take it away. http://www.slipstick.com/outlook-developer/how-to-use-outlooks-vba-editor/

How to save all console output to file in R?

  1. If you want to get error messages saved in a file

    zz <- file("Errors.txt", open="wt")
    sink(zz, type="message")
    

    the output will be:

    Error in print(errr) : object 'errr' not found
    Execution halted
    

    This output will be saved in a file named Errors.txt

  2. In case, you want printed values of console to a file you can use 'split' argument:

    zz <- file("console.txt", open="wt")
    sink(zz,  split=TRUE)
    print("cool")
    print(errr)
    

    output will be:

    [1] "cool"
    

    in console.txt file. So all your console output will be printed in a file named console.txt

How do you use String.substringWithRange? (or, how do Ranges work in Swift?)

NOTE: @airspeedswift makes some very insightful points on the trade-offs of this approach, particularly the hidden performance impacts. Strings are not simple beasts, and getting to a particular index may take O(n) time, which means a loop that uses a subscript can be O(n^2). You have been warned.

You just need to add a new subscript function that takes a range and uses advancedBy() to walk to where you want:

import Foundation

extension String {
    subscript (r: Range<Int>) -> String {
        get {
            let startIndex = self.startIndex.advancedBy(r.startIndex)
            let endIndex = startIndex.advancedBy(r.endIndex - r.startIndex)

            return self[Range(start: startIndex, end: endIndex)]
        }
    }
}

var s = "Hello, playground"

println(s[0...5]) // ==> "Hello,"
println(s[0..<5]) // ==> "Hello"

(This should definitely be part of the language. Please dupe rdar://17158813)

For fun, you can also add a + operator onto the indexes:

func +<T: ForwardIndex>(var index: T, var count: Int) -> T {
  for (; count > 0; --count) {
    index = index.succ()
  }
  return index
}

s.substringWithRange(s.startIndex+2 .. s.startIndex+5)

(I don't know yet if this one should be part of the language or not.)

How to prevent a browser from storing passwords

In such a situation, I populate the password field with some random characters just after the original password is retrieved by the internal JavaScript code, but just before the form submission.

NOTE: The actual password is surely used for the next step by the form. The value is transferred to a hidden field first. See the code example.

That way, when the browser's password manager saves the password, it is not really the password the user had given there. So the user thinks the password has been saved, when in fact some random stuff is what got saved. Over time, the user would know that he/she can't trust the password manager to do the right job for that site.

Now this can lead to a bad user experience; I know because the user may feel that the browser has indeed saved the password. But with adequate documentation, the user can be consoled. I feel this is the way one can fully be sure that the actual password entered by the user cannot be picked up by the browser and saved.

<form id='frm' action="https://google.com">
    Password: <input type="password" id="pwd" />
    <input type='hidden' id='hiddenpwd' />
    <button onclick='subm()'>Submit this</button>
</form>

<script>
    function subm() {
        var actualpwd = $('#pwd').val();
        $('#hiddenpwd').val(actualpwd);
        // ...Do whatever Ajax, etc. with this actual pwd
        // ...Or assign the value to another hidden field
        $('#pwd').val('globbedygook');
        $('#frm').submit();
    }
</script>

jQuery click events firing multiple times

.unbind() is deprecated and you should use the .off() method instead. Simply call .off() right before you call .on().

This will remove all event handlers:

$(element).off().on('click', function() {
    // function body
});

To only remove registered 'click' event handlers:

$(element).off('click').on('click', function() {
    // function body
});

Explaining Python's '__enter__' and '__exit__'

If you know what context managers are then you need nothing more to understand __enter__ and __exit__ magic methods. Lets see a very simple example.

In this example I am opening myfile.txt with help of open function. The try/finally block ensures that even if an unexpected exception occurs myfile.txt will be closed.

fp=open(r"C:\Users\SharpEl\Desktop\myfile.txt")
try:
    for line in fp:
        print(line)
finally:
    fp.close()

Now I am opening same file with with statement:

with open(r"C:\Users\SharpEl\Desktop\myfile.txt") as fp:
    for line in fp:
        print(line) 

If you look at the code, I didn't close the file & there is no try/finally block. Because with statement automatically closes myfile.txt . You can even check it by calling print(fp.closed) attribute -- which returns True.

This is because the file objects (fp in my example) returned by open function has two built-in methods __enter__ and __exit__. It is also known as context manager. __enter__ method is called at the start of with block and __exit__ method is called at the end. Note: with statement only works with objects that support the context mamangement protocol i.e. they have __enter__ and __exit__ methods. A class which implement both methods is known as context manager class.

Now lets define our own context manager class.

 class Log:
    def __init__(self,filename):
        self.filename=filename
        self.fp=None    
    def logging(self,text):
        self.fp.write(text+'\n')
    def __enter__(self):
        print("__enter__")
        self.fp=open(self.filename,"a+")
        return self    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("__exit__")
        self.fp.close()

with Log(r"C:\Users\SharpEl\Desktop\myfile.txt") as logfile:
    print("Main")
    logfile.logging("Test1")
    logfile.logging("Test2")

I hope now you have basic understanding of both __enter__ and __exit__ magic methods.

How to set the font style to bold, italic and underlined in an Android TextView?

For bold and italic whatever you are doing is correct for underscore use following code

HelloAndroid.java

 package com.example.helloandroid;

 import android.app.Activity;
 import android.os.Bundle;
 import android.text.SpannableString;
 import android.text.style.UnderlineSpan;
import android.widget.TextView;

public class HelloAndroid extends Activity {
TextView textview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    textview = (TextView)findViewById(R.id.textview);
    SpannableString content = new SpannableString(getText(R.string.hello));
    content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
    textview.setText(content);
}
}

main.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/hello"
android:textStyle="bold|italic"/>

string.xml

<?xml version="1.0" encoding="utf-8"?>
 <resources>
  <string name="hello">Hello World, HelloAndroid!</string>
  <string name="app_name">Hello, Android</string>
</resources>

Wait until all jQuery Ajax requests are done?

I highly recommend using $.when() if you're starting from scratch.

Even though this question has over million answers, I still didn't find anything useful for my case. Let's say you have to deal with an existing codebase, already making some ajax calls and don't want to introduce the complexity of promises and/or redo the whole thing.

We can easily take advantage of jQuery .data, .on and .trigger functions which have been a part of jQuery since forever.

Codepen

The good stuff about my solution is:

  • it's obvious what the callback exactly depends on

  • the function triggerNowOrOnLoaded doesn't care if the data has been already loaded or we're still waiting for it

  • it's super easy to plug it into an existing code

_x000D_
_x000D_
$(function() {_x000D_
_x000D_
  // wait for posts to be loaded_x000D_
  triggerNowOrOnLoaded("posts", function() {_x000D_
    var $body = $("body");_x000D_
    var posts = $body.data("posts");_x000D_
_x000D_
    $body.append("<div>Posts: " + posts.length + "</div>");_x000D_
  });_x000D_
_x000D_
_x000D_
  // some ajax requests_x000D_
  $.getJSON("https://jsonplaceholder.typicode.com/posts", function(data) {_x000D_
    $("body").data("posts", data).trigger("posts");_x000D_
  });_x000D_
_x000D_
  // doesn't matter if the `triggerNowOrOnLoaded` is called after or before the actual requests _x000D_
  $.getJSON("https://jsonplaceholder.typicode.com/users", function(data) {_x000D_
    $("body").data("users", data).trigger("users");_x000D_
  });_x000D_
_x000D_
_x000D_
  // wait for both types_x000D_
  triggerNowOrOnLoaded(["posts", "users"], function() {_x000D_
    var $body = $("body");_x000D_
    var posts = $body.data("posts");_x000D_
    var users = $body.data("users");_x000D_
_x000D_
    $body.append("<div>Posts: " + posts.length + " and Users: " + users.length + "</div>");_x000D_
  });_x000D_
_x000D_
  // works even if everything has already loaded!_x000D_
  setTimeout(function() {_x000D_
_x000D_
    // triggers immediately since users have been already loaded_x000D_
    triggerNowOrOnLoaded("users", function() {_x000D_
      var $body = $("body");_x000D_
      var users = $body.data("users");_x000D_
_x000D_
      $body.append("<div>Delayed Users: " + users.length + "</div>");_x000D_
    });_x000D_
_x000D_
  }, 2000); // 2 seconds_x000D_
_x000D_
});_x000D_
_x000D_
// helper function_x000D_
function triggerNowOrOnLoaded(types, callback) {_x000D_
  types = $.isArray(types) ? types : [types];_x000D_
_x000D_
  var $body = $("body");_x000D_
_x000D_
  var waitForTypes = [];_x000D_
  $.each(types, function(i, type) {_x000D_
_x000D_
    if (typeof $body.data(type) === 'undefined') {_x000D_
      waitForTypes.push(type);_x000D_
    }_x000D_
  });_x000D_
_x000D_
  var isDataReady = waitForTypes.length === 0;_x000D_
  if (isDataReady) {_x000D_
    callback();_x000D_
    return;_x000D_
  }_x000D_
_x000D_
  // wait for the last type and run this function again for the rest of the types_x000D_
  var waitFor = waitForTypes.pop();_x000D_
  $body.on(waitFor, function() {_x000D_
    // remove event handler - we only want the stuff triggered once_x000D_
    $body.off(waitFor);_x000D_
_x000D_
    triggerNowOrOnLoaded(waitForTypes, callback);_x000D_
  });_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>Hi!</body>
_x000D_
_x000D_
_x000D_

How to parse JSON with VBA without external libraries?

There are two issues here. The first is to access fields in the array returned by your JSON parse, the second is to rename collections/fields (like sentences) away from VBA reserved names.

Let's address the second concern first. You were on the right track. First, replace all instances of sentences with jsentences If text within your JSON also contains the word sentences, then figure out a way to make the replacement unique, such as using "sentences":[ as the search string. You can use the VBA Replace method to do this.

Once that's done, so VBA will stop renaming sentences to Sentences, it's just a matter of accessing the array like so:

'first, declare the variables you need:
Dim jsent as Variant

'Get arr all setup, then
For Each jsent in arr.jsentences
  MsgBox(jsent.orig)
Next

Convert string to Python class object?

This could work:

import sys

def str_to_class(classname):
    return getattr(sys.modules[__name__], classname)

Viewing contents of a .jar file

You can open them with most decompression utilities these days, then just get something like DJ Java Decompiler if you want to view the source.

How do I clear all variables in the middle of a Python script?

In the idle IDE there is Shell/Restart Shell. Cntrl-F6 will do it.

Print a div using javascript in angularJS single page application

Two conditional functions are needed: one for Google Chrome, and a second for the remaining browsers.

$scope.printDiv = function (divName) {

    var printContents = document.getElementById(divName).innerHTML; 

    if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
        var popupWin = window.open('', '_blank', 'width=600,height=600,scrollbars=no,menubar=no,toolbar=no,location=no,status=no,titlebar=no');
        popupWin.window.focus();
        popupWin.document.write('<!DOCTYPE html><html><head>' +
            '<link rel="stylesheet" type="text/css" href="style.css" />' +
            '</head><body onload="window.print()"><div class="reward-body">' + printContents + '</div></body></html>');
        popupWin.onbeforeunload = function (event) {
            popupWin.close();
            return '.\n';
        };
        popupWin.onabort = function (event) {
            popupWin.document.close();
            popupWin.close();
        }
    } else {
        var popupWin = window.open('', '_blank', 'width=800,height=600');
        popupWin.document.open();
        popupWin.document.write('<html><head><link rel="stylesheet" type="text/css" href="style.css" /></head><body onload="window.print()">' + printContents + '</body></html>');
        popupWin.document.close();
    }
    popupWin.document.close();

    return true;
}

PHP Fatal error: Call to undefined function mssql_connect()

I have just tried to install that extension on my dev server.

First, make sure that the extension is correctly enabled. Your phpinfo() output doesn't seem complete.

If it is indeed installed properly, your phpinfo() should have a section that looks like this: enter image description here

If you do not get that section in your phpinfo(). Make sure that you are using the right version. There are both non-thread-safe and thread-safe versions of the extension.

Finally, check your extension_dir setting. By default it's this: extension_dir = "ext", for most of the time it works fine, but if it doesn't try: extension_dir = "C:\PHP\ext".

===========================================================================

EDIT given new info:

You are using the wrong function. mssql_connect() is part of the Mssql extension. You are using microsoft's extension, so use sqlsrv_connect(), for the API for the microsoft driver, look at SQLSRV_Help.chm which should be extracted to your ext directory when you extracted the extension.

CSS3 selector :first-of-type with class name?

This is an old thread, but I'm responding because it still appears high in the list of search results. Now that the future has arrived, you can use the :nth-child pseudo-selector.

p:nth-child(1) { color: blue; }
p.myclass1:nth-child(1) { color: red; }
p.myclass2:nth-child(1) { color: green; }

The :nth-child pseudo-selector is powerful - the parentheses accept formulas as well as numbers.

More here: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

How to create helper file full of functions in react native?

I am sure this can help. Create fileA anywhere in the directory and export all the functions.

export const func1=()=>{
    // do stuff
}
export const func2=()=>{
    // do stuff 
}
export const func3=()=>{
    // do stuff 
}
export const func4=()=>{
    // do stuff 
}
export const func5=()=>{
    // do stuff 
}

Here, in your React component class, you can simply write one import statement.

import React from 'react';
import {func1,func2,func3} from 'path_to_fileA';

class HtmlComponents extends React.Component {
    constructor(props){
        super(props);
        this.rippleClickFunction=this.rippleClickFunction.bind(this);
    }
    rippleClickFunction(){
        //do stuff. 
        // foo==bar
        func1(data);
        func2(data)
    }
   render() {
      return (
         <article>
             <h1>React Components</h1>
             <RippleButton onClick={this.rippleClickFunction}/>
         </article>
      );
   }
}

export default HtmlComponents;

Iterating over Numpy matrix rows to apply a function each?

Here's my take if you want to try using multiprocesses to process each row of numpy array,

from multiprocessing import Pool
import numpy as np

def my_function(x):
    pass     # do something and return something

if __name__ == '__main__':    
    X = np.arange(6).reshape((3,2))
    pool = Pool(processes = 4)
    results = pool.map(my_function, map(lambda x: x, X))
    pool.close()
    pool.join()

pool.map take in a function and an iterable.
I used 'map' function to create an iterator over each rows of the array.
Maybe there's a better to create the iterable though.

Set a default parameter value for a JavaScript function

def read_file(file, delete_after = false)
  # code
end

Following code may work in this situation including ECMAScript 6 (ES6) as well as earlier versions.

_x000D_
_x000D_
function read_file(file, delete_after) {_x000D_
    if(delete_after == undefined)_x000D_
        delete_after = false;//default value_x000D_
_x000D_
    console.log('delete_after =',delete_after);_x000D_
}_x000D_
read_file('text1.txt',true);_x000D_
read_file('text2.txt');
_x000D_
_x000D_
_x000D_

as default value in languages works when the function's parameter value is skipped when calling, in JavaScript it is assigned to undefined. This approach doesn't look attractive programmatically but have backward compatibility.

Swift Beta performance: sorting arrays

From The Swift Programming Language:

The Sort Function Swift’s standard library provides a function called sort, which sorts an array of values of a known type, based on the output of a sorting closure that you provide. Once it completes the sorting process, the sort function returns a new array of the same type and size as the old one, with its elements in the correct sorted order.

The sort function has two declarations.

The default declaration which allows you to specify a comparison closure:

func sort<T>(array: T[], pred: (T, T) -> Bool) -> T[]

And a second declaration that only take a single parameter (the array) and is "hardcoded to use the less-than comparator."

func sort<T : Comparable>(array: T[]) -> T[]

Example:
sort( _arrayToSort_ ) { $0 > $1 }

I tested a modified version of your code in a playground with the closure added on so I could monitor the function a little more closely, and I found that with n set to 1000, the closure was being called about 11,000 times.

let n = 1000
let x = Int[](count: n, repeatedValue: 0)
for i in 0..n {
    x[i] = random()
}
let y = sort(x) { $0 > $1 }

It is not an efficient function, an I would recommend using a better sorting function implementation.

EDIT:

I took a look at the Quicksort wikipedia page and wrote a Swift implementation for it. Here is the full program I used (in a playground)

import Foundation

func quickSort(inout array: Int[], begin: Int, end: Int) {
    if (begin < end) {
        let p = partition(&array, begin, end)
        quickSort(&array, begin, p - 1)
        quickSort(&array, p + 1, end)
    }
}

func partition(inout array: Int[], left: Int, right: Int) -> Int {
    let numElements = right - left + 1
    let pivotIndex = left + numElements / 2
    let pivotValue = array[pivotIndex]
    swap(&array[pivotIndex], &array[right])
    var storeIndex = left
    for i in left..right {
        let a = 1 // <- Used to see how many comparisons are made
        if array[i] <= pivotValue {
            swap(&array[i], &array[storeIndex])
            storeIndex++
        }
    }
    swap(&array[storeIndex], &array[right]) // Move pivot to its final place
    return storeIndex
}

let n = 1000
var x = Int[](count: n, repeatedValue: 0)
for i in 0..n {
    x[i] = Int(arc4random())
}

quickSort(&x, 0, x.count - 1) // <- Does the sorting

for i in 0..n {
    x[i] // <- Used by the playground to display the results
}

Using this with n=1000, I found that

  1. quickSort() got called about 650 times,
  2. about 6000 swaps were made,
  3. and there are about 10,000 comparisons

It seems that the built-in sort method is (or is close to) quick sort, and is really slow...

Javamail Could not convert socket to TLS GMail

This can also be if the application does not support the TLS version the SMTP host is using.

For example, trying to configure an SMTP server that uses TLSv1.2 without fallback, when your application(or java program using an older javax.mail JAR) supports only upto TLSv1.1.

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

Since your might use MAMP, either change your Port to the default 3306 or use 127.0.0.1 in the database.php

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',// leave it for port 3306
    'username' => 'yourUserhere',
    'password' => 'yourPassword',
    'database' => 'yourDatabase',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => FALSE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Or with the default settings:

$db['default'] = array(
        'dsn'   => '',
        'hostname' => '127.0.0.1:8889',// leave it for port 8889
        'username' => 'yourUserhere',
        'password' => 'yourPassword',
        'database' => 'yourDatabase',
        'dbdriver' => 'mysqli',
        'dbprefix' => '',
        'pconnect' => FALSE,
        'db_debug' => (ENVIRONMENT !== 'production'),
        'cache_on' => FALSE,
        'cachedir' => '',
        'char_set' => 'utf8',
        'dbcollat' => 'utf8_general_ci',
        'swap_pre' => '',
        'encrypt' => FALSE,
        'compress' => FALSE,
        'stricton' => FALSE,
        'failover' => array(),
        'save_queries' => TRUE
    );

Altering user-defined table types in SQL Server

Just had to do this alter user defined table type in one of my projects. Here are the steps I employed:

  1. Find all the SP using the user defined table type.
  2. Save a create script for all the SP(s) found.
  3. Drop the SP(s).
  4. Save a create script for the user defined table you wish to alter. 4.5 Add the additional column or changes you need to the user defined table type.
  5. Drop the user defined table type.
  6. Run the create script for the user defined table type.
  7. Run the create script for the SP(s).
  8. Then start modifying the SP(s) accordingly.

Could not find main class HelloWorld

Just remove your "classpath" from you environment variable. Then try running:

java HelloWorld 

This should work fine.

How to open, read, and write from serial port in C?

For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly and Serial Programming Guide for POSIX Operating Systems, the following is offered.
This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.

This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
The program then enters an infinite loop to receive and display data from the serial terminal.
By default the received data is displayed as hexadecimal byte values.

To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.

 cc -DDISPLAY_STRING demo.c

If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.


#define TERMINAL    "/dev/ttyUSB0"

#include <errno.h>
#include <fcntl.h> 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

int set_interface_attribs(int fd, int speed)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error from tcgetattr: %s\n", strerror(errno));
        return -1;
    }

    cfsetospeed(&tty, (speed_t)speed);
    cfsetispeed(&tty, (speed_t)speed);

    tty.c_cflag |= (CLOCAL | CREAD);    /* ignore modem controls */
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;         /* 8-bit characters */
    tty.c_cflag &= ~PARENB;     /* no parity bit */
    tty.c_cflag &= ~CSTOPB;     /* only need 1 stop bit */
    tty.c_cflag &= ~CRTSCTS;    /* no hardware flowcontrol */

    /* setup for non-canonical mode */
    tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    tty.c_oflag &= ~OPOST;

    /* fetch bytes as they become available */
    tty.c_cc[VMIN] = 1;
    tty.c_cc[VTIME] = 1;

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        printf("Error from tcsetattr: %s\n", strerror(errno));
        return -1;
    }
    return 0;
}

void set_mincount(int fd, int mcount)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error tcgetattr: %s\n", strerror(errno));
        return;
    }

    tty.c_cc[VMIN] = mcount ? 1 : 0;
    tty.c_cc[VTIME] = 5;        /* half second timer */

    if (tcsetattr(fd, TCSANOW, &tty) < 0)
        printf("Error tcsetattr: %s\n", strerror(errno));
}


int main()
{
    char *portname = TERMINAL;
    int fd;
    int wlen;
    char *xstr = "Hello!\n";
    int xlen = strlen(xstr);

    fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
    if (fd < 0) {
        printf("Error opening %s: %s\n", portname, strerror(errno));
        return -1;
    }
    /*baudrate 115200, 8 bits, no parity, 1 stop bit */
    set_interface_attribs(fd, B115200);
    //set_mincount(fd, 0);                /* set to pure timed read */

    /* simple output */
    wlen = write(fd, xstr, xlen);
    if (wlen != xlen) {
        printf("Error from write: %d, %d\n", wlen, errno);
    }
    tcdrain(fd);    /* delay for output */


    /* simple noncanonical input */
    do {
        unsigned char buf[80];
        int rdlen;

        rdlen = read(fd, buf, sizeof(buf) - 1);
        if (rdlen > 0) {
#ifdef DISPLAY_STRING
            buf[rdlen] = 0;
            printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
            unsigned char   *p;
            printf("Read %d:", rdlen);
            for (p = buf; rdlen-- > 0; p++)
                printf(" 0x%x", *p);
            printf("\n");
#endif
        } else if (rdlen < 0) {
            printf("Error from read: %d: %s\n", rdlen, strerror(errno));
        } else {  /* rdlen == 0 */
            printf("Timeout from read\n");
        }               
        /* repeat read to get full message */
    } while (1);
}

For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.


How to position a div in the middle of the screen when the page is bigger than the screen

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
.loader {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin-top: -50px;_x000D_
  margin-left: -50px;_x000D_
  border: 10px solid #dcdcdc;_x000D_
  border-radius: 50%;_x000D_
  border-top: 10px solid #3498db;_x000D_
  width: 30px;_x000D_
  height: 30px;_x000D_
  -webkit-animation: spin 2s linear infinite;_x000D_
  animation: spin 1s linear infinite;  _x000D_
}_x000D_
_x000D_
@-webkit-keyframes spin {_x000D_
  0% { -webkit-transform: rotate(0deg); }_x000D_
  100% { -webkit-transform: rotate(360deg); }_x000D_
}_x000D_
_x000D_
@keyframes spin {_x000D_
  0% { transform: rotate(0deg); }_x000D_
  100% { transform: rotate(360deg); }_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
_x000D_
<div class="loader" style="display:block"></div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

#pragma pack effect

Data elements (e.g. members of classes and structs) are typically aligned on WORD or DWORD boundaries for current generation processors in order to improve access times. Retrieving a DWORD at an address which isn't divisible by 4 requires at least one extra CPU cycle on a 32 bit processor. So, if you have e.g. three char members char a, b, c;, they actually tend to take 6 or 12 bytes of storage.

#pragma allows you to override this to achieve more efficient space usage, at the expense of access speed, or for consistency of stored data between different compiler targets. I had a lot of fun with this transitioning from 16 bit to 32 bit code; I expect porting to 64 bit code will cause the same kinds of headaches for some code.

Is it possible to ping a server from Javascript?

You could try using PHP in your web page...something like this:

<html><body>
<form method="post" name="pingform" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<h1>Host to ping:</h1>
<input type="text" name="tgt_host" value='<?php echo $_POST['tgt_host']; ?>'><br>
<input type="submit" name="submit" value="Submit" >
</form></body>
</html>
<?php

$tgt_host = $_POST['tgt_host'];
$output = shell_exec('ping -c 10 '. $tgt_host.');

echo "<html><body style=\"background-color:#0080c0\">
<script type=\"text/javascript\" language=\"javascript\">alert(\"Ping Results: " . $output . ".\");</script>
</body></html>";

?>

This is not tested so it may have typos etc...but I am confident it would work. Could be improved too...

Regular vs Context Free Grammars

I think what you want to think about are the various pumping lemmata. A regular language can be recognized by a finite automaton. A context-free language requires a stack, and a context sensitive language requires two stacks (which is equivalent to saying it requires a full Turing machine.)

So, if we think about the pumping lemma for regular languages, what it says, essentially, is that any regular language can be broken down into three pieces, x, y, and z, where all instances of the language are in xy*z (where * is Kleene repetition, ie, 0 or more copies of y.) You basically have one "nonterminal" that can be expanded.

Now, what about context-free languages? There's an analogous pumping lemma for context-free languages that breaks the strings in the language into five parts, uvxyz, and where all instances of the language are in uvixyiz, for i ≥ 0. Now, you have two "nonterminals" that can be replicated, or pumped, as long as you have the same number.

How to implement HorizontalScrollView like Gallery?

You may use HorizontalScrollView to implement Horizontal scrolling.

Code

<HorizontalScrollView
android:id="@+id/hsv"
android:layout_width="fill_parent"
android:layout_height="100dp"
 android:layout_weight="0"
android:fillViewport="true"
android:measureAllChildren="false"
android:scrollbars="none" >
<LinearLayout
    android:id="@+id/innerLay"
    android:layout_width="wrap_content"
    android:layout_height="100dp"
    android:gravity="center_vertical"
    android:orientation="horizontal" >
    </LinearLayout>
    </HorizontalScrollView>

featured.xml:

<?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="160dp"
   android:layout_margin="4dp"
android:layout_height="match_parent"
android:orientation="vertical" >

      <RelativeLayout 
android:layout_width="fill_parent"
android:layout_height="fill_parent" 
>

<ProgressBar                
    android:layout_width="15dip"       
    android:layout_height="15dip"
    android:id="@+id/progress" 
    android:layout_centerInParent="true"
    />

<ImageView
    android:id="@+id/image"       
    android:layout_width="fill_parent"       
    android:layout_height="fill_parent"
    android:background="#20000000"
    />

<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="30dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:gravity="center"
    android:textColor="#000000"
    android:background="#ffffff"
    android:text="Image Text" />

      </RelativeLayout>
     </LinearLayout>

Java Code:

 LayoutInflater inflater;

    inflater=getLayoutInflater();
    LinearLayout inLay=(LinearLayout) findViewById(R.id.innerLay);

    for(int x=0;x<10;x++)
    {
        inLay.addView(getView(x));
    }




 View getView(final int x)
{
   View rootView = inflater.inflate( R.layout.featured_item,null);

   ImageView image = (ImageView) rootView.findViewById(R.id.image);

   //Thease Two Line is sufficient my dear to implement lazyLoading
   AQuery aq = new AQuery(rootView);
   String url="http://farm6.static.flickr.com/5035/5802797131_a729dac808_s.jpg";
   aq.id(image).progress(R.id.progress).image(url, true, true, 0, R.drawable.placeholder1);
   image.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
     Toast.makeText(PhotoActivity.this, "Click Here Postion "+x,     

         Toast.LENGTH_LONG).show();
        }
    });
   return rootView;
       }

Note: to implement lazy loading, please use this link for AQUERY

https://code.google.com/p/android-query/wiki/ImageLoading

Can't create handler inside thread that has not called Looper.prepare()

Try this, when you see runtimeException due to Looper not prepared before handler.

Handler handler = new Handler(Looper.getMainLooper()); 

handler.postDelayed(new Runnable() {
  @Override
  public void run() {
  // Run your task here
  }
}, 1000 );

How can I calculate the time between 2 Dates in typescript

It doesn't work because Date - Date relies on exactly the kind of type coercion TypeScript is designed to prevent.

There is a workaround this using the + prefix:

var t = Date.now() - +(new Date("2013-02-20T12:01:04.753Z");

Or, if you prefer not to use Date.now():

var t = +(new Date()) - +(new Date("2013-02-20T12:01:04.753Z"));

See discussion here.

Or see Siddharth Singh's answer, below, for a more elegant solution using valueOf()

Have a variable in images path in Sass?

Have you tried the Interpolation syntax?

background: url(#{$get-path-to-assets}/site/background.jpg) repeat-x fixed 0 0;

Array to Collection: Optimized code

You can try something like this:

List<String> list = new ArrayList<String>(Arrays.asList(array));

public ArrayList(Collection c)

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator. The ArrayList instance has an initial capacity of 110% the size of the specified collection.

Taken from here

How do I use a 32-bit ODBC driver on 64-bit Server 2008 when the installer doesn't create a standard DSN?

It turns out that you can create 32-bit ODBC connections using C:\Windows\SysWOW64\odbcad32.exe. My solution was to create the 32-bit ODBC connection as a System DSN. This still didn't allow me to connect to it since .NET couldn't look it up. After significant and fruitless searching to find how to get the OdbcConnection class to look for the DSN in the right place, I stumbled upon a web site that suggested modifying the registry to solve a different problem.

I ended up creating the ODBC connection directly under HKLM\Software\ODBC. I looked in the SysWOW6432 key to find the parameters that were set up using the 32-bit version of the ODBC administration tool and recreated this in the standard location. I didn't add an entry for the driver, however, as that was not installed by the standard installer for the app either.

After creating the entry (by hand), I fired up my windows service and everything was happy.

vba listbox multicolumn add

Simplified example (with counter):

With Me.lstbox
    .ColumnCount = 2
    .ColumnWidths = "60;60"
    .AddItem
    .List(i, 0) = Company_ID
    .List(i, 1) = Company_name 
    i = i + 1

end with

Make sure to start the counter with 0, not 1 to fill up a listbox.

How to change the style of alert box?

Option1. you can use AlertifyJS , this is good for alert

enter image description here

enter image description here

Option2. you start up or just join a project based on webapplications, the design of interface is maybe good. Otherwise this should be changed. In order to Web 2.0 applications you will work with dynamic contents, many effects and other stuff. All these things are fine, but no one thought about to style up the JavaScript alert and confirm boxes. Here is the they way

create simple js file name jsConfirmStyle.js. Here is simple js code

ie5=(document.getElementById&&document.all&&document.styleSheets)?1:0;
nn6=(document.getElementById&&!document.all)?1:0;

xConfirmStart=800;
yConfirmStart=100;

if(ie5||nn6) {
if(ie5) cs=2,th=30;
else cs=0,th=20;
document.write(
    "<div id='jsconfirm'>"+
        "<table>"+
            "<tr><td id='jsconfirmtitle'></td></tr>"+
            "<tr><td id='jsconfirmcontent'></td></tr>"+
            "<tr><td id='jsconfirmbuttons'>"+
                "<input id='jsconfirmleft' type='button' value='' onclick='leftJsConfirm()' onfocus='if(this.blur)this.blur()'>"+
                "&nbsp;&nbsp;"+
                "<input id='jsconfirmright' type='button' value='' onclick='rightJsConfirm()' onfocus='if(this.blur)this.blur()'>"+
            "</td></tr>"+
        "</table>"+
    "</div>"
);
 }

           document.write("<div id='jsconfirmfade'></div>");


function leftJsConfirm() {
document.getElementById('jsconfirm').style.top=-1000;
document.location.href=leftJsConfirmUri;
}
function rightJsConfirm() {
document.getElementById('jsconfirm').style.top=-1000;
document.location.href=rightJsConfirmUri;
}
function confirmAlternative() {
if(confirm("Scipt requieres a better browser!"))       document.location.href="http://www.mozilla.org";
 }

leftJsConfirmUri = '';
rightJsConfirmUri = '';

/**
 * Show the message/confirm box
*/
function showConfirm(confirmtitle,confirmcontent,confirmlefttext,confirmlefturi,confirmrighttext,confirmrighturi)  {
document.getElementById("jsconfirmtitle").innerHTML=confirmtitle;
document.getElementById("jsconfirmcontent").innerHTML=confirmcontent;
document.getElementById("jsconfirmleft").value=confirmlefttext;
document.getElementById("jsconfirmright").value=confirmrighttext;
leftJsConfirmUri=confirmlefturi;
rightJsConfirmUri=confirmrighturi;
xConfirm=xConfirmStart, yConfirm=yConfirmStart;
if(ie5) {
    document.getElementById("jsconfirm").style.left='25%';
    document.getElementById("jsconfirm").style.top='35%';
}
else if(nn6) {
    document.getElementById("jsconfirm").style.top='25%';
    document.getElementById("jsconfirm").style.left='35%';
}
else confirmAlternative();
}

Create simple html file

<html>
<head>
<title>jsConfirmSyle</title>
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<script type="text/javascript" src="jsConfirmStyle.js"></script>
<script type="text/javascript">

 function confirmation() {
 var answer = confirm("Wanna visit google?")
 if (answer){
    window.location = "http://www.google.com/";
}
}
  </script>
   <style type="text/css">
    body {
  background-color: white;
   font-family: sans-serif;
  }
#jsconfirm {
border-color: #c0c0c0;
border-width: 2px 4px 4px 2px;
left: 0;
margin: 0;
padding: 0;
position: absolute;
top: -1000px;
z-index: 100;
}

#jsconfirm table {
background-color: #fff;
border: 2px groove #c0c0c0;
height: 150px;
width: 300px;
}

#jsconfirmtitle {
background-color: #B0B0B0;
font-weight: bold;
height: 20px;
text-align: center;
}

#jsconfirmbuttons {
height: 50px;
text-align: center;
}

#jsconfirmbuttons input {
background-color: #E9E9CF;
color: #000000;
font-weight: bold;
width: 125px;
height: 33px;
padding-left: 20px;
}

#jsconfirmleft{
background-image: url(left.png);
}

#jsconfirmright{
background-image: url(right.png);
}
</style>

 <p>
<a href="#"  onclick="javascript:showConfirm('Please confirm','Are you really sure to visit google?','Yes','http://www.google.com','No','#')">JsConfirmStyled</a> </p>
<p><a href="#" onclick="confirmation()">standard</a></p>


</body>
 </html>

Laravel csrf token mismatch for ajax POST Request

I think is better put the token in the form, and get this token by id

<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">

And the JQUery :

var data = {
        "_token": $('#token').val()
    };

this way, your JS don't need to be in your blade files.

Any way to write a Windows .bat file to kill processes?

As TASKKILL might be unavailable on some Home/basic editions of windows here some alternatives:

TSKILL processName

or

TSKILL PID

Have on mind that processName should not have the .exe suffix and is limited to 18 characters.

Another option is WMIC :

wmic Path win32_process Where "Caption Like 'MyProcess%.exe'" Call Terminate

wmic offer even more flexibility than taskkill with its SQL-like matchers .With wmic Path win32_process get you can see the available fileds you can filter (and % can be used as a wildcard).

java: Class.isInstance vs Class.isAssignableFrom

Both answers are in the ballpark but neither is a complete answer.

MyClass.class.isInstance(obj) is for checking an instance. It returns true when the parameter obj is non-null and can be cast to MyClass without raising a ClassCastException. In other words, obj is an instance of MyClass or its subclasses.

MyClass.class.isAssignableFrom(Other.class) will return true if MyClass is the same as, or a superclass or superinterface of, Other. Other can be a class or an interface. It answers true if Other can be converted to a MyClass.

A little code to demonstrate:

public class NewMain
{
    public static void main(String[] args)
    {
        NewMain nm = new NewMain();
        nm.doit();
    }

    class A { }

    class B extends A { }

    public void doit()
    {
        A myA = new A();
        B myB = new B();
        A[] aArr = new A[0];
        B[] bArr = new B[0];

        System.out.println("b instanceof a: " + (myB instanceof A)); // true
        System.out.println("b isInstance a: " + A.class.isInstance(myB)); //true
        System.out.println("a isInstance b: " + B.class.isInstance(myA)); //false
        System.out.println("b isAssignableFrom a: " + A.class.isAssignableFrom(B.class)); //true
        System.out.println("a isAssignableFrom b: " + B.class.isAssignableFrom(A.class)); //false
        System.out.println("bArr isInstance A: " + A.class.isInstance(bArr)); //false
        System.out.println("bArr isInstance aArr: " + aArr.getClass().isInstance(bArr)); //true
        System.out.println("bArr isAssignableFrom aArr: " + aArr.getClass().isAssignableFrom(bArr.getClass())); //true
    }
}

How to pass a file path which is in assets folder to File(String path)?

AFAIK, you can't create a File from an assets file because these are stored in the apk, that means there is no path to an assets folder.

But, you can try to create that File using a buffer and the AssetManager (it provides access to an application's raw asset files).

Try to do something like:

AssetManager am = getAssets();
InputStream inputStream = am.open("myfoldername/myfilename");
File file = createFileFromInputStream(inputStream);

private File createFileFromInputStream(InputStream inputStream) {

   try{
      File f = new File(my_file_name);
      OutputStream outputStream = new FileOutputStream(f);
      byte buffer[] = new byte[1024];
      int length = 0;

      while((length=inputStream.read(buffer)) > 0) {
        outputStream.write(buffer,0,length);
      }

      outputStream.close();
      inputStream.close();

      return f;
   }catch (IOException e) {
         //Logging exception
   }

   return null;
}

Let me know about your progress.

Convert a Unicode string to a string in Python (containing extra symbols)

If you have a Unicode string, and you want to write this to a file, or other serialised form, you must first encode it into a particular representation that can be stored. There are several common Unicode encodings, such as UTF-16 (uses two bytes for most Unicode characters) or UTF-8 (1-4 bytes / codepoint depending on the character), etc. To convert that string into a particular encoding, you can use:

>>> s= u'£10'
>>> s.encode('utf8')
'\xc2\x9c10'
>>> s.encode('utf16')
'\xff\xfe\x9c\x001\x000\x00'

This raw string of bytes can be written to a file. However, note that when reading it back, you must know what encoding it is in and decode it using that same encoding.

When writing to files, you can get rid of this manual encode/decode process by using the codecs module. So, to open a file that encodes all Unicode strings into UTF-8, use:

import codecs
f = codecs.open('path/to/file.txt','w','utf8')
f.write(my_unicode_string)  # Stored on disk as UTF-8

Do note that anything else that is using these files must understand what encoding the file is in if they want to read them. If you are the only one doing the reading/writing this isn't a problem, otherwise make sure that you write in a form understandable by whatever else uses the files.

In Python 3, this form of file access is the default, and the built-in open function will take an encoding parameter and always translate to/from Unicode strings (the default string object in Python 3) for files opened in text mode.

Difference between String replace() and replaceAll()

  1. Both replace() and replaceAll() accepts two arguments and replaces all occurrences of the first substring(first argument) in a string with the second substring (second argument).
  2. replace() accepts a pair of char or charsequence and replaceAll() accepts a pair of regex.
  3. It is not true that replace() works faster than replaceAll() since both uses the same code in its implementation

    Pattern.compile(regex).matcher(this).replaceAll(replacement);

Now the question is when to use replace and when to use replaceAll(). When you want to replace a substring with another substring regardless of its place of occurrence in the string use replace(). But if you have some particular preference or condition like replace only those substrings at the beginning or end of a string use replaceAll(). Here are some examples to prove my point:

String str = new String("==qwerty==").replaceAll("^==", "?"); \\str: "?qwerty=="
String str = new String("==qwerty==").replaceAll("==$", "?"); \\str: "==qwerty?"
String str = new String("===qwerty==").replaceAll("(=)+", "?"); \\str: "?qwerty?"

NameError: global name 'unicode' is not defined - in Python 3

One can replace unicode with u''.__class__ to handle the missing unicode class in Python 3. For both Python 2 and 3, you can use the construct

isinstance(unicode_or_str, u''.__class__)

or

type(unicode_or_str) == type(u'')

Depending on your further processing, consider the different outcome:

Python 3

>>> isinstance('text', u''.__class__)
True
>>> isinstance(u'text', u''.__class__)
True

Python 2

>>> isinstance(u'text', u''.__class__)
True
>>> isinstance('text', u''.__class__)
False

How to format html table with inline styles to look like a rendered Excel table?

Add cellpadding and cellspacing to solve it. Edit: Also removed double pixel border.

<style>
td
{border-left:1px solid black;
border-top:1px solid black;}
table
{border-right:1px solid black;
border-bottom:1px solid black;}
</style>
<html>
    <body>
        <table cellpadding="0" cellspacing="0">
            <tr>
                <td width="350" >
                    Foo
                </td>
                <td width="80" >
                    Foo1
                </td>
                <td width="65" >
                    Foo2
                </td>
            </tr>
            <tr>
                <td>
                    Bar1
                </td>
                <td>
                    Bar2
                </td>
                <td>
                    Bar3
                </td>
            </tr>
            <tr >
                <td>
                    Bar1
                </td>
                <td>
                    Bar2
                </td>
                <td>
                    Bar3
                </td>
            </tr>
        </table>
    </body>
</html>

Why functional languages?

I don't think that there's any question about the functional approach to programming "catching on", because it's been in use (as a style of programming) for about 40 years. Whenever an OO programmer writes clean code that favors immutable objects, that code is borrowing functional concepts.

However, languages that enforce a functional style are getting lots of virtual ink these days, and whether those languages will become dominant in the future is an open question. My own suspicion is that hybrid, multi-paradigm languages such as Scala or OCaml will likely dominate over "purist" functional languages in the same way that pure OO language (Smalltalk, Beta, etc.) have influenced mainstream programming but haven't ended up as the most widely-used notations.

Finally, I can't resist pointing out that your comments re FP are highly parallel to the remarks I heard from procedural programmers not that many years ago:

  • The (mythical, IMHO) "average" programmer doesn't understand it.
  • It's not widely taught.
  • Any program you can write with it can be written another way with current techniques.

Just as graphical user interfaces and "code as a model of the business" were concepts that helped OO become more widely appreciated, I believe that increased use of immutability and simpler (massive) parallelism will help more programmers see the benefits that the functional approach offers. But as much as we've learned in the past 50 or so years that make up the entire history of digital computer programming, I think we still have much to learn. Twenty years from now, programmers will look back in amazement at the primitive nature of the tools we're currently using, including the now-popular OO and FP languages.

Doing a cleanup action just before Node.js exits

The script below allows having a single handler for all exit conditions. It uses an app specific callback function to perform custom cleanup code.

cleanup.js

// Object to capture process exits and call app specific cleanup function

function noOp() {};

exports.Cleanup = function Cleanup(callback) {

  // attach user callback to the process event emitter
  // if no callback, it will still exit gracefully on Ctrl-C
  callback = callback || noOp;
  process.on('cleanup',callback);

  // do app specific cleaning before exiting
  process.on('exit', function () {
    process.emit('cleanup');
  });

  // catch ctrl+c event and exit normally
  process.on('SIGINT', function () {
    console.log('Ctrl-C...');
    process.exit(2);
  });

  //catch uncaught exceptions, trace, then exit normally
  process.on('uncaughtException', function(e) {
    console.log('Uncaught Exception...');
    console.log(e.stack);
    process.exit(99);
  });
};

This code intercepts uncaught exceptions, Ctrl+C and normal exit events. It then calls a single optional user cleanup callback function before exiting, handling all exit conditions with a single object.

The module simply extends the process object instead of defining another event emitter. Without an app specific callback the cleanup defaults to a no op function. This was sufficient for my use where child processes were left running when exiting by Ctrl+C.

You can easily add other exit events such as SIGHUP as desired. Note: per NodeJS manual, SIGKILL cannot have a listener. The test code below demonstrates various ways of using cleanup.js

// test cleanup.js on version 0.10.21

// loads module and registers app specific cleanup callback...
var cleanup = require('./cleanup').Cleanup(myCleanup);
//var cleanup = require('./cleanup').Cleanup(); // will call noOp

// defines app specific callback...
function myCleanup() {
  console.log('App specific cleanup code...');
};

// All of the following code is only needed for test demo

// Prevents the program from closing instantly
process.stdin.resume();

// Emits an uncaught exception when called because module does not exist
function error() {
  console.log('error');
  var x = require('');
};

// Try each of the following one at a time:

// Uncomment the next line to test exiting on an uncaught exception
//setTimeout(error,2000);

// Uncomment the next line to test exiting normally
//setTimeout(function(){process.exit(3)}, 2000);

// Type Ctrl-C to test forced exit 

How to iterate over columns of pandas dataframe to run regression

Based on the accepted answer, if an index corresponding to each column is also desired:

for i, column in enumerate(df):
    print i, df[column]

The above df[column] type is Series, which can simply be converted into numpy ndarrays:

for i, column in enumerate(df):
    print i, np.asarray(df[column])

How to decrypt the password generated by wordpress

You will not be able to retrieve a plain text password from wordpress.

Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.

See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password

TortoiseGit save user authentication / credentials

For msysgit 1.8.0, download git-credential-wincred.exe from https://github.com/downloads/msysgit/git/git-credential-wincred.zip and put into C:\Program Files\Git\libexec\git-core

For msysgit 1.8.1 and later, the exe is built-in.

in git config, add the following settings.

[credential] helper = wincred

Writing .csv files from C++

Here is a STL-like class

File "csvfile.h"

#pragma once

#include <iostream>
#include <fstream>

class csvfile;

inline static csvfile& endrow(csvfile& file);
inline static csvfile& flush(csvfile& file);

class csvfile
{
    std::ofstream fs_;
    const std::string separator_;
public:
    csvfile(const std::string filename, const std::string separator = ";")
        : fs_()
        , separator_(separator)
    {
        fs_.exceptions(std::ios::failbit | std::ios::badbit);
        fs_.open(filename);
    }

    ~csvfile()
    {
        flush();
        fs_.close();
    }

    void flush()
    {
        fs_.flush();
    }

    void endrow()
    {
        fs_ << std::endl;
    }

    csvfile& operator << ( csvfile& (* val)(csvfile&))
    {
        return val(*this);
    }

    csvfile& operator << (const char * val)
    {
        fs_ << '"' << val << '"' << separator_;
        return *this;
    }

    csvfile& operator << (const std::string & val)
    {
        fs_ << '"' << val << '"' << separator_;
        return *this;
    }

    template<typename T>
    csvfile& operator << (const T& val)
    {
        fs_ << val << separator_;
        return *this;
    }
};


inline static csvfile& endrow(csvfile& file)
{
    file.endrow();
    return file;
}

inline static csvfile& flush(csvfile& file)
{
    file.flush();
    return file;
}

File "main.cpp"

#include "csvfile.h"

int main()
{
    try
    {
        csvfile csv("MyTable.csv"); // throws exceptions!
        // Header
        csv << "X" << "VALUE"        << endrow;
        // Data
        csv <<  1  << "String value" << endrow;
        csv <<  2  << 123            << endrow;
        csv <<  3  << 1.f            << endrow;
        csv <<  4  << 1.2            << endrow;
    }
    catch (const std::exception& ex)
    {
        std::cout << "Exception was thrown: " << e.what() << std::endl;
    }
    return 0;
}

Latest version here

Find and kill a process in one line using bash and regex

I use this to kill Firefox when it's being script slammed and cpu bashing :) Replace 'Firefox' with the app you want to die. I'm on the Bash shell - OS X 10.9.3 Darwin.

kill -Hup $(ps ux | grep Firefox | awk 'NR == 1 {next} {print $2}' | uniq | sort)

What is IllegalStateException?

package com.concepttimes.java;

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

public class IllegalStateExceptionDemo {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        List al = new ArrayList();
        al.add("Sachin");
        al.add("Rahul");
        al.add("saurav");
        Iterator itr = al.iterator();  
        while (itr.hasNext()) {           
            itr.remove();
        }
    }
}

IllegalStateException signals that method has been invoked at the wrong time. In this below example, we can see that. remove() method is called at the same time element is being used in while loop.

Please refer to below link for more details. http://www.elitmuszone.com/elitmus/illegalstateexception-in-java/

How to show full object in Chrome console?

You might get even better results if you try:

console.log(JSON.stringify(obj, null, 4));

Jupyter notebook not running code. Stuck on In [*]

Based on you kernel status (upper right beside "Python 3", the one that is a circle). It seems that it is still busy. It might be trapped in an endless loop or maybe you've run/display something that is not closed.

How to Install pip for python 3.7 on Ubuntu 18?

For those who intend to use venv:

If you don't already have pip for Python 3:

sudo apt install python3-pip

Install venv package:

sudo apt install python3.7-venv

Create virtual environment (which will be bootstrapped with pip by default):

python3.7 -m venv /path/to/new/virtual/environment

To activate the virtual environment, source the appropriate script for the current shell, from the bin directory of the virtual environment. The appropriate scripts for the different shells are:

bash/zsh – activate

fish – activate.fish

csh/tcsh – activate.csh

For example, if using bash:

source /path/to/new/virtual/environment/bin/activate

Optionally, to update pip for the virtual environment (while it is activated):

pip install --upgrade pip

When you want to deactivate the virtual environment:

deactivate 

How can I send a Firebase Cloud Messaging notification without use the Firebase Console?

Go to cloud Messaging select:  Server key



function sendGCM($message, $deviceToken) {

    $url = 'https://fcm.googleapis.com/fcm/send';
    $fields = array (
            'registration_ids' => array (
                $id
            ),
            'data' => array (
                "title" =>  "Notification title",
                "body" =>  $message,
            )
    );
    $fields = json_encode ( $fields );
    $headers = array (
        'Authorization: key=' . "YOUR_SERVER_KEY",
        'Content-Type: application/json'
    );
    $ch = curl_init ();
    curl_setopt ( $ch, CURLOPT_URL, $url );
    curl_setopt ( $ch, CURLOPT_POST, true );
    curl_setopt ( $ch, CURLOPT_HTTPHEADER, $headers );
    curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
    curl_setopt ( $ch, CURLOPT_POSTFIELDS, $fields );
    $result = curl_exec ( $ch );
    echo $result;

    curl_close ($ch);
}

Auto-indent in Notepad++

If the TextFX menu does not exist, you need to download & install the plugin. Plugins->Plugin Manager->Show Plugin Manager and then check the plugin TextFX Characters. Click 'install,' restart Notepad++.

In version Notepad++ v6.1.3, I resolve with: Plugin Manager->Show Plugin Manager** and then check the plugin "Indent By Fold"

jquery - disable click

If you're using jQuery versions 1.4.3+:

$('selector').click(false);

If not:

$('selector').click(function(){return false;});

Converting Long to Date in Java returns 1970

1220227200 corresponds to Jan 15 1980 (and indeed new Date(1220227200).toString() returns "Thu Jan 15 03:57:07 CET 1970"). If you pass a long value to a date, that is before 01/01/1970 it will in fact return a date of 01/01/1970. Make sure that your values are not in this situation (lower than 82800000).

How to run the sftp command with a password from Bash script?

Bash program to wait for sftp to ask for a password then send it along:

#!/bin/bash
expect -c "
spawn sftp username@your_host
expect \"Password\"
send \"your_password_here\r\"
interact "

You may need to install expect, change the wording of 'Password' to lowercase 'p' to match what your prompt receives. The problems here is that it exposes your password in plain text in the file as well as in the command history. Which nearly defeats the purpose of having a password in the first place.

REST API Authentication

Here's a guided approach.

Your authentication service issues a JWT token that is signed using a secret that is also available in your API service. The reason they need to be there too is that you will need to verify the tokens received to make sure you created them. The nice thing about JWTs is that their payload can hold claims as to what the user is authorised to access should different users have different access control levels.

That architecture renders authentication stateless: No need to store any tokens in a database unless you would like to handle token blacklisting (think banning users). Being stateless is crucial if you ever need to scale. That also frees up your API service from having to call the authentication server at all as the information they need for both authentication and authorisation are in the issued token.

Flow (no refresh tokens):

  1. User authenticates with the authentication server (eg: POST /auth/login) and receives a JWT token generated and signed by the auth server.
  2. User uses that token to talk to your API and assuming user is authorised), gets and posts the necessary resources.

There are a couple of issues here. Namely, that auth token in the wrong hands provides unlimited access to a malicious user to pretend they are the affected user and call your APIs indefinitely. To handle that, tokens have an expiry date and clients are forced to request new tokens whenever expiry happens. That expiry is part of the token's payload. But if tokens are short-lived, do we require users to authenticate with their usernames and password every time? No. We do not want to ask a user for their password every 30min to an hour, and we do not want to persist that password anywhere in the client. To get around that issue, we introduce the concept of refresh tokens. They are longer lived tokens that serve one purpose: act as a user's password, authenticate them to get a new token. Downside is that with this architecture your authentication server needs to persist these refresh token in a database.

New flow (with refresh tokens):

  1. User authenticates with the authentication server (eg: POST /auth/login) and receives a JWT token generated and signed by the auth server, alongside a long lived (eg: 6 months) refresh token that they store securely
  2. Whenever the user needs to make an API request, the token's expiry is checked. Assuming it has not yet expired, user uses that token to talk to your API and assuming user is authorised), gets and posts the necessary resources.
  3. If the token has indeed expired, there is a need to refresh your token, user calls authentication server (EG: POST / auth/token) and passes the securely stored refresh token. Response is a new access token issued.
  4. Use that new token to talk to your API image servers.

OPTIONAL (banning users)

How do we ban users? Using that model there is no easy way to do so. Enhancement: Every persisted refresh token includes a blacklisted field and only issue new tokens if the refresh token isn't black listed.

Things to consider:

  • You may want to rotate refresh token. To do so, blacklist the refresh token each time your user needs a new access token. That way refresh tokens can only be used once. Downside you will end up with a lot more refresh tokens but that can easily be solved with a job that clears blacklisted refresh tokens (eg: once a day)
  • You may want to consider setting a maximum number of allowed refresh tokens issued per user (say 10 or 20) as you issue a new one every time they login (with username and password). This number depends on your flow, how many clients a user may use (web, mobile, etc) and other factors.
  • Logout endpoint in your authentication service may or may not blacklist refresh tokens. Something to think about.

How to resolve the error "Unable to access jarfile ApacheJMeter.jar errorlevel=1" while initiating Jmeter?

This error could also happen because of version mismatch of jmeter and java. As jmeter versions supports different java versions as below.

Image of java versions supported for jmeter versions

Download the zip accordingly and you are good to go.

Creating layout constraints programmatically

Please also note that from iOS9 we can define constraints programmatically "more concise, and easier to read" using subclasses of the new helper class NSLayoutAnchor.

An example from the doc:

[self.cancelButton.leadingAnchor constraintEqualToAnchor:self.saveButton.trailingAnchor constant: 8.0].active = true;

How to assign string to bytes array

Besides the methods mentioned above, you can also do a trick as

s := "hello"
b := *(*[]byte)(unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&s))))

Go Play: http://play.golang.org/p/xASsiSpQmC

You should never use this :-)

How to discard local changes and pull latest from GitHub repository

To push over old repo. git push -u origin master --force

I think the --force would work for a pull as well.

Java - ignore exception and continue

Printing the STACK trace, logging it or send message to the user, are very bad ways to process the exceptions. Does any one can describe solutions to fix the exception in proper steps then can trying the broken instruction again?

Understanding dict.copy() - shallow or deep?

By "shallow copying" it means the content of the dictionary is not copied by value, but just creating a new reference.

>>> a = {1: [1,2,3]}
>>> b = a.copy()
>>> a, b
({1: [1, 2, 3]}, {1: [1, 2, 3]})
>>> a[1].append(4)
>>> a, b
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})

In contrast, a deep copy will copy all contents by value.

>>> import copy
>>> c = copy.deepcopy(a)
>>> a, c
({1: [1, 2, 3, 4]}, {1: [1, 2, 3, 4]})
>>> a[1].append(5)
>>> a, c
({1: [1, 2, 3, 4, 5]}, {1: [1, 2, 3, 4]})

So:

  1. b = a: Reference assignment, Make a and b points to the same object.

    Illustration of 'a = b': 'a' and 'b' both point to '{1: L}', 'L' points to '[1, 2, 3]'.

  2. b = a.copy(): Shallow copying, a and b will become two isolated objects, but their contents still share the same reference

    Illustration of 'b = a.copy()': 'a' points to '{1: L}', 'b' points to '{1: M}', 'L' and 'M' both point to '[1, 2, 3]'.

  3. b = copy.deepcopy(a): Deep copying, a and b's structure and content become completely isolated.

    Illustration of 'b = copy.deepcopy(a)': 'a' points to '{1: L}', 'L' points to '[1, 2, 3]'; 'b' points to '{1: M}', 'M' points to a different instance of '[1, 2, 3]'.

'Use of Unresolved Identifier' in Swift

My issue was calling my program with the same name as one of its cocoapods. It caused a conflict. Solution: Create a program different name.

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

How do I turn a C# object into a JSON string in .NET?

In your Lad model class, add an override to the ToString() method that returns a JSON string version of your Lad object.
Note: you will need to import System.Text.Json;

using System.Text.Json;

class MyDate
{
    int year, month, day;
}

class Lad
{
    public string firstName { get; set; };
    public string lastName { get; set; };
    public MyDate dateOfBirth { get; set; };
    public override string ToString() => JsonSerializer.Serialize<Lad>(this);
}

How to add title to seaborn boxplot

.set_title('') can be used to add title to Seaborn Plot

import seaborn as sb
sb.boxplot().set_title('Title')

How to split (chunk) a Ruby array into parts of X elements?

If you're using rails you can also use in_groups_of:

foo.in_groups_of(3)

java: run a function after a specific number of seconds

All other unswers require to run your code inside a new thread. In some simple use cases you may just want to wait a bit and continue execution within the same thread/flow.

Code below demonstrates that technique. Keep in mind this is similar to what java.util.Timer does under the hood but more lightweight.

import java.util.concurrent.TimeUnit;
public class DelaySample {
    public static void main(String[] args) {
       DelayUtil d = new DelayUtil();
       System.out.println("started:"+ new Date());
       d.delay(500);
       System.out.println("half second after:"+ new Date());
       d.delay(1, TimeUnit.MINUTES); 
       System.out.println("1 minute after:"+ new Date());
    }
}

DelayUtil Implementation

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class DelayUtil {
    /** 
    *  Delays the current thread execution. 
    *  The thread loses ownership of any monitors. 
    *  Quits immediately if the thread is interrupted
    *  
    * @param duration the time duration in milliseconds
    */
   public void delay(final long durationInMillis) {
      delay(durationInMillis, TimeUnit.MILLISECONDS);
   }

   /** 
    * @param duration the time duration in the given {@code sourceUnit}
    * @param unit
    */
    public void delay(final long duration, final TimeUnit unit) {
        long currentTime = System.currentTimeMillis();
        long deadline = currentTime+unit.toMillis(duration);
        ReentrantLock lock = new ReentrantLock();
        Condition waitCondition = lock.newCondition();

        while ((deadline-currentTime)>0) {
            try {
                lock.lockInterruptibly();    
                waitCondition.await(deadline-currentTime, TimeUnit.MILLISECONDS);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return;
            } finally {
                lock.unlock();
            }
            currentTime = System.currentTimeMillis();
        }
    }
}

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

This may not be relevant to your specific issue, but I had a similar problem when the pickle archive had been created using gzip.

For example if a compressed pickle archive is made like this,

import gzip, pickle
with gzip.open('test.pklz', 'wb') as ofp:
    pickle.dump([1,2,3], ofp)

Trying to open it throws the errors

 with open('test.pklz', 'rb') as ifp:
     print(pickle.load(ifp))
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
_pickle.UnpicklingError: invalid load key, ''.

But, if the pickle file is opened using gzip all is harmonious

with gzip.open('test.pklz', 'rb') as ifp:
    print(pickle.load(ifp))

[1, 2, 3]

Twitter Bootstrap dropdown menu

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- core CSS -->
    <link href="http://webdesign9.in/css/bootstrap.min.css" rel="stylesheet">
    <link href="http://webdesign9.in/css/font-awesome.min.css" rel="stylesheet">
    <link href="http://webdesign9.in/css/responsive.css" rel="stylesheet">
    <!--[if lt IE 9]>
    <script src="js/html5shiv.js"></script>
    <script src="js/respond.min.js"></script>
    <![endif]-->       
</head><!--/head-->
<body class="homepage">
    <header id="header">
        <nav class="navbar navbar-inverse" role="banner">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" title="Web Design Company in Mumbai" href="index.php"><img src="images/logo.png" alt="The Best Web Design Company in Mumbai" /></a>
                </div>
                <div class="collapse navbar-collapse navbar-right">
                    <ul class="nav navbar-nav">
                        <li class="active"><a href="index.php">Home</a></li>
                        <li><a href="about.php">About Us</a></li>
                        <li><a href="services.php">Services</a></li>
                        <li><a href="term-condition.php">Terms &amp; Condition</a></li></li>
                        <li><a href="contact.php">Contact</a></li>                        
                    </ul>
                </div>
            </div><!--/.container-->
        </nav><!--/nav-->
    </header><!--/header-->
    <script src="http://webdesign9.in/js/jquery.js"></script>
    <script src="http://webdesign9.in/js/bootstrap.min.js"></script>
</body>
</html>

How to pull remote branch from somebody else's repo

If antak's answer:

git fetch [email protected]:<THEIR USERNAME>/<REPO>.git <THEIR BRANCH>:<OUR NAME FOR BRANCH> 

gives you:

Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Then (following Przemek D's advice) use

git fetch https://github.com/<THEIR USERNAME>/<REPO>.git <THEIR BRANCH>:<OUR NAME FOR BRANCH>

How to change legend size with matplotlib.pyplot

There are multiple settings for adjusting the legend size. The two I find most useful are:

  • labelspacing: which sets the spacing between label entries in multiples of the font size. For instance with a 10 point font, legend(..., labelspacing=0.2) will reduce the spacing between entries to 2 points. The default on my install is about 0.5.
  • prop: which allows full control of the font size, etc. You can set an 8 point font using legend(..., prop={'size':8}). The default on my install is about 14 points.

In addition, the legend documentation lists a number of other padding and spacing parameters including: borderpad, handlelength, handletextpad, borderaxespad, and columnspacing. These all follow the same form as labelspacing and area also in multiples of fontsize.

These values can also be set as the defaults for all figures using the matplotlibrc file.

Draggable div without jQuery UI

$(document).ready(function() {
    var $startAt = null;

    $(document.body).live("mousemove", function(e) {
        if ($startAt) {
            $("#someDiv").offset({
                top: e.pageY,
                left: $("#someDiv").position().left-$startAt+e.pageX
            });
            $startAt = e.pageX; 
        }
    });

    $("#someDiv").live("mousedown", function (e) {$startAt = e.pageX;});
    $(document.body).live("mouseup", function (e) {$startAt = null;});
});

How to change text and background color?

SetConsoleTextAttribute.

HANDLE hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(hStdOut, FOREGROUND_RED | BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED);

This would produce red text on a white background.

Image resizing in React Native

Try this: (for more details click here)

image: { flex: 1, height: undefined, width: undefined, resizeMode: 'contain' }

CREATE DATABASE permission denied in database 'master' (EF code-first)

This error can also occur if you have multiple projects in the solution and the wrong one is set as the start-up project.

This matters because the connection string used by Update-Database comes from the start-up project, rather than the "Default project" selected in the package manager console.

(credits to masoud)

Format output string, right alignment

You can align it like that:

print('{:>8} {:>8} {:>8}'.format(*words))

where > means "align to right" and 8 is the width for specific value.

And here is a proof:

>>> for line in [[1, 128, 1298039], [123388, 0, 2]]:
    print('{:>8} {:>8} {:>8}'.format(*line))


       1      128  1298039
  123388        0        2

Ps. *line means the line list will be unpacked, so .format(*line) works similarly to .format(line[0], line[1], line[2]) (assuming line is a list with only three elements).

Changing background colour of tr element on mouseover

I had the same problem:

tr:hover { background: #000 !important; }

allone did not work, but adding

tr:hover td { background: transparent; }

to the next line of my css did the job for me!! My problem was that some of the TDs already had a background-color assigned and I did not know that I have to set that to TRANSPARENT to make the tr:hover work.

Actually, I used it with a classnames:

.trclass:hover { background: #000 !important; }
.trclass:hover td { background: transparent; }

Thanks for these answers, they made my day!! :)

How to break lines in PowerShell?

I think I found it. All you have to do is type in "`n" (WITH THE QUOTATION MARKS!)

Thanks!

How to get JSON objects value if its name contains dots?

Just to make use of updated solution try using lodash utility https://lodash.com/docs#get

iPhone viewWillAppear not firing

I just had this problem myself and it took me 3 full hours (2 of which googling) to fix it.

What turned out to help was to simply delete the app from the device/simulator, clean and then run again.

Hope that helps

Hiding the address bar of a browser (popup)

There is no definite way to do that. JS may have the API, but the browser vendor may choose not to implement it or implement it in another way.

Also, as far as I remember, Opera even provides the user preferences to prevent JS from making such changes, like have the window move, change status bar content, and stuff like that.

How do I use select with date condition?

If you put in

SELECT * FROM Users WHERE RegistrationDate >= '1/20/2009' 

it will automatically convert the string '1/20/2009' into the DateTime format for a date of 1/20/2009 00:00:00. So by using >= you should get every user whose registration date is 1/20/2009 or more recent.

Edit: I put this in the comment section but I should probably link it here as well. This is an article detailing some more in depth ways of working with DateTime's in you queries: http://www.databasejournal.com/features/mssql/article.php/2209321/Working-with-SQL-Server-DateTime-Variables-Part-Three---Searching-for-Particular-Date-Values-and-Ranges.htm

angular.js ng-repeat li items with html content

Note that ng-bind-html-unsafe is no longer suppported in rc 1.2. Use ng-bind-html instead. See: With ng-bind-html-unsafe removed, how do I inject HTML?

Defining arrays in Google Scripts

Try this

function readRows() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var rows = sheet.getDataRange();
  var numRows = rows.getNumRows();
  //var values = rows.getValues();

  var Names = sheet.getRange("A2:A7");
  var Name = [
    Names.getCell(1, 1).getValue(),
    Names.getCell(2, 1).getValue(),
    .....
    Names.getCell(5, 1).getValue()]

You can define arrays simply as follows, instead of allocating and then assigning.

var arr = [1,2,3,5]

Your initial error was because of the following line, and ones like it

var Name[0] = Name_cell.getValue(); 

Since Name is already defined and you are assigning the values to its elements, you should skip the var, so just

Name[0] = Name_cell.getValue();

Pro tip: For most issues that, like this one, don't directly involve Google services, you are better off Googling for the way to do it in javascript in general.

How to combine results of two queries into a single dataset

Try this:

SELECT ProductName,NumberofProducts ,NumberofProductssold
   FROM table1 
     JOIN table2
     ON table1.ProductName = table2.ProductName

What is the difference between atan and atan2 in C++?

I guess the main question tries to figure out: "when should I use one or the other", or "which should I use", or "Am I using the right one"?

I guess the important point is atan only was intended to feed positive values in a right-upwards direction curve like for time-distance vectors. Cero is always at the bottom left, and thigs can only go up and right, just slower or faster. atan doesn't return negative numbers, so you can't trace things in the 4 directions on a screen just by adding/subtracting its result.

atan2 is intended for the origin to be in the middle, and things can go backwards or down. That's what you'd use in a screen representation, because it DOES matter what direction you want the curve to go. So atan2 can give you negative numbers, because its cero is in the center, and its result is something you can use to trace things in 4 directions.

Missing XML comment for publicly visible type or member

In your solution, once you check the option to generate XML Document file, it start checking your public members, for having the XMLDoc, if they don't, you'll receive a warning per each element. if you don't really want to release your DLL, and also you don't need documentations then, go to your solution, build section, and turn it off, else if you need it, so fill them, and if there are unimportant properties and fields, just surpass them with pre-compiler instruction #pragma warning disable 1591 you can also restore the warning : #pragma warning restore 1591

pragma usage: any where in code before the place you get compiler warning for... (for file, put it in header, and you do not need to enable it again, for single class wrap around a class, or for method wrap around a method, or ... you do not either need to wrap it around, you can call it and restore it casually (start in begin of file, and end inside a method)), write this code:

#pragma warning disable 1591 and in case you need to restore it, use: #pragma warning restore 1591

Here an example:

using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Attributes;
using RealEstate.Entity.Models.Base;

namespace RealEstate.Models.Base
{
    public class CityVM
    {

#pragma warning disable 1591

        [Required]
        public string Id { get; set; }

        [Required]
        public string Name { get; set; }

        public List<LanguageBasedName> LanguageBasedNames { get; set; }

        [Required]
        public string CountryId { get; set; }

#pragma warning restore 1591

        /// <summary>
        /// Some countries do not have neither a State, nor a Province
        /// </summary>
        public string StateOrProvinceId { get; set; }
    }
}

Note that pragma directive start at the begin of line

force client disconnect from server with socket.io and nodejs

Edit: This is now possible

You can now simply call socket.disconnect() on the server side.

My original answer:

This is not possible yet.

If you need it as well, vote/comment on this issue.

Removing a list of characters in string

If you are using python3 and looking for the translate solution - the function was changed and now takes 1 parameter instead of 2.

That parameter is a table (can be dictionary) where each key is the Unicode ordinal (int) of the character to find and the value is the replacement (can be either a Unicode ordinal or a string to map the key to).

Here is a usage example:

>>> list = [',', '!', '.', ';']
>>> s = "This is, my! str,ing."
>>> s.translate({ord(x): '' for x in list})
'This is my string'

Call web service in excel

Yes You Can!

I worked on a project that did that (see comment). Unfortunately no code samples from that one, but googling revealed these:

How you can integrate data from several Web services using Excel and VBA

STEP BY STEP: Consuming Web Services through VBA (Excel or Word)

VBA: Consume Soap Web Services

On a CSS hover event, can I change another div's styling?

The following example is based on jQuery but it can be achieved using any JS tool kit or even plain old JS

$(document).ready(function(){
     $("#a").mouseover(function(){
         $("#b").css("background-color", "red");
     });
});

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

Alternatively, you could use a class for it and an instance for the check.

_x000D_
_x000D_
function A() {_x000D_
    var value = 0;_x000D_
    this.valueOf = function () { return ++value; };_x000D_
}_x000D_
_x000D_
var a = new A;_x000D_
_x000D_
if (a == 1 && a == 2 && a == 3) {_x000D_
    console.log('bingo!');_x000D_
}
_x000D_
_x000D_
_x000D_

EDIT

Using ES6 classes it would look like this

_x000D_
_x000D_
class A {_x000D_
  constructor() {_x000D_
    this.value = 0;_x000D_
    this.valueOf();_x000D_
  }_x000D_
  valueOf() {_x000D_
    return this.value++;_x000D_
  };_x000D_
}_x000D_
_x000D_
let a = new A;_x000D_
_x000D_
if (a == 1 && a == 2 && a == 3) {_x000D_
  console.log('bingo!');_x000D_
}
_x000D_
_x000D_
_x000D_

Trigger to fire only if a condition is met in SQL Server

The _ character is also a wildcard, BTW, but I'm not sure why this wasn't working for you:

CREATE TRIGGER 
    [dbo].[SystemParameterInsertUpdate]
ON 
    [dbo].[SystemParameter]
FOR INSERT, UPDATE 
AS
  BEGIN
    SET NOCOUNT ON
      INSERT INTO SystemParameterHistory 
      (
        Attribute,
        ParameterValue,
        ParameterDescription,
        ChangeDate
      )
    SELECT
      I.Attribute,
      I.ParameterValue,
      I.ParameterDescription,
      I.ChangeDate
    FROM Inserted AS I
    WHERE I.Attribute NOT LIKE 'NoHist[_]%'
END

Script not served by static file handler on IIS7.5

alt text

should check out this option i suppose

Performance of FOR vs FOREACH in PHP

My personal opinion is to use what makes sense in the context. Personally I almost never use for for array traversal. I use it for other types of iteration, but foreach is just too easy... The time difference is going to be minimal in most cases.

The big thing to watch for is:

for ($i = 0; $i < count($array); $i++) {

That's an expensive loop, since it calls count on every single iteration. So long as you're not doing that, I don't think it really matters...

As for the reference making a difference, PHP uses copy-on-write, so if you don't write to the array, there will be relatively little overhead while looping. However, if you start modifying the array within the array, that's where you'll start seeing differences between them (since one will need to copy the entire array, and the reference can just modify inline)...

As for the iterators, foreach is equivalent to:

$it->rewind();
while ($it->valid()) {
    $key = $it->key();     // If using the $key => $value syntax
    $value = $it->current();

    // Contents of loop in here

    $it->next();
}

As far as there being faster ways to iterate, it really depends on the problem. But I really need to ask, why? I understand wanting to make things more efficient, but I think you're wasting your time for a micro-optimization. Remember, Premature Optimization Is The Root Of All Evil...

Edit: Based upon the comment, I decided to do a quick benchmark run...

$a = array();
for ($i = 0; $i < 10000; $i++) {
    $a[] = $i;
}

$start = microtime(true);
foreach ($a as $k => $v) {
    $a[$k] = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {
    $v = $v + 1;
}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => $v) {}
echo "Completed in ", microtime(true) - $start, " Seconds\n";

$start = microtime(true);
foreach ($a as $k => &$v) {}    
echo "Completed in ", microtime(true) - $start, " Seconds\n";

And the results:

Completed in 0.0073502063751221 Seconds
Completed in 0.0019769668579102 Seconds
Completed in 0.0011849403381348 Seconds
Completed in 0.00111985206604 Seconds

So if you're modifying the array in the loop, it's several times faster to use references...

And the overhead for just the reference is actually less than copying the array (this is on 5.3.2)... So it appears (on 5.3.2 at least) as if references are significantly faster...

Collapsing Sidebar with Bootstrap

Bootstrap 3

Yes, it's possible. This "off-canvas" example should help to get you started.

https://codeply.com/p/esYgHWB2zJ

Basically you need to wrap the layout in an outer div, and use media queries to toggle the layout on smaller screens.

/* collapsed sidebar styles */
@media screen and (max-width: 767px) {
  .row-offcanvas {
    position: relative;
    -webkit-transition: all 0.25s ease-out;
    -moz-transition: all 0.25s ease-out;
    transition: all 0.25s ease-out;
  }
  .row-offcanvas-right
  .sidebar-offcanvas {
    right: -41.6%;
  }

  .row-offcanvas-left
  .sidebar-offcanvas {
    left: -41.6%;
  }
  .row-offcanvas-right.active {
    right: 41.6%;
  }
  .row-offcanvas-left.active {
    left: 41.6%;
  }
  .sidebar-offcanvas {
    position: absolute;
    top: 0;
    width: 41.6%;
  }
  #sidebar {
    padding-top:0;
  }
}

Also, there are several more Bootstrap sidebar examples here


Bootstrap 4

Create a responsive navbar sidebar "drawer" in Bootstrap 4?

How to justify a single flexbox item (override justify-content)

For those situations where width of the items you do want to flex-end is known, you can set their flex to "0 0 ##px" and set the item you want to flex-start with flex:1

This will cause the pseudo flex-start item to fill the container, just format it to text-align:left or whatever.

Conda environments not showing up in Jupyter Notebook

First you need to activate your environment .

pip install ipykernel

Next you can add your virtual environment to Jupyter by typing:

python -m ipykernel install --name = my_env

Insert Multiple Rows Into Temp Table With SQL Server 2012

When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:

SQL Fiddle

MS SQL Server 2012 Schema Setup:

Query 1:

CREATE TABLE #Names
  ( 
    Name1 VARCHAR(100),
    Name2 VARCHAR(100)
  ) 

INSERT INTO #Names
  (Name1, Name2)
VALUES
  ('Matt', 'Matthew'),
  ('Matt', 'Marshal'),
  ('Matt', 'Mattison')

SELECT * FROM #NAMES

Results:

| NAME1 |    NAME2 |
--------------------
|  Matt |  Matthew |
|  Matt |  Marshal |
|  Matt | Mattison |

Here a SSMS 2012 screenshot: enter image description here

Why is there an unexplainable gap between these inline-block div elements?

Using inline-block allows for white-space in your HTML, This usually equates to .25em (or 4px).

You can either comment out the white-space or, a more commons solution, is to set the parent's font-size to 0 and the reset it back to the required size on the inline-block elements.

Set the layout weight of a TextView programmatically

just set layout params in that layout like

create param variable

 android.widget.LinearLayout.LayoutParams params = new android.widget.LinearLayout.LayoutParams(
            LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT, 1f);

1f is weight variable

set your widget or layout like

 TextView text = (TextView) findViewById(R.id.text);
 text.setLayoutParams(params);

Five equal columns in twitter bootstrap

Bootstrap or other grid system it doesn't always mean simpler and better. Inside your .container or .row (to keep your responsive layout) u can just create 5 divs (with class .col f.e.) and add css like this:
.col { width: 20%; float: left };

update: nowodays its better to use flexbox

What are the sizes used for the iOS application splash screen?

With iOS 7+, static Launch Images are now deprecated.

You should create a custom view that composes slices of images, which sizes to all screens like a normal UIViewController view.

https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/LaunchImages.html

Mvn install or Mvn package

Also you should note that if your project is consist of several modules which are dependent on each other, you should use "install" instead of "package", otherwise your build will fail, cause when you use install command, module A will be packaged and deployed to local repository and then if module B needs module A as a dependency, it can access it from local repository.

Correct way to synchronize ArrayList in java

Let's take a normal list (implemented by the ArrayList class) and make it synchronized. This is shown in the SynchronizedListExample class. We pass the Collections.synchronizedList method a new ArrayList of Strings. The method returns a synchronized List of Strings. //Here is SynchronizedArrayList class

package com.mnas.technology.automation.utility;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import org.apache.log4j.Logger;
/**
* 
* @author manoj.kumar
* @email [email protected]
* 
*/
public class SynchronizedArrayList {
    static Logger log = Logger.getLogger(SynchronizedArrayList.class.getName());
    public static void main(String[] args) {    
        List<String> synchronizedList = Collections.synchronizedList(new ArrayList<String>());
        synchronizedList.add("Aditya");
        synchronizedList.add("Siddharth");
        synchronizedList.add("Manoj");
        // when iterating over a synchronized list, we need to synchronize access to the synchronized list
        synchronized (synchronizedList) {
            Iterator<String> iterator = synchronizedList.iterator();
            while (iterator.hasNext()) {
                log.info("Synchronized Array List Items: " + iterator.next());
            }
        }    
    }
}

Notice that when iterating over the list, this access is still done using a synchronized block that locks on the synchronizedList object. In general, iterating over a synchronized collection should be done in a synchronized block

MAC addresses in JavaScript

Nope. The reason ActiveX can do it is because ActiveX is a little application that runs on the client's machine.

I would imagine access to such information via JavaScript would be a security vulnerability.

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

You can use RTRIM or cast your value to VARCHAR:

SELECT RIGHT(RTRIM(Field),3), LEFT(Field,LEN(Field)-3)

Or

SELECT RIGHT(CAST(Field AS VARCHAR(15)),3), LEFT(Field,LEN(Field)-3)

Check if element is visible in DOM

According to this MDN documentation, an element's offsetParent property will return null whenever it, or any of its parents, is hidden via the display style property. Just make sure that the element isn't fixed. A script to check this, if you have no position: fixed; elements on your page, might look like:

// Where el is the DOM element you'd like to test for visibility
function isHidden(el) {
    return (el.offsetParent === null)
}

On the other hand, if you do have position fixed elements that might get caught in this search, you will sadly (and slowly) have to use window.getComputedStyle(). The function in that case might be:

// Where el is the DOM element you'd like to test for visibility
function isHidden(el) {
    var style = window.getComputedStyle(el);
    return (style.display === 'none')
}

Option #2 is probably a little more straightforward since it accounts for more edge cases, but I bet its a good deal slower, too, so if you have to repeat this operation many times, best to probably avoid it.

Disable submit button when form invalid with AngularJS

If you are using Reactive Forms you can use this:

<button [disabled]="!contactForm.valid" type="submit" class="btn btn-lg btn primary" (click)="printSomething()">Submit</button>

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

For Spring-boot 1.3.3 the method exchange() for List is working as in the related answer

Spring Data Rest - _links

How display only years in input Bootstrap Datepicker?

format: "YYYY" 

Should be capital instead of "yyyy"

Case insensitive comparison NSString

Alternate solution for swift:

To make both UpperCase:

e.g:

if ("ABcd".uppercased() == "abcD".uppercased()){
}

or to make both LowerCase:

e.g:

if ("ABcd".lowercased() == "abcD".lowercased()){
}

Regex Letters, Numbers, Dashes, and Underscores

You can indeed match all those characters, but it's safer to escape the - so that it is clear that it be taken literally.

If you are using a POSIX variant you can opt to use:

([[:alnum:]\-_]+)

But a since you are including the underscore I would simply use:

([\w\-]+)

(works in all variants)

resize2fs: Bad magic number in super-block while trying to open

I ran into the same exact problem around noon today and finally found a solution here --> Trying to resize2fs EB volume fails

I skipped mounting, since the partition was already mounted.

Apparently CentOS 7 uses XFS as the default file system and as a result resize2fs will fail.

I took a look in /etc/fstab, and guess what, XFS was staring me in the face... Hope this helps.

Renaming columns in Pandas

df.rename(index=str, columns={'A':'a', 'B':'b'})

pandas.DataFrame.rename

how to view the contents of a .pem certificate

An alternative to using keytool, you can use the command

openssl x509 -in certificate.pem -text

This should work for any x509 .pem file provided you have openssl installed.

Reason: no suitable image found

For me this issue was appearing due to the WWRD cert -- Mine was up to date but for some reason it was set to 'always trust' instead of 'use system default', which apparently makes a difference.

How to create a delay in Swift?

In Swift 4.2 and Xcode 10.1

You have 4 ways total to delay. Out of these option 1 is preferable to call or execute a function after some time. The sleep() is least case in use.

Option 1.

DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
    self.yourFuncHere()
}
//Your function here    
func yourFuncHere() {

}

Option 2.

perform(#selector(yourFuncHere2), with: nil, afterDelay: 5.0)

//Your function here  
@objc func yourFuncHere2() {
    print("this is...")
}

Option 3.

Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(yourFuncHere3), userInfo: nil, repeats: false)

//Your function here  
@objc func yourFuncHere3() {

}

Option 4.

sleep(5)

If you want to call a function after some time to execute something don't use sleep.

json Uncaught SyntaxError: Unexpected token :

I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].

The one that worked for me is as follows: 1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ]. 2- add a script link to it just below the normal jQuery link. 3- add the line "crossOrigin: true," to your ajax function.

Good to go! here is my working code for this:

_x000D_
_x000D_
  $.ajax({_x000D_
      crossOrigin: true,_x000D_
      url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.86,151.195&radius=5000&type=ATM&keyword=ATM&key=MyKey",_x000D_
      type : "GET",_x000D_
      success:function(data){_x000D_
         console.log(data);_x000D_
      }_x000D_
    })
_x000D_
_x000D_
_x000D_

What's the easiest way to install a missing Perl module?

Lots of recommendation for CPAN.pm, which is great, but if you're using Perl 5.10 then you've also got access to CPANPLUS.pm which is like CPAN.pm but better.

And, of course, it's available on CPAN for people still using older versions of Perl. Why not try:

$ cpan CPANPLUS

What exactly does Perl's "bless" do?

This function tells the entity referenced by REF that it is now an object in the CLASSNAME package, or the current package if CLASSNAME is omitted. Use of the two-argument form of bless is recommended.

Example:

bless REF, CLASSNAME
bless REF

Return Value

This function returns the reference to an object blessed into CLASSNAME.

Example:

Following is the example code showing its basic usage, the object reference is created by blessing a reference to the package's class -

#!/usr/bin/perl

package Person;
sub new
{
    my $class = shift;
    my $self = {
        _firstName => shift,
        _lastName  => shift,
        _ssn       => shift,
    };
    # Print all the values just for clarification.
    print "First Name is $self->{_firstName}\n";
    print "Last Name is $self->{_lastName}\n";
    print "SSN is $self->{_ssn}\n";
    bless $self, $class;
    return $self;
}

Set background image according to screen resolution

Delete your "body background image code" then paste this code:

html { 
    background: url(../img/background.jpg) no-repeat center center fixed #000; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Execute combine multiple Linux commands in one line

What is the utility of an only one Ampersand? This morning, I made a launcher in the XFCE panel (in Manjaro+XFCE) to launch 2 passwords managers simultaneously:

sh -c "keepassx && password-gorilla"
or
sh -c "keepassx; password-gorilla"

But it does not work as I want. I.E., the first app starts but the second starts only when the previous is closed

However, I found that (with only one ampersand):

sh -c "keepassx & password-gorilla"

and it works as I want now...

The name 'ViewBag' does not exist in the current context

I updated webpages:Version under in ./Views/Web.Config folder but this setting was also present in web.config in root. Update both or remove from root web.config

Ignore self-signed ssl cert using Jersey Client

For Jersey 1.X

    TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {

        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {}

        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException {}

        public java.security.cert.X509Certificate[] getAcceptedIssuers() { 
            // or you can return null too
            return new java.security.cert.X509Certificate[0];
        }
    }};


    SSLContext sc = SSLContext.getInstance("TLS");
    sc.init(null, trustAllCerts, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
        public boolean verify(String string, SSLSession sslSession) {
            return true;
        }
    });

MongoDB not equal to

Use $ne instead of $not

http://docs.mongodb.org/manual/reference/operator/ne/#op._S_ne

db.collections.find({"name": {$ne: ""}});

MongoDB: How to find out if an array field contains an element?

It seems like the $in operator would serve your purposes just fine.

You could do something like this (pseudo-query):

if (db.courses.find({"students" : {"$in" : [studentId]}, "course" : courseId }).count() > 0) {
  // student is enrolled in class
}

Alternatively, you could remove the "course" : courseId clause and get back a set of all classes the student is enrolled in.