Programs & Examples On #Equinox

Use this tag for questions about Equinox which is an implementation of the OSGi R4 core framework specification, a set of bundles that implement various optional OSGi services and other infrastructure for running OSGi-based systems.

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Eclipse: Java was started but returned error code=13

This is caused when java is updated. You have to delete in environement path : C:**ProgramData\Oracle\Java\javapath**

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Please check if you got the x64 edition of eclipse. Someone answered this just a few hours ago.

NullPointerException in eclipse in Eclipse itself at PartServiceImpl.internalFixContext

Better you update your eclipse by clicking it on help >> check for updates, also you can start eclipse by entering command in command prompt eclipse -clean.
Hope this will help you.

"insufficient memory for the Java Runtime Environment " message in eclipse

Your application (Eclipse) needs more memory and JVM is not allocating enough.You can increase the amount of memory JVM allocates by following the answers given here

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

This happened to me when deleting some Equinox package from my plugins directory, make sure this is not the case.

Eclipse will not start and I haven't changed anything

I moved workbench.xmi located at workspace/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi to a backup folder. Then started eclipse and waited for all background processes to finish. Then I closed eclipse and moved my backup copy of workbench.xmi back (overwriting the one created with the last launch). Eclipse launched fine and I got all my settings back.

Can't access Eclipse marketplace

I know it's a bit old but I ran in the same problem today. I wanted to install eclipse on my vm with xubuntu. Because I've had problems with the latest eclipse version 2019-06 I tried with Oxygen. So I went to eclipse.org and downloaded oxygen. When running oxygen, the problem with merketplace not reachable occurs. So I downloaded the eclipse installer not immediatly the oxygen. After that I can use eclipse as expectet ( all versions)

Eclipse - Failed to create the java virtual machine

If Anybody Is using prior version then Jdk 8 update 20 and getting this Issue Please Remove the following from eclipse.ini file

-XX:+UseStringDeduplication

As StringDeduplication was added in later version of JDK 8 in update 20 For StringDeduplication Clarification check this By Fabian Lange https://blog.codecentric.de/en/2014/08/string-deduplication-new-feature-java-8-update-20-2/

Increase JVM max heap size for Eclipse

You can use this configuration:

-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.gtk.linux.x86_64_1.1.200.v20120913-144807
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Xms512m
-Xmx1024m
-XX:+UseParallelGC
-XX:PermSize=256M
-XX:MaxPermSize=512M

Can't start Eclipse - Java was started but returned exit code=13

I've solved this issue by installing a JDK (v7 update 80) whereas I had only had the JRE installed before.

Note: This was for IBM's RTC software (built on Eclipse).

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

Thanks a lot guys!

I overlooked my ECLIPSE VERSION it was 64Bit and 3.6

I had to make sure it's 32Bit Eclipse, 32 Bit JVM so i uninstalled Eclipse & all JVM for clean start. Installed 32Bit JDK1.6 from here and 32Bit Eclipse from here

Eclipse cannot load SWT libraries

SOLVED:

Because I had installed the Oracle Java 7 it had changed the default Java to Oracle Java 7, however it needed to be the Open JDK.

To fix, open up terminal and type

sudo update-alternatives --config java

This brings up a list of the different types of Java. Simply select the Open JDK.

An error occurred while collecting items to be installed (Access is denied)

Installig Eclispe ADT from market place solved this problem for me.

Eclipse hangs on loading workbench

./eclipse -clean -refresh

as mentioned in comment by sulai Dec 20 '12 at 12:46, that worked for me.

However, on the Mac OS X, I had to figure out how to get to ./eclipse

Here's the solution:

cd Eclipse.app/Contents/MacOS/

Thank you Andrew's comment for this post: https://stackoverflow.com/a/1783448/2162226

Eclipse error: 'Failed to create the Java Virtual Machine'

This worked for me:

I closed all the other memory intensive applications on my Windows 7 machine. And I tried to open Eclipse, and, voila, it worked.

What to do about Eclipse's "No repository found containing: ..." error messages?

I got this error (September 2020) during an automatic upgrade.

The solution was to add:

http://download.eclipse.org/releases/2020-09

to the list of Available Software Sites.

I also disabled:

http://download.eclipse.org/eclipse/updates/4.15

and several more with release numbers earlier than 4.15, but I don't think that was the important part.

Cannot run Eclipse; JVM terminated. Exit code=13

use the configuration below;

    -startup
    plugins/org.eclipse.equinox.launcher_1.3.0.v20130327-1440.jar
    --launcher.library
    plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20130807-1835
    -product
    org.springsource.ggts.ide
    --launcher.defaultAction
    openFile
    --launcher.XXMaxPermSize
    256M
    -vm
    C:\Program Files\Java\jdk1.7.0_51\jre\bin\javaw.exe
    -vmargs
    -Dorg.eclipse.swt.browser.IEVersion=10001
    -Dgrails.console.enable.interactive=false
    -Dgrails.console.enable.terminal=false
    -Djline.terminal=jline.UnsupportedTerminal
    -Dgrails.console.class=grails.build.logging.GrailsEclipseConsole
    -Dosgi.requiredJavaVersion=1.6
    -Xms40m
    -Xmx768m
    -XX:MaxPermSize=256m
    -Dorg.eclipse.swt.browser.IEVersion=10001

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

In your config.ini file of eclipse eclipse\configuration\config.ini check this three things:

osgi.framework=file\:plugins\\org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar
osgi.bundles=reference\:file\:org.eclipse.equinox.simpleconfigurator_1.0.0.v20080604.jar@1\:start
org.eclipse.equinox.simpleconfigurator.configUrl=file\:org.eclipse.equinox.simpleconfigurator\\bundles.info

And check whether these jars are in place or not, the jar files depend upon your version of eclipse .

How can I give eclipse more memory than 512M?

I don't think you need to change the MaxPermSize to 1024m. This works for me:

-startup
plugins/org.eclipse.equinox.launcher_1.0.200.v20090520.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.0.200.v20090519
-product
org.eclipse.epp.package.jee.product
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms256m
-Xmx1024m
-XX:PermSize=64m
-XX:MaxPermSize=128m

"Unable to acquire application service" error while launching Eclipse

in my opinion, if after trying all solution nothing wors then simply delete eclipse folder from your C://use/{pc}/eclipse and then again install the same eclipse . You will get all your data no need to worry.

This happens because of unexpected shutdown of your eclipse

Eclipse 3.5 Unable to install plugins

i fought with eclipse 3.5.0 (galileo) for days, i had to use this version because I am doing blackberry development and eclipse comes bundle with blackberry specifics so i need to use the package they bundled, which was not 3.5.0 (not the 3.5.1) , BUT SirFabel saved the day, thanks to all who contributed to this post

I used 3.5.0 and did "Set the following system property in you eclipse.ini file: -Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient For more details on this: wiki.eclipse.org/… - Configure only the HTTP and HTTPS proxies. Not SOCKS!! "

and I am able to get through my companies proxy!!!!

How do format a phone number as a String in Java?

You can implement your own method to do that for you, I recommend you to use something such as this. Using DecimalFormat and MessageFormat. With this method you can use pretty much whatever you want (String,Integer,Float,Double) and the output will be always right.

import java.text.DecimalFormat;
import java.text.MessageFormat;

/**
 * Created by Yamil Garcia Hernandez on 25/4/16.
 */

public class test {
    // Constants
    public static final DecimalFormat phoneFormatD = new DecimalFormat("0000000000");
    public static final MessageFormat phoneFormatM = new MessageFormat("({0}) {1}-{2}");

    // Example Method on a Main Class
    public static void main(String... args) {
        try {
            System.out.println(formatPhoneNumber("8091231234"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(formatPhoneNumber("18091231234"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(formatPhoneNumber("451231234"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(formatPhoneNumber("11231234"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(formatPhoneNumber("1231234"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(formatPhoneNumber("231234"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(formatPhoneNumber(""));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(formatPhoneNumber(0));
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(formatPhoneNumber(8091231234f));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    // Magic
    public static String formatPhoneNumber(Object phone) throws Exception {

        double p = 0;

        if (phone instanceof String)
            p = Double.valueOf((String) phone);

        if (phone instanceof Integer)
            p = (Integer) phone;

        if (phone instanceof Float)
            p = (Float) phone;

        if (phone instanceof Double)
            p = (Double) phone;

        if (p == 0 || String.valueOf(p) == "" || String.valueOf(p).length() < 7)
            throw new Exception("Paramenter is no valid");

        String fot = phoneFormatD.format(p);

        String extra = fot.length() > 10 ? fot.substring(0, fot.length() - 10) : "";
        fot = fot.length() > 10 ? fot.substring(fot.length() - 10, fot.length()) : fot;

        String[] arr = {
                (fot.charAt(0) != '0') ? fot.substring(0, 3) : (fot.charAt(1) != '0') ? fot.substring(1, 3) : fot.substring(2, 3),
                fot.substring(3, 6),
                fot.substring(6)
        };
        String r = phoneFormatM.format(arr);
        r = (r.contains("(0)")) ? r.replace("(0) ", "") : r;
        r = (extra != "") ? ("+" + extra + " " + r) : r;
        return (r);
    }
}

Result will be

(809) 123-1234
+1 (809) 123-1234
(45) 123-1234
(1) 123-1234
123-1234
023-1234
java.lang.NumberFormatException: empty String
    at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842)
    at sun.misc.FloatingDecimal.parseDouble(FloatingDecimal.java:110)
    at java.lang.Double.parseDouble(Double.java:538)
    at java.lang.Double.valueOf(Double.java:502)
    at test.formatPhoneNumber(test.java:66)
    at test.main(test.java:45)
java.lang.Exception: Paramenter is no valid
    at test.formatPhoneNumber(test.java:78)
    at test.main(test.java:50)
(809) 123-1232

Unnamed/anonymous namespaces vs. static functions

Personally I prefer static functions over nameless namespaces for the following reasons:

  • It's obvious and clear from function definition alone that it's private to the translation unit where it's compiled. With nameless namespace you might need to scroll and search to see if a function is in a namespace.

  • Functions in namespaces might be treated as extern by some (older) compilers. In VS2017 they are still extern. For this reason even if a function is in nameless namespace you might still want to mark them static.

  • Static functions behave very similar in C or C++, while nameless namespaces are obviously C++ only. nameless namespaces also add extra level in indentation and I don't like that :)

So, I'm happy to see that use of static for functions isn't deprecated anymore.

Share cookie between subdomain and domain

The 2 domains mydomain.com and subdomain.mydomain.com can only share cookies if the domain is explicitly named in the Set-Cookie header. Otherwise, the scope of the cookie is restricted to the request host. (This is referred to as a "host-only cookie". See What is a host only cookie?)

For instance, if you sent the following header from subdomain.mydomain.com, then the cookie won't be sent for requests to mydomain.com:

Set-Cookie: name=value

However if you use the following, it will be usable on both domains:

Set-Cookie: name=value; domain=mydomain.com

This cookie will be sent for any subdomain of mydomain.com, including nested subdomains like subsub.subdomain.mydomain.com.

In RFC 2109, a domain without a leading dot meant that it could not be used on subdomains, and only a leading dot (.mydomain.com) would allow it to be used across multiple subdomains (but not the top-level domain, so what you ask was not possible in the older spec).

However, all modern browsers respect the newer specification RFC 6265, and will ignore any leading dot, meaning you can use the cookie on subdomains as well as the top-level domain.

In summary, if you set a cookie like the second example above from mydomain.com, it would be accessible by subdomain.mydomain.com, and vice versa. This can also be used to allow sub1.mydomain.com and sub2.mydomain.com to share cookies.

See also:

how to get all markers on google-maps-v3

Google Maps API v3:

I initialized Google Map and added markers to it. Later, I wanted to retrieve all markers and did it simply by accessing the map property "markers".

var map = new GMaps({
    div: '#map',
    lat: 40.730610,
    lng: -73.935242,
});

var myMarkers = map.markers;

You can loop over it and access all Marker methods listed at Google Maps Reference.

HTML table sort

The way I have sorted HTML tables in the browser uses plain, unadorned Javascript.

The basic process is:

  1. add a click handler to each table header
  2. the click handler notes the index of the column to be sorted
  3. the table is converted to an array of arrays (rows and cells)
  4. that array is sorted using javascript sort function
  5. the data from the sorted array is inserted back into the HTML table

The table should, of course, be nice HTML. Something like this...

<table>
 <thead>
  <tr><th>Name</th><th>Age</th></tr>
 </thead>
 <tbody>
  <tr><td>Sioned</td><td>62</td></tr>
  <tr><td>Dylan</td><td>37</td></tr>
  ...etc...
 </tbody>
</table>

So, first adding the click handlers...

const table = document.querySelector('table'); //get the table to be sorted

table.querySelectorAll('th') // get all the table header elements
  .forEach((element, columnNo)=>{ // add a click handler for each 
    element.addEventListener('click', event => {
        sortTable(table, columnNo); //call a function which sorts the table by a given column number
    })
  })

This won't work right now because the sortTable function which is called in the event handler doesn't exist.

Lets write it...

function sortTable(table, sortColumn){
  // get the data from the table cells
  const tableBody = table.querySelector('tbody')
  const tableData = table2data(tableBody);
  // sort the extracted data
  tableData.sort((a, b)=>{
    if(a[sortColumn] > b[sortColumn]){
      return 1;
    }
    return -1;
  })
  // put the sorted data back into the table
  data2table(tableBody, tableData);
}

So now we get to the meat of the problem, we need to make the functions table2data to get data out of the table, and data2table to put it back in once sorted.

Here they are ...

// this function gets data from the rows and cells 
// within an html tbody element
function table2data(tableBody){
  const tableData = []; // create the array that'll hold the data rows
  tableBody.querySelectorAll('tr')
    .forEach(row=>{  // for each table row...
      const rowData = [];  // make an array for that row
      row.querySelectorAll('td')  // for each cell in that row
        .forEach(cell=>{
          rowData.push(cell.innerText);  // add it to the row data
        })
      tableData.push(rowData);  // add the full row to the table data 
    });
  return tableData;
}

// this function puts data into an html tbody element
function data2table(tableBody, tableData){
  tableBody.querySelectorAll('tr') // for each table row...
    .forEach((row, i)=>{  
      const rowData = tableData[i]; // get the array for the row data
      row.querySelectorAll('td')  // for each table cell ...
        .forEach((cell, j)=>{
          cell.innerText = rowData[j]; // put the appropriate array element into the cell
        })
      tableData.push(rowData);
    });
}

And that should do it.

A couple of things that you may wish to add (or reasons why you may wish to use an off the shelf solution): An option to change the direction and type of sort i.e. you may wish to sort some columns numerically ("10" > "2" is false because they're strings, probably not what you want). The ability to mark a column as sorted. Some kind of data validation.

Android Center text on canvas

In my case, I didn't have to put the text in the middle of a canvas, but in a wheel that spins. Though I had to use this code to succeed:

fun getTextRect(textSize: Float, textPaint: TextPaint, string: String) : PointF {
    val rect = RectF(left, top, right, bottom)
    val rectHeight = Rect()
    val cx = rect.centerX()
    val cy = rect.centerY()

    textPaint.getTextBounds(string, 0, string.length, rectHeight)
    val y = cy + rectHeight.height()/2
    val x = cx - textPaint.measureText(string)/2

    return PointF(x, y)
}

Then I call this method from the View class:

private fun drawText(canvas: Canvas, paint: TextPaint, text: String, string: String) {
    val pointF = getTextRect(paint.textSize, textPaint, string)
    canvas.drawText(text, pointF!!.x, pointF.y, paint)
}

Updating user data - ASP.NET Identity

OK... I spent hours trying to figure why userManager.updateAsync would not persist the user data that we edit ... until I reached the following conclusion:

The confusion arises from the fact that we create the UserManager in one line like this:

var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new MyDbContext()));

...then we use manager.UpdateAsync( user ); but that will update the user in the context, and then we will need to save changes to the dbcontext of the Identity. So, the question is how to get the Identity DBcontext in the easiest way.

To solve this, we should not create the UserManager in one line ... and here is how I do it:

var store = new UserStore<ApplicationUser>(new MyDbContext());
var manager = new UserManager(store);

then after updating the user by calling

manager.UpdateAsync(user);

then you go to the context

var ctx = store.context;

then

ctx.saveChanges();

wahooooooo...persisted :)

Hope this will help someone who pulled their hair for a few hours :P

Jquery to open Bootstrap v3 modal of remote url

So basically, in jquery what we can do is to load href attribute using the load function. This way we can use the url in <a> tag and load that in modal-body.

<a  href='/site/login' class='ls-modal'>Login</a>

//JS script
$('.ls-modal').on('click', function(e){
  e.preventDefault();
  $('#myModal').modal('show').find('.modal-body').load($(this).attr('href'));
});

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

Does the class org.apache.maven.shared.filtering.MavenFilteringException exist in file:/C:/Users/utopcu/.m2/repository/org/apache/maven/shared/maven-filtering/1.0-beta-2/maven-filtering-1.0-beta-2.jar?

The error message suggests that it doesn't. Maybe the JAR was corrupted somehow.

I'm also wondering where the version 1.0-beta-2 comes from; I have 1.0 on my disk. Try version 2.3 of the WAR plugin.

Interface type check with Typescript

I found an example from @progress/kendo-data-query in file filter-descriptor.interface.d.ts

Checker

declare const isCompositeFilterDescriptor: (source: FilterDescriptor | CompositeFilterDescriptor) => source is CompositeFilterDescriptor;

Example usage

const filters: Array<FilterDescriptor | CompositeFilterDescriptor> = filter.filters;

filters.forEach((element: FilterDescriptor | CompositeFilterDescriptor) => {
    if (isCompositeFilterDescriptor(element)) {
        // element type is CompositeFilterDescriptor
    } else {
        // element type is FilterDescriptor
    }
});

Escaping a forward slash in a regular expression

If you are using C#, you do not need to escape it.

How to avoid Sql Query Timeout

You could put an index on MemberType.

How can I generate an MD5 hash?

If you actually want the answer back as a string as opposed to a byte array, you could always do something like this:

String plaintext = "your text here";
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(plaintext.getBytes());
byte[] digest = m.digest();
BigInteger bigInt = new BigInteger(1,digest);
String hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while(hashtext.length() < 32 ){
  hashtext = "0"+hashtext;
}

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

What is the difference between an IntentService and a Service?

See Tejas Lagvankar's post about this subject. Below are some key differences between Service and IntentService and other components.

enter image description here

How to call execl() in C with the proper arguments?

If you need just to execute your VLC playback process and only give control back to your application process when it is done and nothing more complex, then i suppose you can use just:

system("The same thing you type into console");

Peak memory usage of a linux/unix process

Perhaps (gnu) time(1) already does what you want. For instance:

$ /usr/bin/time -f "%P %M" command
43% 821248

But other profiling tools may give more accurate results depending on what you are looking for.

How does Task<int> become an int?

Does an implicit conversion occur between Task<> and int?

Nope. This is just part of how async/await works.

Any method declared as async has to have a return type of:

  • void (avoid if possible)
  • Task (no result beyond notification of completion/failure)
  • Task<T> (for a logical result of type T in an async manner)

The compiler does all the appropriate wrapping. The point is that you're asynchronously returning urlContents.Length - you can't make the method just return int, as the actual method will return when it hits the first await expression which hasn't already completed. So instead, it returns a Task<int> which will complete when the async method itself completes.

Note that await does the opposite - it unwraps a Task<T> to a T value, which is how this line works:

string urlContents = await getStringTask;

... but of course it unwraps it asynchronously, whereas just using Result would block until the task had completed. (await can unwrap other types which implement the awaitable pattern, but Task<T> is the one you're likely to use most often.)

This dual wrapping/unwrapping is what allows async to be so composable. For example, I could write another async method which calls yours and doubles the result:

public async Task<int> AccessTheWebAndDoubleAsync()
{
    var task = AccessTheWebAsync();
    int result = await task;
    return result * 2;
}

(Or simply return await AccessTheWebAsync() * 2; of course.)

Google maps API V3 - multiple markers on exact same spot

How to get away with it.. [Swift]

    var clusterArray = [String]()
    var pinOffSet : Double = 0
    var pinLat = yourLat
    var pinLong = yourLong
    var location = pinLat + pinLong

A new marker is about to be created? check clusterArray and manipulate it's offset

 if(!clusterArray.contains(location)){
        clusterArray.append(location)
    } else {

        pinOffSet += 1
        let offWithIt = 0.00025 // reasonable offset with zoomLvl(14-16)
        switch pinOffSet {
        case 1 : pinLong = pinLong + offWithIt ; pinLat = pinLat + offWithIt
        case 2 : pinLong = pinLong + offWithIt ; pinLat = pinLat - offWithIt
        case 3 : pinLong = pinLong - offWithIt ; pinLat = pinLat - offWithIt
        case 4 : pinLong = pinLong - offWithIt ; pinLat = pinLat + offWithIt
        default : print(1)
        }


    }

result

enter image description here

What is a simple C or C++ TCP server and client example?

Although many year ago, clsocket seems a really nice small cross-platform (Windows, Linux, Mac OSX): https://github.com/DFHack/clsocket

How to sum a variable by group

Using aggregate:

aggregate(x$Frequency, by=list(Category=x$Category), FUN=sum)
  Category  x
1    First 30
2   Second  5
3    Third 34

In the example above, multiple dimensions can be specified in the list. Multiple aggregated metrics of the same data type can be incorporated via cbind:

aggregate(cbind(x$Frequency, x$Metric2, x$Metric3) ...

(embedding @thelatemail comment), aggregate has a formula interface too

aggregate(Frequency ~ Category, x, sum)

Or if you want to aggregate multiple columns, you could use the . notation (works for one column too)

aggregate(. ~ Category, x, sum)

or tapply:

tapply(x$Frequency, x$Category, FUN=sum)
 First Second  Third 
    30      5     34 

Using this data:

x <- data.frame(Category=factor(c("First", "First", "First", "Second",
                                      "Third", "Third", "Second")), 
                    Frequency=c(10,15,5,2,14,20,3))

Flask - Calling python function on button OnClick event

Easiest solution

<button type="button" onclick="window.location.href='{{ url_for( 'move_forward') }}';">Forward</button>

The transaction manager has disabled its support for remote/network transactions

I post the below solution here because after some searching this is where I landed, so other may too. I was trying to use EF 6 to call a stored procedure, but had a similar error because the stored procedure had a linked server being utilized.

The operation could not be performed because OLE DB provider _ for linked server _ was unable to begin a distributed transaction

The partner transaction manager has disabled its support for remote/network transactions*

Jumping over to SQL Client did fix my issue, which also confirmed for me that it was an EF thing.

EF model generated method based attempt:

db.SomeStoredProcedure();

ExecuteSqlCommand based attempt:

db.Database.ExecuteSqlCommand("exec [SomeDB].[dbo].[SomeStoredProcedure]");

With:

var connectionString = db.Database.Connection.ConnectionString;
var connection = new System.Data.SqlClient.SqlConnection(connectionString);    
var cmd = connection.CreateCommand();
cmd.CommandText = "exec [SomeDB].[dbo].[SomeStoredProcedure]";

connection.Open();
var result = cmd.ExecuteNonQuery();

That code can be shortened, but I think that version is slightly more convenient for debugging and stepping through.

I don't believe that Sql Client is necessarily a preferred choice, but I felt this was at least worth sharing if anyone else having similar problems gets landed here by google.

The above Code is C#, but the concept of trying to switch over to Sql Client still applies. At the very least it will be diagnostic to attempt to do so.

Creating a simple XML file using python

For such a simple XML structure, you may not want to involve a full blown XML module. Consider a string template for the simplest structures, or Jinja for something a little more complex. Jinja can handle looping over a list of data to produce the inner xml of your document list. That is a bit trickier with raw python string templates

For a Jinja example, see my answer to a similar question.

Here is an example of generating your xml with string templates.

import string
from xml.sax.saxutils import escape

inner_template = string.Template('    <field${id} name="${name}">${value}</field${id}>')

outer_template = string.Template("""<root>
 <doc>
${document_list}
 </doc>
</root>
 """)

data = [
    (1, 'foo', 'The value for the foo document'),
    (2, 'bar', 'The <value> for the <bar> document'),
]

inner_contents = [inner_template.substitute(id=id, name=name, value=escape(value)) for (id, name, value) in data]
result = outer_template.substitute(document_list='\n'.join(inner_contents))
print result

Output:

<root>
 <doc>
    <field1 name="foo">The value for the foo document</field1>
    <field2 name="bar">The &lt;value&gt; for the &lt;bar&gt; document</field2>
 </doc>
</root>

The downer of the template approach is that you won't get escaping of < and > for free. I danced around that problem by pulling in a util from xml.sax

Declaring abstract method in TypeScript

I believe that using a combination of interfaces and base classes could work for you. It will enforce behavioral requirements at compile time (rq_ post "below" refers to a post above, which is not this one).

The interface sets the behavioral API that isn't met by the base class. You will not be able to set base class methods to call on methods defined in the interface (because you will not be able to implement that interface in the base class without having to define those behaviors). Maybe someone can come up with a safe trick to allow calling of the interface methods in the parent.

You have to remember to extend and implement in the class you will instantiate. It satisfies concerns about defining runtime-fail code. You also won't even be able to call the methods that would puke if you haven't implemented the interface (such as if you try to instantiate the Animal class). I tried having the interface extend the BaseAnimal below, but it hid the constructor and the 'name' field of BaseAnimal from Snake. If I had been able to do that, the use of a module and exports could have prevented accidental direct instantiation of the BaseAnimal class.

Paste this in here to see if it works for you: http://www.typescriptlang.org/Playground/

// The behavioral interface also needs to extend base for substitutability
interface AbstractAnimal extends BaseAnimal {
    // encapsulates animal behaviors that must be implemented
    makeSound(input : string): string;
}

class BaseAnimal {
    constructor(public name) { }

    move(meters) {
        alert(this.name + " moved " + meters + "m.");
    }
}

// If concrete class doesn't extend both, it cannot use super methods.
class Snake extends BaseAnimal implements AbstractAnimal {
    constructor(name) { super(name); }
    makeSound(input : string): string {
        var utterance = "sssss"+input;
        alert(utterance);
        return utterance;
    }
    move() {
        alert("Slithering...");
        super.move(5);
    }
}

var longMover = new Snake("windy man");

longMover.makeSound("...am I nothing?");
longMover.move();

var fulture = new BaseAnimal("bob fossil");
// compile error on makeSound() because it is not defined.
// fulture.makeSound("you know, like a...")
fulture.move(1);

I came across FristvanCampen's answer as linked below. He says abstract classes are an anti-pattern, and suggests that one instantiate base 'abstract' classes using an injected instance of an implementing class. This is fair, but there are counter arguments made. Read for yourself: https://typescript.codeplex.com/discussions/449920

Part 2: I had another case where I wanted an abstract class, but I was prevented from using my solution above, because the defined methods in the "abstract class" needed to refer to the methods defined in the matching interface. So, I tool FristvanCampen's advice, sort of. I have the incomplete "abstract" class, with method implementations. I have the interface with the unimplemented methods; this interface extends the "abstract" class. I then have a class that extends the first and implements the second (it must extend both because the super constructor is inaccessible otherwise). See the (non-runnable) sample below:

export class OntologyConceptFilter extends FilterWidget.FilterWidget<ConceptGraph.Node, ConceptGraph.Link> implements FilterWidget.IFilterWidget<ConceptGraph.Node, ConceptGraph.Link> {

    subMenuTitle = "Ontologies Rendered"; // overload or overshadow?

    constructor(
        public conceptGraph: ConceptGraph.ConceptGraph,
        graphView: PathToRoot.ConceptPathsToRoot,
        implementation: FilterWidget.IFilterWidget<ConceptGraph.Node, ConceptGraph.Link>
        ){
        super(graphView);
        this.implementation = this;
    }
}

and

export class FilterWidget<N extends GraphView.BaseNode, L extends GraphView.BaseLink<GraphView.BaseNode>> {

    public implementation: IFilterWidget<N, L>

    filterContainer: JQuery;

    public subMenuTitle : string; // Given value in children

    constructor(
        public graphView: GraphView.GraphView<N, L>
        ){

    }

    doStuff(node: N){
        this.implementation.generateStuff(thing);
    }

}

export interface IFilterWidget<N extends GraphView.BaseNode, L extends GraphView.BaseLink<GraphView.BaseNode>> extends FilterWidget<N, L> {

    generateStuff(node: N): string;

}

How does PHP 'foreach' actually work?

foreach supports iteration over three different kinds of values:

In the following, I will try to explain precisely how iteration works in different cases. By far the simplest case is Traversable objects, as for these foreach is essentially only syntax sugar for code along these lines:

foreach ($it as $k => $v) { /* ... */ }

/* translates to: */

if ($it instanceof IteratorAggregate) {
    $it = $it->getIterator();
}
for ($it->rewind(); $it->valid(); $it->next()) {
    $v = $it->current();
    $k = $it->key();
    /* ... */
}

For internal classes, actual method calls are avoided by using an internal API that essentially just mirrors the Iterator interface on the C level.

Iteration of arrays and plain objects is significantly more complicated. First of all, it should be noted that in PHP "arrays" are really ordered dictionaries and they will be traversed according to this order (which matches the insertion order as long as you didn't use something like sort). This is opposed to iterating by the natural order of the keys (how lists in other languages often work) or having no defined order at all (how dictionaries in other languages often work).

The same also applies to objects, as the object properties can be seen as another (ordered) dictionary mapping property names to their values, plus some visibility handling. In the majority of cases, the object properties are not actually stored in this rather inefficient way. However, if you start iterating over an object, the packed representation that is normally used will be converted to a real dictionary. At that point, iteration of plain objects becomes very similar to iteration of arrays (which is why I'm not discussing plain-object iteration much in here).

So far, so good. Iterating over a dictionary can't be too hard, right? The problems begin when you realize that an array/object can change during iteration. There are multiple ways this can happen:

  • If you iterate by reference using foreach ($arr as &$v) then $arr is turned into a reference and you can change it during iteration.
  • In PHP 5 the same applies even if you iterate by value, but the array was a reference beforehand: $ref =& $arr; foreach ($ref as $v)
  • Objects have by-handle passing semantics, which for most practical purposes means that they behave like references. So objects can always be changed during iteration.

The problem with allowing modifications during iteration is the case where the element you are currently on is removed. Say you use a pointer to keep track of which array element you are currently at. If this element is now freed, you are left with a dangling pointer (usually resulting in a segfault).

There are different ways of solving this issue. PHP 5 and PHP 7 differ significantly in this regard and I'll describe both behaviors in the following. The summary is that PHP 5's approach was rather dumb and lead to all kinds of weird edge-case issues, while PHP 7's more involved approach results in more predictable and consistent behavior.

As a last preliminary, it should be noted that PHP uses reference counting and copy-on-write to manage memory. This means that if you "copy" a value, you actually just reuse the old value and increment its reference count (refcount). Only once you perform some kind of modification a real copy (called a "duplication") will be done. See You're being lied to for a more extensive introduction on this topic.

PHP 5

Internal array pointer and HashPointer

Arrays in PHP 5 have one dedicated "internal array pointer" (IAP), which properly supports modifications: Whenever an element is removed, there will be a check whether the IAP points to this element. If it does, it is advanced to the next element instead.

While foreach does make use of the IAP, there is an additional complication: There is only one IAP, but one array can be part of multiple foreach loops:

// Using by-ref iteration here to make sure that it's really
// the same array in both loops and not a copy
foreach ($arr as &$v1) {
    foreach ($arr as &$v) {
        // ...
    }
}

To support two simultaneous loops with only one internal array pointer, foreach performs the following shenanigans: Before the loop body is executed, foreach will back up a pointer to the current element and its hash into a per-foreach HashPointer. After the loop body runs, the IAP will be set back to this element if it still exists. If however the element has been removed, we'll just use wherever the IAP is currently at. This scheme mostly-kinda-sort of works, but there's a lot of weird behavior you can get out of it, some of which I'll demonstrate below.

Array duplication

The IAP is a visible feature of an array (exposed through the current family of functions), as such changes to the IAP count as modifications under copy-on-write semantics. This, unfortunately, means that foreach is in many cases forced to duplicate the array it is iterating over. The precise conditions are:

  1. The array is not a reference (is_ref=0). If it's a reference, then changes to it are supposed to propagate, so it should not be duplicated.
  2. The array has refcount>1. If refcount is 1, then the array is not shared and we're free to modify it directly.

If the array is not duplicated (is_ref=0, refcount=1), then only its refcount will be incremented (*). Additionally, if foreach by reference is used, then the (potentially duplicated) array will be turned into a reference.

Consider this code as an example where duplication occurs:

function iterate($arr) {
    foreach ($arr as $v) {}
}

$outerArr = [0, 1, 2, 3, 4];
iterate($outerArr);

Here, $arr will be duplicated to prevent IAP changes on $arr from leaking to $outerArr. In terms of the conditions above, the array is not a reference (is_ref=0) and is used in two places (refcount=2). This requirement is unfortunate and an artifact of the suboptimal implementation (there is no concern of modification during iteration here, so we don't really need to use the IAP in the first place).

(*) Incrementing the refcount here sounds innocuous, but violates copy-on-write (COW) semantics: This means that we are going to modify the IAP of a refcount=2 array, while COW dictates that modifications can only be performed on refcount=1 values. This violation results in user-visible behavior change (while a COW is normally transparent) because the IAP change on the iterated array will be observable -- but only until the first non-IAP modification on the array. Instead, the three "valid" options would have been a) to always duplicate, b) do not increment the refcount and thus allowing the iterated array to be arbitrarily modified in the loop or c) don't use the IAP at all (the PHP 7 solution).

Position advancement order

There is one last implementation detail that you have to be aware of to properly understand the code samples below. The "normal" way of looping through some data structure would look something like this in pseudocode:

reset(arr);
while (get_current_data(arr, &data) == SUCCESS) {
    code();
    move_forward(arr);
}

However foreach, being a rather special snowflake, chooses to do things slightly differently:

reset(arr);
while (get_current_data(arr, &data) == SUCCESS) {
    move_forward(arr);
    code();
}

Namely, the array pointer is already moved forward before the loop body runs. This means that while the loop body is working on element $i, the IAP is already at element $i+1. This is the reason why code samples showing modification during iteration will always unset the next element, rather than the current one.

Examples: Your test cases

The three aspects described above should provide you with a mostly complete impression of the idiosyncrasies of the foreach implementation and we can move on to discuss some examples.

The behavior of your test cases is simple to explain at this point:

  • In test cases 1 and 2 $array starts off with refcount=1, so it will not be duplicated by foreach: Only the refcount is incremented. When the loop body subsequently modifies the array (which has refcount=2 at that point), the duplication will occur at that point. Foreach will continue working on an unmodified copy of $array.

  • In test case 3, once again the array is not duplicated, thus foreach will be modifying the IAP of the $array variable. At the end of the iteration, the IAP is NULL (meaning iteration has done), which each indicates by returning false.

  • In test cases 4 and 5 both each and reset are by-reference functions. The $array has a refcount=2 when it is passed to them, so it has to be duplicated. As such foreach will be working on a separate array again.

Examples: Effects of current in foreach

A good way to show the various duplication behaviors is to observe the behavior of the current() function inside a foreach loop. Consider this example:

foreach ($array as $val) {
    var_dump(current($array));
}
/* Output: 2 2 2 2 2 */

Here you should know that current() is a by-ref function (actually: prefer-ref), even though it does not modify the array. It has to be in order to play nice with all the other functions like next which are all by-ref. By-reference passing implies that the array has to be separated and thus $array and the foreach-array will be different. The reason you get 2 instead of 1 is also mentioned above: foreach advances the array pointer before running the user code, not after. So even though the code is at the first element, foreach already advanced the pointer to the second.

Now lets try a small modification:

$ref = &$array;
foreach ($array as $val) {
    var_dump(current($array));
}
/* Output: 2 3 4 5 false */

Here we have the is_ref=1 case, so the array is not copied (just like above). But now that it is a reference, the array no longer has to be duplicated when passing to the by-ref current() function. Thus current() and foreach work on the same array. You still see the off-by-one behavior though, due to the way foreach advances the pointer.

You get the same behavior when doing by-ref iteration:

foreach ($array as &$val) {
    var_dump(current($array));
}
/* Output: 2 3 4 5 false */

Here the important part is that foreach will make $array an is_ref=1 when it is iterated by reference, so basically you have the same situation as above.

Another small variation, this time we'll assign the array to another variable:

$foo = $array;
foreach ($array as $val) {
    var_dump(current($array));
}
/* Output: 1 1 1 1 1 */

Here the refcount of the $array is 2 when the loop is started, so for once we actually have to do the duplication upfront. Thus $array and the array used by foreach will be completely separate from the outset. That's why you get the position of the IAP wherever it was before the loop (in this case it was at the first position).

Examples: Modification during iteration

Trying to account for modifications during iteration is where all our foreach troubles originated, so it serves to consider some examples for this case.

Consider these nested loops over the same array (where by-ref iteration is used to make sure it really is the same one):

foreach ($array as &$v1) {
    foreach ($array as &$v2) {
        if ($v1 == 1 && $v2 == 1) {
            unset($array[1]);
        }
        echo "($v1, $v2)\n";
    }
}

// Output: (1, 1) (1, 3) (1, 4) (1, 5)

The expected part here is that (1, 2) is missing from the output because element 1 was removed. What's probably unexpected is that the outer loop stops after the first element. Why is that?

The reason behind this is the nested-loop hack described above: Before the loop body runs, the current IAP position and hash is backed up into a HashPointer. After the loop body it will be restored, but only if the element still exists, otherwise the current IAP position (whatever it may be) is used instead. In the example above this is exactly the case: The current element of the outer loop has been removed, so it will use the IAP, which has already been marked as finished by the inner loop!

Another consequence of the HashPointer backup+restore mechanism is that changes to the IAP through reset() etc. usually do not impact foreach. For example, the following code executes as if the reset() were not present at all:

$array = [1, 2, 3, 4, 5];
foreach ($array as &$value) {
    var_dump($value);
    reset($array);
}
// output: 1, 2, 3, 4, 5

The reason is that, while reset() temporarily modifies the IAP, it will be restored to the current foreach element after the loop body. To force reset() to make an effect on the loop, you have to additionally remove the current element, so that the backup/restore mechanism fails:

$array = [1, 2, 3, 4, 5];
$ref =& $array;
foreach ($array as $value) {
    var_dump($value);
    unset($array[1]);
    reset($array);
}
// output: 1, 1, 3, 4, 5

But, those examples are still sane. The real fun starts if you remember that the HashPointer restore uses a pointer to the element and its hash to determine whether it still exists. But: Hashes have collisions, and pointers can be reused! This means that, with a careful choice of array keys, we can make foreach believe that an element that has been removed still exists, so it will jump directly to it. An example:

$array = ['EzEz' => 1, 'EzFY' => 2, 'FYEz' => 3];
$ref =& $array;
foreach ($array as $value) {
    unset($array['EzFY']);
    $array['FYFY'] = 4;
    reset($array);
    var_dump($value);
}
// output: 1, 4

Here we should normally expect the output 1, 1, 3, 4 according to the previous rules. How what happens is that 'FYFY' has the same hash as the removed element 'EzFY', and the allocator happens to reuse the same memory location to store the element. So foreach ends up directly jumping to the newly inserted element, thus short-cutting the loop.

Substituting the iterated entity during the loop

One last odd case that I'd like to mention, it is that PHP allows you to substitute the iterated entity during the loop. So you can start iterating on one array and then replace it with another array halfway through. Or start iterating on an array and then replace it with an object:

$arr = [1, 2, 3, 4, 5];
$obj = (object) [6, 7, 8, 9, 10];

$ref =& $arr;
foreach ($ref as $val) {
    echo "$val\n";
    if ($val == 3) {
        $ref = $obj;
    }
}
/* Output: 1 2 3 6 7 8 9 10 */

As you can see in this case PHP will just start iterating the other entity from the start once the substitution has happened.

PHP 7

Hashtable iterators

If you still remember, the main problem with array iteration was how to handle removal of elements mid-iteration. PHP 5 used a single internal array pointer (IAP) for this purpose, which was somewhat suboptimal, as one array pointer had to be stretched to support multiple simultaneous foreach loops and interaction with reset() etc. on top of that.

PHP 7 uses a different approach, namely, it supports creating an arbitrary amount of external, safe hashtable iterators. These iterators have to be registered in the array, from which point on they have the same semantics as the IAP: If an array element is removed, all hashtable iterators pointing to that element will be advanced to the next element.

This means that foreach will no longer use the IAP at all. The foreach loop will be absolutely no effect on the results of current() etc. and its own behavior will never be influenced by functions like reset() etc.

Array duplication

Another important change between PHP 5 and PHP 7 relates to array duplication. Now that the IAP is no longer used, by-value array iteration will only do a refcount increment (instead of duplication the array) in all cases. If the array is modified during the foreach loop, at that point a duplication will occur (according to copy-on-write) and foreach will keep working on the old array.

In most cases, this change is transparent and has no other effect than better performance. However, there is one occasion where it results in different behavior, namely the case where the array was a reference beforehand:

$array = [1, 2, 3, 4, 5];
$ref = &$array;
foreach ($array as $val) {
    var_dump($val);
    $array[2] = 0;
}
/* Old output: 1, 2, 0, 4, 5 */
/* New output: 1, 2, 3, 4, 5 */

Previously by-value iteration of reference-arrays was special cases. In this case, no duplication occurred, so all modifications of the array during iteration would be reflected by the loop. In PHP 7 this special case is gone: A by-value iteration of an array will always keep working on the original elements, disregarding any modifications during the loop.

This, of course, does not apply to by-reference iteration. If you iterate by-reference all modifications will be reflected by the loop. Interestingly, the same is true for by-value iteration of plain objects:

$obj = new stdClass;
$obj->foo = 1;
$obj->bar = 2;
foreach ($obj as $val) {
    var_dump($val);
    $obj->bar = 42;
}
/* Old and new output: 1, 42 */

This reflects the by-handle semantics of objects (i.e. they behave reference-like even in by-value contexts).

Examples

Let's consider a few examples, starting with your test cases:

  • Test cases 1 and 2 retain the same output: By-value array iteration always keep working on the original elements. (In this case, even refcounting and duplication behavior is exactly the same between PHP 5 and PHP 7).

  • Test case 3 changes: Foreach no longer uses the IAP, so each() is not affected by the loop. It will have the same output before and after.

  • Test cases 4 and 5 stay the same: each() and reset() will duplicate the array before changing the IAP, while foreach still uses the original array. (Not that the IAP change would have mattered, even if the array was shared.)

The second set of examples was related to the behavior of current() under different reference/refcounting configurations. This no longer makes sense, as current() is completely unaffected by the loop, so its return value always stays the same.

However, we get some interesting changes when considering modifications during iteration. I hope you will find the new behavior saner. The first example:

$array = [1, 2, 3, 4, 5];
foreach ($array as &$v1) {
    foreach ($array as &$v2) {
        if ($v1 == 1 && $v2 == 1) {
            unset($array[1]);
        }
        echo "($v1, $v2)\n";
    }
}

// Old output: (1, 1) (1, 3) (1, 4) (1, 5)
// New output: (1, 1) (1, 3) (1, 4) (1, 5)
//             (3, 1) (3, 3) (3, 4) (3, 5)
//             (4, 1) (4, 3) (4, 4) (4, 5)
//             (5, 1) (5, 3) (5, 4) (5, 5) 

As you can see, the outer loop no longer aborts after the first iteration. The reason is that both loops now have entirely separate hashtable iterators, and there is no longer any cross-contamination of both loops through a shared IAP.

Another weird edge case that is fixed now, is the odd effect you get when you remove and add elements that happen to have the same hash:

$array = ['EzEz' => 1, 'EzFY' => 2, 'FYEz' => 3];
foreach ($array as &$value) {
    unset($array['EzFY']);
    $array['FYFY'] = 4;
    var_dump($value);
}
// Old output: 1, 4
// New output: 1, 3, 4

Previously the HashPointer restore mechanism jumped right to the new element because it "looked" like it's the same as the removed element (due to colliding hash and pointer). As we no longer rely on the element hash for anything, this is no longer an issue.

How can I check if string contains characters & whitespace, not just whitespace?

if (!myString.replace(/^\s+|\s+$/g,""))
  alert('string is only whitespace');

String comparison technique used by Python

From the docs:

The comparison uses lexicographical ordering: first the first two items are compared, and if they differ this determines the outcome of the comparison; if they are equal, the next two items are compared, and so on, until either sequence is exhausted.

Also:

Lexicographical ordering for strings uses the Unicode code point number to order individual characters.

or on Python 2:

Lexicographical ordering for strings uses the ASCII ordering for individual characters.

As an example:

>>> 'abc' > 'bac'
False
>>> ord('a'), ord('b')
(97, 98)

The result False is returned as soon as a is found to be less than b. The further items are not compared (as you can see for the second items: b > a is True).

Be aware of lower and uppercase:

>>> [(x, ord(x)) for x in abc]
[('a', 97), ('b', 98), ('c', 99), ('d', 100), ('e', 101), ('f', 102), ('g', 103), ('h', 104), ('i', 105), ('j', 106), ('k', 107), ('l', 108), ('m', 109), ('n', 110), ('o', 111), ('p', 112), ('q', 113), ('r', 114), ('s', 115), ('t', 116), ('u', 117), ('v', 118), ('w', 119), ('x', 120), ('y', 121), ('z', 122)]
>>> [(x, ord(x)) for x in abc.upper()]
[('A', 65), ('B', 66), ('C', 67), ('D', 68), ('E', 69), ('F', 70), ('G', 71), ('H', 72), ('I', 73), ('J', 74), ('K', 75), ('L', 76), ('M', 77), ('N', 78), ('O', 79), ('P', 80), ('Q', 81), ('R', 82), ('S', 83), ('T', 84), ('U', 85), ('V', 86), ('W', 87), ('X', 88), ('Y', 89), ('Z', 90)]

Is there a way to get version from package.json in nodejs code?

Using ES6 modules you can do the following:

import {version} from './package.json';

Best way to generate xml?

Use lxml.builder class, from: http://lxml.de/tutorial.html#the-e-factory

import lxml.builder as lb
from lxml import etree

nstext = "new story"
story = lb.E.Asset(
  lb.E.Attribute(nstext, name="Name", act="set"),
  lb.E.Relation(lb.E.Asset(idref="Scope:767"),
            name="Scope", act="set")
  )

print 'story:\n', etree.tostring(story, pretty_print=True)

Output:

story:
<Asset>
  <Attribute name="Name" act="set">new story</Attribute>
  <Relation name="Scope" act="set">
    <Asset idref="Scope:767"/>
  </Relation>
</Asset>

Giving multiple URL patterns to Servlet Filter

In case you are using the annotation method for filter definition (as opposed to defining them in the web.xml), you can do so by just putting an array of mappings in the @WebFilter annotation:

/**
 * Filter implementation class LoginFilter
 */
@WebFilter(urlPatterns = { "/faces/Html/Employee","/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginFilter implements Filter {
    ...

And just as an FYI, this same thing works for servlets using the servlet annotation too:

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet({"/faces/Html/Employee", "/faces/Html/Admin", "/faces/Html/Supervisor"})
public class LoginServlet extends HttpServlet {
    ...

Right click to select a row in a Datagridview and show a menu to delete it

It is work for me without any errors:

this.dataGridView2.MouseDown += new System.Windows.Forms.MouseEventHandler(this.MyDataGridView_MouseDown); 
this.dataGridView2.Click += new System.EventHandler(this.DeleteRow_Click);

And this

private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
    if (e.Button == MouseButtons.Right)
    {
        var hti = dataGridView2.HitTest(e.X, e.Y);
        dataGridView2.ClearSelection();
        dataGridView2.Rows[hti.RowIndex].Selected = true;
    }

}


private void DeleteRow_Click(object sender, EventArgs e)
{
    Int32 rowToDelete = dataGridView2.Rows.GetFirstRow(DataGridViewElementStates.Selected);
    if (rowToDelete == -1) { }
    else 
    {
        dataGridView2.Rows.RemoveAt(rowToDelete);
        dataGridView2.ClearSelection();
    }
}

how to fetch array keys with jQuery?

Don't Reinvent the Wheel, Use Underscore

I know the OP specifically mentioned jQuery but I wanted to put an answer here to introduce people to the helpful Underscore library if they are not aware of it already.

By leveraging the keys method in the Underscore library, you can simply do the following:

_.keys(foo)  #=> ["alfa", "beta"]

Plus, there's a plethora of other useful functions that are worth perusing.

Django Model() vs Model.objects.create()

The differences between Model() and Model.objects.create() are the following:


  1. INSERT vs UPDATE

    Model.save() does either INSERT or UPDATE of an object in a DB, while Model.objects.create() does only INSERT.

    Model.save() does

    • UPDATE If the object’s primary key attribute is set to a value that evaluates to True

    • INSERT If the object’s primary key attribute is not set or if the UPDATE didn’t update anything (e.g. if primary key is set to a value that doesn’t exist in the database).


  1. Existing primary key

    If primary key attribute is set to a value and such primary key already exists, then Model.save() performs UPDATE, but Model.objects.create() raises IntegrityError.

    Consider the following models.py:

    class Subject(models.Model):
       subject_id = models.PositiveIntegerField(primary_key=True, db_column='subject_id')
       name = models.CharField(max_length=255)
       max_marks = models.PositiveIntegerField()
    
    1. Insert/Update to db with Model.save()

      physics = Subject(subject_id=1, name='Physics', max_marks=100)
      physics.save()
      math = Subject(subject_id=1, name='Math', max_marks=50)  # Case of update
      math.save()
      

      Result:

      Subject.objects.all().values()
      <QuerySet [{'subject_id': 1, 'name': 'Math', 'max_marks': 50}]>
      
    2. Insert to db with Model.objects.create()

      Subject.objects.create(subject_id=1, name='Chemistry', max_marks=100)
      IntegrityError: UNIQUE constraint failed: m****t.subject_id
      

    Explanation: In the example, math.save() does an UPDATE (changes name from Physics to Math, and max_marks from 100 to 50), because subject_id is a primary key and subject_id=1 already exists in the DB. But Subject.objects.create() raises IntegrityError, because, again the primary key subject_id with the value 1 already exists.


  1. Forced insert

    Model.save() can be made to behave as Model.objects.create() by using force_insert=True parameter: Model.save(force_insert=True).


  1. Return value

    Model.save() return None where Model.objects.create() return model instance i.e. package_name.models.Model


Conclusion: Model.objects.create() does model initialization and performs save() with force_insert=True.

Excerpt from the source code of Model.objects.create()

def create(self, **kwargs):
    """
    Create a new object with the given kwargs, saving it to the database
    and returning the created object.
    """
    obj = self.model(**kwargs)
    self._for_write = True
    obj.save(force_insert=True, using=self.db)
    return obj

For more details follow the links:

  1. https://docs.djangoproject.com/en/stable/ref/models/querysets/#create

  2. https://github.com/django/django/blob/2d8dcba03aae200aaa103ec1e69f0a0038ec2f85/django/db/models/query.py#L440

How to completely uninstall kubernetes

In my "Ubuntu 16.04", I use next steps to completely remove and clean Kubernetes (installed with "apt-get"):

kubeadm reset
sudo apt-get purge kubeadm kubectl kubelet kubernetes-cni kube*   
sudo apt-get autoremove  
sudo rm -rf ~/.kube

And restart the computer.

Change values on matplotlib imshow() graph axis

I would try to avoid changing the xticklabels if possible, otherwise it can get very confusing if you for example overplot your histogram with additional data.

Defining the range of your grid is probably the best and with imshow it can be done by adding the extent keyword. This way the axes gets adjusted automatically. If you want to change the labels i would use set_xticks with perhaps some formatter. Altering the labels directly should be the last resort.

fig, ax = plt.subplots(figsize=(6,6))

ax.imshow(hist, cmap=plt.cm.Reds, interpolation='none', extent=[80,120,32,0])
ax.set_aspect(2) # you may also use am.imshow(..., aspect="auto") to restore the aspect ratio

enter image description here

how to access downloads folder in android?

For your first question try

Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); 

(available since API 8)

To access individual files in this directory use either File.list() or File.listFiles(). Seems that reporting download progress is only possible in notification, see here.

How to Consolidate Data from Multiple Excel Columns All into One Column

Take a look at Blockspring - you do need to install the plugin, but then it's just another function you call like this:

=BLOCKSPRING("twodee-array-reduce","input_array",D5:F7)

The source code and other details are here. If this doesn't suit and/or you want to build off my solution, you can fork my function (Python) or use another supported scripting language (Ruby, R, JS, etc...).

How to convert HH:mm:ss.SSS to milliseconds?

If you want to use SimpleDateFormat, you could write:

private final SimpleDateFormat sdf =
    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
    { sdf.setTimeZone(TimeZone.getTimeZone("GMT")); }

private long parseTimeToMillis(final String time) throws ParseException
    { return sdf.parse("1970-01-01 " + time).getTime(); }

But a custom method would be much more efficient. SimpleDateFormat, because of all its calendar support, time-zone support, daylight-savings-time support, and so on, is pretty slow. The slowness is worth it if you actually need some of those features, but since you don't, it might not be. (It depends how often you're calling this method, and whether efficiency is a concern for your application.)

Also, SimpleDateFormat is non-thread-safe, which is sometimes a pain. (Without knowing anything about your application, I can't guess whether that matters.)

Personally, I'd probably write a custom method.

How do I add a new sourceset to Gradle?

I'm new to Gradle, using Gradle 6.0.1 JUnit 4.12. Here's what I came up with to solve this problem.

apply plugin: 'java'
repositories { jcenter() }

dependencies {
    testImplementation 'junit:junit:4.12'
}

sourceSets {
  main {
    java {
       srcDirs = ['src']
    }
  }
  test {
    java {
      srcDirs = ['tests']
    }
  }
}

Notice that the main source and test source is referenced separately, one under main and one under test.

The testImplementation item under dependencies is only used for compiling the source in test. If your main code actually had a dependency on JUnit, then you would also specify implementation under dependencies.

I had to specify the repositories section to get this to work, I doubt that is the best/only way.

Excel Create Collapsible Indented Row Hierarchies

Create a Pivot Table. It has these features and many more.

If you are dead-set on doing this yourself then you could add shapes to the worksheet and use VBA to hide and unhide rows and columns on clicking the shapes.

How to split an integer into an array of digits?

Another solution that does not involve converting to/from strings:

from math import log10

def decompose(n):
    if n == 0:
        return [0]
    b = int(log10(n)) + 1
    return [(n // (10 ** i)) % 10 for i in reversed(range(b))]

SQL select everything in an array

SELECT * FROM products WHERE catid IN ('1', '2', '3', '4')

How to clear the Entry widget after a button is pressed in Tkinter?

real gets the value ent.get() which is just a string. It has no idea where it came from, and no way to affect the widget.

Instead of real.delete(), call .delete() on the entry widget itself:

def res(ent, real, secret):
    if secret == eval(real):
        showinfo(message='that is right!')
    ent.delete(0, END)

def guess():
    ...
    btn = Button(ge, text="Enter", command=lambda: res(ent, ent.get(), secret))

Xcode error "Could not find Developer Disk Image"

If you have iOS 9.1 on your phone, just download Xcode 7.1 beta instead of using GM.

See Apple's response: Could not find developer disk image for iOS 9.1

Difference between 'cls' and 'self' in Python classes?

The distinction between "self" and "cls" is defined in PEP 8 . As Adrien said, this is not a mandatory. It's a coding style. PEP 8 says:

Function and method arguments:

Always use self for the first argument to instance methods.

Always use cls for the first argument to class methods.

Auto insert date and time in form input field?

Javascript won't execute within a value attribute. You could do something like this, though:

<input id="date" name="date">

<script type="text/javascript">
  document.getElementById('date').value = Date();
</script>

You'd probably want to format the date as you prefer, because the default output of Date() looks something like: Tue Jun 16 2009 10:47:10 GMT-0400 (Eastern Daylight Time). See this SO question for info about formatting a date.

Python List & for-each access (Find/Replace in built-in list)

Python is not Java, nor C/C++ -- you need to stop thinking that way to really utilize the power of Python.

Python does not have pass-by-value, nor pass-by-reference, but instead uses pass-by-name (or pass-by-object) -- in other words, nearly everything is bound to a name that you can then use (the two obvious exceptions being tuple- and list-indexing).

When you do spam = "green", you have bound the name spam to the string object "green"; if you then do eggs = spam you have not copied anything, you have not made reference pointers; you have simply bound another name, eggs, to the same object ("green" in this case). If you then bind spam to something else (spam = 3.14159) eggs will still be bound to "green".

When a for-loop executes, it takes the name you give it, and binds it in turn to each object in the iterable while running the loop; when you call a function, it takes the names in the function header and binds them to the arguments passed; reassigning a name is actually rebinding a name (it can take a while to absorb this -- it did for me, anyway).

With for-loops utilizing lists, there are two basic ways to assign back to the list:

for i, item in enumerate(some_list):
    some_list[i] = process(item)

or

new_list = []
for item in some_list:
    new_list.append(process(item))
some_list[:] = new_list

Notice the [:] on that last some_list -- it is causing a mutation of some_list's elements (setting the entire thing to new_list's elements) instead of rebinding the name some_list to new_list. Is this important? It depends! If you have other names besides some_list bound to the same list object, and you want them to see the updates, then you need to use the slicing method; if you don't, or if you do not want them to see the updates, then rebind -- some_list = new_list.

How to make a launcher

They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.

File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish

But if you do not have samples loaded, then download it using the below steps

Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install

Line break in HTML with '\n'

You can use CSS white-space property for \n. You can also preserve the tabs as in \t.

For line break \n:

white-space: pre-line;

For line break \n and tabs \t:

white-space: pre-wrap;

_x000D_
_x000D_
document.getElementById('just-line-break').innerHTML = 'Testing 1\nTesting 2\n\tNo tab';_x000D_
_x000D_
document.getElementById('line-break-and-tab').innerHTML = 'Testing 1\nTesting 2\n\tWith tab';
_x000D_
#just-line-break {_x000D_
  white-space: pre-line;_x000D_
}_x000D_
_x000D_
#line-break-and-tab {_x000D_
  white-space: pre-wrap;_x000D_
}
_x000D_
<div id="just-line-break"></div>_x000D_
_x000D_
<br/>_x000D_
_x000D_
<div id="line-break-and-tab"></div>
_x000D_
_x000D_
_x000D_

Best practices for SQL varchar column length

In a sense you're right, although anything lower than 2^8 characters will still register as a byte of data.

If you account for the base character that leaves anything with a VARCHAR < 255 as consuming the same amount of space.

255 is a good baseline definition unless you particularly wish to curtail excessive input.

How do you add UI inside cells in a google spreadsheet using app script?

The apps UI only works for panels.

The best you can do is to draw a button yourself and put that into your spreadsheet. Than you can add a macro to it.

Go into "Insert > Drawing...", Draw a button and add it to the spreadsheet. Than click it and click "assign Macro...", then insert the name of the function you wish to execute there. The function must be defined in a script in the spreadsheet.

Alternatively you can also draw the button somewhere else and insert it as an image.

More info: https://developers.google.com/apps-script/guides/menus

enter image description here enter image description here enter image description here

Check that a input to UITextField is numeric only

Accept decimal values in text fields with single (.)dot working with iPad and iPhone in Swift 3

 func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        let inverseSet = NSCharacterSet(charactersIn:"0123456789").inverted

        let components = string.components(separatedBy: inverseSet)

        let filtered = components.joined(separator: "")

        if filtered == string {
            return true
        } else {
            if string == "." {
                let countdots = textField.text!.components(separatedBy:".").count - 1
                if countdots == 0 {
                    return true
                }else{
                    if countdots > 0 && string == "." {
                        return false
                    } else {
                        return true
                    }
                }
            }else{
                return false
            }
        }
    }

$watch'ing for data changes in an Angular directive

You need to enable deep object dirty checking. By default angular only checks the reference of the top level variable that you watch.

App.directive('d3Visualization', function() {
    return {
        restrict: 'E',
        scope: {
            val: '='
        },
        link: function(scope, element, attrs) {
            scope.$watch('val', function(newValue, oldValue) {
                if (newValue)
                    console.log("I see a data change!");
            }, true);
        }
    }
});

see Scope. The third parameter of the $watch function enables deep dirty checking if it's set to true.

Take note that deep dirty checking is expensive. So if you just need to watch the children array instead of the whole data variable the watch the variable directly.

scope.$watch('val.children', function(newValue, oldValue) {}, true);

version 1.2.x introduced $watchCollection

Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties)

scope.$watchCollection('val.children', function(newValue, oldValue) {});

Java - JPA - @Version annotation

Although @Pascal answer is perfectly valid, from my experience I find the code below helpful to accomplish optimistic locking:

@Entity
public class MyEntity implements Serializable {    
    // ...

    @Version
    @Column(name = "optlock", columnDefinition = "integer DEFAULT 0", nullable = false)
    private long version = 0L;

    // ...
}

Why? Because:

  1. Optimistic locking won't work if field annotated with @Version is accidentally set to null.
  2. As this special field isn't necessarily a business version of the object, to avoid a misleading, I prefer to name such field to something like optlock rather than version.

First point doesn't matter if application uses only JPA for inserting data into the database, as JPA vendor will enforce 0 for @version field at creation time. But almost always plain SQL statements are also in use (at least during unit and integration testing).

Replace duplicate spaces with a single space in T-SQL

Please Find below code

select trim(string_agg(value,' ')) from STRING_SPLIT('  single    spaces   only  ',' ')
where value<>' '

This worked for me.. Hope this helps...

How can I use getSystemService in a non-activity class (LocationManager)?

One way I have gotten around this is by create a static class for instances. I used it a lot in AS3 I has worked great for me in android development too.

Config.java

public final class Config {
    public static MyApp context = null;
}

MyApp.java

public class MyApp extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Config.context = this;
    }
    ...
}

You can then access the context or by using Config.context

LocationManager locationManager;
String context = Context.LOCATION_SERVICE;
locationManager = Config.context.getSystemService(context);

Create comma separated strings C#?

Another approach is to use the CommaDelimitedStringCollection class from System.Configuration namespace/assembly. It behaves like a list plus it has an overriden ToString method that returns a comma-separated string.

Pros - More flexible than an array.

Cons - You can't pass a string containing a comma.

CommaDelimitedStringCollection list = new CommaDelimitedStringCollection();

list.AddRange(new string[] { "Huey", "Dewey" });
list.Add("Louie");
//list.Add(",");

string s = list.ToString(); //Huey,Dewey,Louie

How to style a checkbox using CSS

input[type=checkbox].css-checkbox {
    position: absolute;
    overflow: hidden;
    clip: rect(0 0 0 0);
    height: 1px;
    width: 1px;
    margin: -1px;
    padding: 0;
    border: 0;
}

input[type=checkbox].css-checkbox + label.css-label {
    padding-left: 20px;
    height: 15px;
    display: inline-block;
    line-height: 15px;
    background-repeat: no-repeat;
    background-position: 0 0;
    font-size: 15px;
    vertical-align: middle;
    cursor: pointer;
}

input[type=checkbox].css-checkbox:checked + label.css-label {
    background-position: 0 -15px;
}

.css-label{
    background-image:url(http://csscheckbox.com/checkboxes/dark-check-green.png);
}

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

Try Restarting the editor in which you are writing the code(VS code or Sublime). Compile and Run it again. I have done the same and it worked.

This happens when you add a new class outside from your editor or keep running your angular cli 'ng serve'. Actually your editor or the 'ng serve' command may not able to find the newly created files.

How to redirect the output of the time command to a file in Linux?

If you want just the time in a shell variable then this works:

var=`{ time <command> ; } 2>&1 1>/dev/null`

Simple Android RecyclerView example

Here's a much newer Kotlin solution for this which is much simpler than many of the answers written here, it uses anonymous class.

val items = mutableListOf<String>()

inner class ItemHolder(view: View): RecyclerView.ViewHolder(view) {
    var textField: TextView = view.findViewById(android.R.id.text1) as TextView
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    rvitems.layoutManager = LinearLayoutManager(context)
    rvitems.adapter = object : RecyclerView.Adapter<ItemHolder>() {

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemHolder {
            return ItemHolder(LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_1, parent, false))
        }

        override fun getItemCount(): Int {
            return items.size
        }

        override fun onBindViewHolder(holder: ItemHolder, position: Int) {
            holder.textField.text = items[position]
            holder.textField.setOnClickListener {
                Toast.makeText(context, "Clicked $position", Toast.LENGTH_SHORT).show()
            }
        }
    }
}

I took the liberty to use android.R.layout.simple_list_item_1 as it's simpler. I wanted to simplify it even further and put ItemHolder as an inner class but couldn't quite figure out how to reference it in a type in the outer class parameter.

How do I execute a file in Cygwin?

Apparently, gcc doesn't behave like the one described in The C Programming language, where it says that the command cc helloworld.c produces a file called a.out which can be run by typing a.out on the prompt.

A Unix hasn't behaved in that way by default (so you can just write the executable name without ./ at the front) in a long time. It's called a.exe, because else Windows won't execute it, as it gets file types from the extension.

Checking for empty or null JToken in a JObject

You can proceed as follows to check whether a JToken Value is null

JToken token = jObject["key"];

if(token.Type == JTokenType.Null)
{
    // Do your logic
}

Func vs. Action vs. Predicate

The difference between Func and Action is simply whether you want the delegate to return a value (use Func) or not (use Action).

Func is probably most commonly used in LINQ - for example in projections:

 list.Select(x => x.SomeProperty)

or filtering:

 list.Where(x => x.SomeValue == someOtherValue)

or key selection:

 list.Join(otherList, x => x.FirstKey, y => y.SecondKey, ...)

Action is more commonly used for things like List<T>.ForEach: execute the given action for each item in the list. I use this less often than Func, although I do sometimes use the parameterless version for things like Control.BeginInvoke and Dispatcher.BeginInvoke.

Predicate is just a special cased Func<T, bool> really, introduced before all of the Func and most of the Action delegates came along. I suspect that if we'd already had Func and Action in their various guises, Predicate wouldn't have been introduced... although it does impart a certain meaning to the use of the delegate, whereas Func and Action are used for widely disparate purposes.

Predicate is mostly used in List<T> for methods like FindAll and RemoveAll.

List files ONLY in the current directory

You can use os.listdir for this purpose. If you only want files and not directories, you can filter the results using os.path.isfile.

example:

files = os.listdir(os.curdir)  #files and directories

or

files = filter(os.path.isfile, os.listdir( os.curdir ) )  # files only
files = [ f for f in os.listdir( os.curdir ) if os.path.isfile(f) ] #list comprehension version.

How to create a GUID/UUID using iOS

In Swift 3.0

var uuid = UUID().uuidString

Java: convert List<String> to a String

With Java 8 you can do this without any third party library.

If you want to join a Collection of Strings you can use the new String.join() method:

List<String> list = Arrays.asList("foo", "bar", "baz");
String joined = String.join(" and ", list); // "foo and bar and baz"

If you have a Collection with another type than String you can use the Stream API with the joining Collector:

List<Person> list = Arrays.asList(
  new Person("John", "Smith"),
  new Person("Anna", "Martinez"),
  new Person("Paul", "Watson ")
);

String joinedFirstNames = list.stream()
  .map(Person::getFirstName)
  .collect(Collectors.joining(", ")); // "John, Anna, Paul"

The StringJoiner class may also be useful.

A method to count occurrences in a list

You can do something like this to count from a list of things.

IList<String> names = new List<string>() { "ToString", "Format" };
IEnumerable<String> methodNames = typeof(String).GetMethods().Select(x => x.Name);

int count = methodNames.Where(x => names.Contains(x)).Count();

To count a single element

string occur = "Test1";
IList<String> words = new List<string>() {"Test1","Test2","Test3","Test1"};

int count = words.Where(x => x.Equals(occur)).Count();

Android ACTION_IMAGE_CAPTURE Intent

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_CANCELED)
    {
        //do not process data, I use return; to resume activity calling camera intent
        enter code here
    }
}

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

You might consider using double slashes on your directory e.g

_x000D_
_x000D_
app.get('/',(req,res)=>{_x000D_
    res.sendFile('C:\\Users\\DOREEN\\Desktop\\Fitness Finder' + '/index.html')_x000D_
})
_x000D_
_x000D_
_x000D_

Listen to port via a Java socket

What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:

$ nc -l 4000

...and change socket address to localhost:4000, it will work and try to read something from nc-created server.

What you probably want is to create a ServerSocket and listen on it:

ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();

The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)

How to choose an AWS profile when using boto3 to connect to CloudFront

This section of the boto3 documentation is helpful.

Here's what worked for me:

session = boto3.Session(profile_name='dev')
client = session.client('cloudfront')

Python list sort in descending order

You can simply do this:

timestamps.sort(reverse=True)

How to use youtube-dl from a python program?

For simple code, may be i think

import os
os.system('youtube-dl [OPTIONS] URL [URL...]')

Above is just running command line inside python.

Other is mentioned in the documentation Using youtube-dl on python Here is the way

from __future__ import unicode_literals
import youtube_dl

ydl_opts = {}
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
    ydl.download(['https://www.youtube.com/watch?v=BaW_jenozKc'])

A table name as a variable

Declare @fs_e int, @C_Tables CURSOR, @Table varchar(50)

SET @C_Tables = CURSOR FOR
        select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN @C_Tables
FETCH @C_Tables INTO @Table
    SELECT @fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '@C_Tables'

WHILE ( @fs_e <> -1)
    BEGIN
        exec('Select * from ' + @Table)
        FETCH @C_Tables INTO @Table
        SELECT @fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '@C_Tables'
    END

C++ calling base class constructors

Imagine it like this: When your sub-class inherits properties from a super-class, they don't magically appear. You still have to construct the object. So, you call the base constructor. Imagine if you class inherits a variable, which your super-class constructor initializes to an important value. If we didn't do this, your code could fail because the variable wasn't initialized.

MVC - Set selected value of SelectList

I usually use this method

        public static SelectList SetSelectedValue(SelectList list, string value)
    {
        if (value != null)
        {
            var selected = list.Where(x => x.Value == value).First();
            selected.Selected = true;
            return list;
        }
        return list;
    }

How to check if an NSDictionary or NSMutableDictionary contains a key?

For checking existence of key in NSDictionary:

if([dictionary objectForKey:@"Replace your key here"] != nil)
    NSLog(@"Key Exists");
else
    NSLog(@"Key not Exists");

Does Java read integers in little endian or big endian?

There are no unsigned integers in Java. All integers are signed and in big endian.

On the C side the each byte has tne LSB at the start is on the left and the MSB at the end.

It sounds like you are using LSB as Least significant bit, are you? LSB usually stands for least significant byte. Endianness is not bit based but byte based.

To convert from unsigned byte to a Java integer:

int i = (int) b & 0xFF;

To convert from unsigned 32-bit little-endian in byte[] to Java long (from the top of my head, not tested):

long l = (long)b[0] & 0xFF;
l += ((long)b[1] & 0xFF) << 8;
l += ((long)b[2] & 0xFF) << 16;
l += ((long)b[3] & 0xFF) << 24;

builder for HashMap

I had a similar requirement a while back. Its nothing to do with Guava but you can do something like this to be able to cleanly construct a Map using a fluent builder.

Create a base class that extends Map.

public class FluentHashMap<K, V> extends LinkedHashMap<K, V> {
    private static final long serialVersionUID = 4857340227048063855L;

    public FluentHashMap() {}

    public FluentHashMap<K, V> delete(Object key) {
        this.remove(key);
        return this;
    }
}

Then create the fluent builder with methods that suit your needs:

public class ValueMap extends FluentHashMap<String, Object> {
    private static final long serialVersionUID = 1L;

    public ValueMap() {}

    public ValueMap withValue(String key, String val) {
        super.put(key, val);
        return this;
    }

... Add withXYZ to suit...

}

You can then implement it like this:

ValueMap map = new ValueMap()
      .withValue("key 1", "value 1")
      .withValue("key 2", "value 2")
      .withValue("key 3", "value 3")

Sending HTML email using Python

From Python v2.7.14 documentation - 18.1.11. email: Examples:

Here’s an example of how to create an HTML message with an alternative plain text version:

#! /usr/bin/python

import smtplib

from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

# me == my email address
# you == recipient's email address
me = "[email protected]"
you = "[email protected]"

# Create message container - the correct MIME type is multipart/alternative.
msg = MIMEMultipart('alternative')
msg['Subject'] = "Link"
msg['From'] = me
msg['To'] = you

# Create the body of the message (a plain-text and an HTML version).
text = "Hi!\nHow are you?\nHere is the link you wanted:\nhttp://www.python.org"
html = """\
<html>
  <head></head>
  <body>
    <p>Hi!<br>
       How are you?<br>
       Here is the <a href="http://www.python.org">link</a> you wanted.
    </p>
  </body>
</html>
"""

# Record the MIME types of both parts - text/plain and text/html.
part1 = MIMEText(text, 'plain')
part2 = MIMEText(html, 'html')

# Attach parts into message container.
# According to RFC 2046, the last part of a multipart message, in this case
# the HTML message, is best and preferred.
msg.attach(part1)
msg.attach(part2)

# Send the message via local SMTP server.
s = smtplib.SMTP('localhost')
# sendmail function takes 3 arguments: sender's address, recipient's address
# and message to send - here it is sent as one string.
s.sendmail(me, you, msg.as_string())
s.quit()

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

Doing the expicit casting to the "int" solves the problem in my case. I had the same issue. So:

int count = (int)[myColors count];

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

Some solutions didn't work for me but the best option I found was the example below when i decided to use the flex option.

_x000D_
_x000D_
html, body{
    height: 100%;   
}

body{
    display: flex;
    flex-direction: column;
}

.main-contents{ 
    flex: 1 0 auto;
    min-height: 100%;
    margin-bottom: -77px;
  background-color: #CCC;
}

.footer{
    height:  77px;
    min-height: 77px;
    width: 100%;
    bottom: 0;
    left: 0;
    background: #000000;
    flex-shrink: 0;
    flex-direction: row;
    position: relative;
    
    
}

.footer-text{
  color: #FFF;
}

@media screen and (max-width: 767px){
    #content{
        padding-bottom: 0;
    }
    .footer{
        position: relative;
        /*position: absolute;*/
        height: 77px;
        width: 100%;
        bottom: 0;
        left: 0;
    }

}
_x000D_
<html>
  <body>
    <div class="main-contents" >
      this is the main content
    </div>
  </body>

  <footer class="footer">
    <p class="footer-text">This is the sticky footer</p>
  </footer>

</html>
_x000D_
_x000D_
_x000D_

X-Frame-Options on apache

This worked for me on all browsers:

  1. Created one page with all my javascript
  2. Created a 2nd page on the same server and embedded the first page using the object tag.
  3. On my third party site I used the Object tag to embed the 2nd page.
  4. Created a .htaccess file on the original server in the public_html folder and put Header unset X-Frame-Options in it.

How do you append to an already existing string?

$ string="test"
$ string="${string}test2"
$ echo $string
testtest2

Class method differences in Python: bound, unbound and static

Bound method = instance method

Unbound method = static method.

estimating of testing effort as a percentage of development time

When you speak of tests, you could mean waterfall or agile test development. In an agile environment, developers should spend 50% of their time developing and maintaining tests.

But that 50% extra will save you time when the re-factoring and manual verification time comes.

CSS - Overflow: Scroll; - Always show vertical scroll bar?

This will make the scroll bars always display when there is content within windows that must be scrolled to access, it applies to all windows and all apps on the Mac:

Launch System Preferences from the ? Apple menu Click on the “General” settings panel Look for ‘Show scroll bars’ and select the radiobox next to “Always” Close out of System Preferences when finished

Best way to format integer as string with leading zeros?

A straightforward conversion would be (again with a function):

def add_nulls2(int, cnt):
    nulls = str(int)
    for i in range(cnt - len(str(int))):
        nulls = '0' + nulls
    return nulls

MySQL - How to increase varchar size of an existing column in a database without breaking existing data?

For me worked this one:

ALTER TABLE tablename MODIFY fieldname VARCHAR(128) NOT NULL;

Kotlin unresolved reference in IntelliJ

Had the same with IDEA 14.1.5, Kotlin v.1.0.0-beta-1038-IJ141-17.
Kotlin gets its own list entry (like Java) when creating new project, but the only working config was:

New | Project | Java | "Kotlin (Java)" (make sure you have Project SDK configured, too)
use library: Create, "Copy to: lib".

How to use the addr2line command in Linux?

That's exactly how you use it. There is a possibility that the address you have does not correspond to something directly in your source code though.

For example:

$ cat t.c
#include <stdio.h>
int main()
{
    printf("hello\n");
    return 0;
}
$ gcc -g t.c
$ addr2line -e a.out 0x400534
/tmp/t.c:3
$ addr2line -e a.out 0x400550
??:0

0x400534 is the address of main in my case. 0x400408 is also a valid function address in a.out, but it's a piece of code generated/imported by GCC, that has no debug info. (In this case, __libc_csu_init. You can see the layout of your executable with readelf -a your_exe.)

Other times when addr2line will fail is if you're including a library that has no debug information.

How do I send email with JavaScript without opening the mail client?

There needs to be some type of backend framework to send the email. This can be done via PHP/ASP.NET, or with the local mail client. If you want the user to see nothing, the best way is to tap into those by an AJAX call to a separate send_email file.

Delete from two tables in one query

Try this please

DELETE FROM messages,usersmessages

USING messages

INNER JOIN usermessages on (messages.messageid = usersmessages.messageid)

WHERE messages.messsageid='1'

Error: TypeError: $(...).dialog is not a function

I just experienced this with the line:

$('<div id="editor" />').dialogelfinder({

I got the error "dialogelfinder is not a function" because another component was inserting a call to load an older version of JQuery (1.7.2) after the newer version was loaded.

As soon as I commented out the second load, the error went away.

How to comment lines in rails html.erb files?

Note that if you want to comment out a single line of printing erb you should do like this

<%#= ["Buck", "Papandreou"].join(" you ") %>

Chart.js v2 - hiding grid lines

If you want them gone by default, you can set:

Chart.defaults.scale.gridLines.display = false;

How to run shell script file using nodejs?

you can go:

var cp = require('child_process');

and then:

cp.exec('./myScript.sh', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a command in your $SHELL.
Or go

cp.spawn('./myScript.sh', [args], function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a file WITHOUT a shell.
Or go

cp.execFile();

which is the same as cp.exec() but doesn't look in the $PATH.

You can also go

cp.fork('myJS.js', function(err, stdout, stderr) {
  // handle err, stdout, stderr
});

to run a javascript file with node.js, but in a child process (for big programs).

EDIT

You might also have to access stdin and stdout with event listeners. e.g.:

var child = cp.spawn('./myScript.sh', [args]);
child.stdout.on('data', function(data) {
  // handle stdout as `data`
});

Is there a way to pass jvm args via command line to maven?

I think MAVEN_OPTS would be most appropriate for you. See here: http://maven.apache.org/configure.html

In Unix:

Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.

In Win, you need to set environment variable via the dialogue box

Add ... environment variable by opening up the system properties (WinKey + Pause),... In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.

What's the difference between text/xml vs application/xml for webservice response

application/xml is seen by svn as binary type whereas text/xml as text file for which a diff can be displayed.

Can Console.Clear be used to only clear a line instead of whole console?

We could simply write the following method

public static void ClearLine()
{
    Console.SetCursorPosition(0, Console.CursorTop - 1);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, Console.CursorTop - 1);
}

and then call it when needed like this

Console.WriteLine("Test");
ClearLine();

It works fine for me.

Adding backslashes without escaping [Python]

There is no extra backslash, it's just formatted that way in the interactive environment. Try:

print string

Then you can see that there really is no extra backslash.

How to add a jar in External Libraries in android studio

Put your JAR in app/libs, and in app/build.gradle add in the dependencies section:

compile fileTree(dir: 'libs', include: ['*.jar'])

How to get the selected value from RadioButtonList?

Technically speaking the answer is correct, but there is a potential problem remaining. string test = rb.SelectedValue is an object and while this implicit cast works. It may not work correction if you were sending it to another method (and granted this may depend on the version of framework, I am unsure) it may not recognize the value.

string test = rb.SelectedValue;  //May work fine
SomeMethod(rb.SelectedValue);

where SomeMethod is expecting a string may not.

Sadly the rb.SelectedValue.ToString(); can save a few unexpected issues.

Understanding __get__ and __set__ and Python descriptors

I tried (with minor changes as suggested) the code from Andrew Cooke's answer. (I am running python 2.7).

The code:

#!/usr/bin/env python
class Celsius:
    def __get__(self, instance, owner): return 9 * (instance.fahrenheit + 32) / 5.0
    def __set__(self, instance, value): instance.fahrenheit = 32 + 5 * value / 9.0

class Temperature:
    def __init__(self, initial_f): self.fahrenheit = initial_f
    celsius = Celsius()

if __name__ == "__main__":

    t = Temperature(212)
    print(t.celsius)
    t.celsius = 0
    print(t.fahrenheit)

The result:

C:\Users\gkuhn\Desktop>python test2.py
<__main__.Celsius instance at 0x02E95A80>
212

With Python prior to 3, make sure you subclass from object which will make the descriptor work correctly as the get magic does not work for old style classes.

Python Remove last 3 characters of a string

>>> foo = 'BS1 1AB'
>>> foo.replace(" ", "").rstrip()[:-3].upper()
'BS1'

How to create a inset box-shadow only on one side?

The trick is a second .box-inner inside, which is larger in width than the original .box, and the box-shadow is applied to that.

Then, added more padding to the .text to make up for the added width.

This is how the logic looks:

box logic

And here's how it's done in CSS:

Use max width for .inner-box to not cause .box to get wider, and overflow to make sure the remaining is clipped:

.box {
    max-width: 100% !important;
    overflow: hidden;
}

110% is wider than the parent which is 100% in a child's context (should be the same when the parent .box has a fixed width, for example). Negative margins make up for the width and cause the element to be centered (instead of only the right part hiding):

.box-inner {
    width: 110%;
    margin-left:-5%;
    margin-right: -5%;
    -webkit-box-shadow: inset 0px 5px 10px 1px #000000;
    box-shadow: inset 0px 5px 10px 1px #000000;
}

And add some padding on the X axis to make up for the wider .inner-box:

.text {
    padding: 20px 40px;
}

Here's a working Fiddle.

If you inspect the Fiddle, you'll see:

.box .box-inner .text

MAVEN_HOME, MVN_HOME or M2_HOME

Here is my Maven setup. You can use it as an example. You don't need anything else in order to use Maven.

M2_HOME is used for both Maven 2 and 3

export M2_HOME=/Users/xxx/sdk/apache-maven-3.0.5
export M2=$M2_HOME/bin
export MAVEN_OPTS="-Xmx1048m -Xms256m -XX:MaxPermSize=312M"
export PATH=$M2:$PATH

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

You just need to use below code when launching the new activity.

startActivity(new Intent(this, newactivity.class));
finish();

Format price in the current locale and currency

For formatting the price in another currency than the current one:

Mage::app()->getLocale()->currency('EUR')->toCurrency($price);

Uncaught TypeError: .indexOf is not a function

Basically indexOf() is a method belongs to string(array object also), But while calling the function you are passing a number, try to cast it to a string and pass it.

document.getElementById("oset").innerHTML = timeD2C(timeofday + "");

_x000D_
_x000D_
 var timeofday = new Date().getHours() + (new Date().getMinutes()) / 60;_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
 function timeD2C(time) { // Converts 11.5 (decimal) to 11:30 (colon)_x000D_
    var pos = time.indexOf('.');_x000D_
    var hrs = time.substr(1, pos - 1);_x000D_
    var min = (time.substr(pos, 2)) * 60;_x000D_
_x000D_
    if (hrs > 11) {_x000D_
        hrs = (hrs - 12) + ":" + min + " PM";_x000D_
    } else {_x000D_
        hrs += ":" + min + " AM";_x000D_
    }_x000D_
    return hrs;_x000D_
}_x000D_
alert(timeD2C(timeofday+""));
_x000D_
_x000D_
_x000D_


And it is good to do the string conversion inside your function definition,

function timeD2C(time) { 
  time = time + "";
  var pos = time.indexOf('.');

So that the code flow won't break at times when devs forget to pass a string into this function.

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 do I subtract minutes from a date in javascript?

moment.js has some really nice convenience methods to manipulate date objects

The .subtract method, allows you to subtract a certain amount of time units from a date, by providing the amount and a timeunit string.

var now = new Date();
// Sun Jan 22 2017 17:12:18 GMT+0200 ...
var olderDate = moment(now).subtract(3, 'minutes').toDate();
// Sun Jan 22 2017 17:09:18 GMT+0200 ...

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

What does elementFormDefault do in XSD?

ElementFormDefault has nothing to do with namespace of the types in the schema, it's about the namespaces of the elements in XML documents which comply with the schema.

Here's the relevent section of the spec:

Element Declaration Schema

Component Property  {target namespace}
Representation      If form is present and its ·actual value· is qualified, 
                    or if form is absent and the ·actual value· of 
                    elementFormDefault on the <schema> ancestor is qualified, 
                    then the ·actual value· of the targetNamespace [attribute]
                    of the parent <schema> element information item, or 
                    ·absent· if there is none, otherwise ·absent·.

What that means is that the targetNamespace you've declared at the top of the schema only applies to elements in the schema compliant XML document if either elementFormDefault is "qualified" or the element is declared explicitly in the schema as having form="qualified".

For example: If elementFormDefault is unqualified -

<element name="name" type="string" form="qualified"></element>
<element name="page" type="target:TypePage"></element>

will expect "name" elements to be in the targetNamespace and "page" elements to be in the null namespace.

To save you having to put form="qualified" on every element declaration, stating elementFormDefault="qualified" means that the targetNamespace applies to each element unless overridden by putting form="unqualified" on the element declaration.

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

You could try this registry hack:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters]
"DeadGWDetectDefault"=dword:00000001
"KeepAliveTime"=dword:00120000

If it works, just keep increasing the KeepAliveTime. It is currently set for 2 minutes.

git - remote add origin vs remote set-url origin

This is very simple If you have already set a remote origin url then you use set-url command to change that, otherwise simply use add command

  1. git remote -v Check if any remote already exists
  2. If Yes then use git remote set-url origin [email protected]:User/UserRepo.git to change the origin
  3. If No then use git remote add origin [email protected]:User/UserRepo.git to set new origin for your repo.
  4. and finally use git push -u origin master to push your code to remote and add upstream (tracking) reference to your remote branch.

NOTE: If you use -u flag, its for upstream, it enables you to use simply git pull instead of git pull origin <branch-name> in upcoming operations.

Happy Coding ;)

Undo a git stash

You can just run:

git stash pop

and it will unstash your changes.

If you want to preserve the state of files (staged vs. working), use

git stash apply --index

How to check if a subclass is an instance of a class at runtime?

If there is polymorphism such as checking SQLRecoverableException vs SQLException, it can be done like that.

try {
    // sth may throw exception
    ....
} catch (Exception e) {
    if(SQLException.class.isAssignableFrom(e.getCause().getClass()))
    {
        // do sth
        System.out.println("SQLException occurs!");
    }
}

Simply say,

ChildClass child= new ChildClass();
if(ParentClass.class.isAssignableFrom(child.getClass()))
{
    // do sth
    ...
}

list.clear() vs list = new ArrayList<Integer>();

Tried the below program , With both the approach. 1. With clearing the arraylist obj in for loop 2. creating new New Arraylist in for loop.

List al= new ArrayList();
        for(int i=0;i<100;i++)
        {
            //List al= new ArrayList();

            for(int j=0;j<10;j++)
            {
                al.add(Integer.parseInt("" +j+i));
                //System.out.println("Obj val " +al.get(j));
            }
            //System.out.println("Hashcode : " + al.hashCode());
            al.clear();

        }

and to my surprise. the memory allocation didnt change much.

With New Arraylist approach.

Before loop total free memory: 64,909 ::

After loop total free memory: 64,775 ::

with Clear approach,

Before loop total free memory: 64,909 :: After loop total free memory: 64,765 ::

So this says there is not much difference in using arraylist.clear from memory utilization perspective.

How to start/stop/restart a thread in Java?

It is impossible to terminate a thread unless the code running in that thread checks for and allows termination.

You said: "Sadly I must kill/restart it ... I don't have complete control over the contents of the thread and for my situation it requires a restart"

If the contents of the thread does not allow for termination of its exectuion then you can not terminate that thread.

In your post you said: "My first attempt was with ExecutorService but I can't seem to find a way for it restart a task. When I use .shutdownnow()..."

If you look at the source of "shutdownnow" it just runs through and interrupts the currently running threads. This will not stop their execution unless the code in those threads checks to see if it has been ineterrupted and, if so, stops execution itself. So shutdownnow is probably not doing what you think.

Let me illustrate what I mean when I say that the contents of the thread must allow for that thread to be terminated:

myExecutor.execute(new Runnable() {
 public void run() {
  while (true) {
    System.out.println("running");
  }
 }
 });
myExecutor.shutdownnow();

That thread will continue to run forever, even though shutdownnow was called, because it never checks to see if it has been terminated or not. This thread, however, will shut down:

myExecutor.execute(new Runnable() {
 public void run() {
  while (!Thread.interrupted()) {
    System.out.println("running");
  }
 }
 });
myExecutor.shutdownnow();

Since this thread checks to see whether or not it has been interrupted / shut down / terminated.

So if you want a thread that you can shut down, you need to make sure it checks to see if it has been interrupted. If you want a thread that you can "shut down" and "restart" you can make a runnable that can take new tasks as was mentioned before.

Why can you not shut down a running thread? Well I actually lied, you can call "yourThread.stop()" but why is this a bad idea? The thread could be in a synchronized (or other critical section, but we will limit ourselves to setions guarded by the syncrhonized key word here) section of code when you stop it. synch blocks are supposed to be executed in their entirity and only by one thread before being accessed by some other thread. If you stop a thread in the middle of a synch block, the protection put into place by the synch block is invalidated and your program will get into an unknown state. Developers make put stuff in synch blocks to keep things in synch, if you use threadInstance.stop() you destroy the meaning of synchronize, what the developer of that code was trying to accomplish and how the developer of that code expected his synchronized blocks to behave.

HTML: how to force links to open in a new tab, not new window

a {
    target-name: new;
    target-new: tab;
}

The target-new property specifies whether new destination links should open in a new window or in a new tab of an existing window.

Note: The target-new property only works if the target-name property creates a new tab or a new window.

How to turn a String into a JavaScript function call?

Based on Nicolas Gauthier answer:

var strng = 'someobj.someCallback';
var data = 'someData';

var func = window;
var funcSplit = strng.split('.');
for(i = 0;i < funcSplit.length;i++){
   //We maybe can check typeof and break the bucle if typeof != function
   func = func[funcSplit[i]];
}
func(data);

Loop X number of times

Use:

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

Output:

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

How to generate an MD5 file hash in JavaScript?

You can use crypto-js.

To use crypto-js, you need to load core.js then md5.js .

A list of URLs are here https://cdnjs.com/libraries/crypto-js

cryptojs is also available in zip form here https://code.google.com/archive/p/crypto-js/downloads

There is an answer from answerer 'amal' in 2013, that is similar to this but a)his link to md5.js no longer works b)he didn't load core.js beforehand, which is necessary.

<html>    
  <head> 

    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/core.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/md5.js"></script>

  <script>
     var hash = CryptoJS.MD5("Message");
     console.log(hash);
  </script>

  </head>
  <body>

  </body>
</html>

display HTML page after loading complete

try using javascript for this! Seems like its the best and easiest way to do this. You'll get inbuilt funcn to execute a html code only after HTML page loads completely.

or else you may use state based programming where an event occurs at a particular state of the browser..

Toggle show/hide on click with jQuery

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js</script>        <script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").toggle();
  });
});
</script>
</head>
<body>
<p>Welcome !!!</p>
<button>Toggle between hide() and show()</button>
</body>
</html>

When and where to use GetType() or typeof()?

typeof is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType is called on an object at runtime. In both cases the result is an object of the type System.Type containing meta-information on a type.

Example where compile-time and run-time types are equal

string s = "hello";

Type t1 = typeof(string);
Type t2 = s.GetType();

t1 == t2 ==> true

Example where compile-time and run-time types are different

object obj = "hello";

Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType();  // ==> string!

t1 == t2 ==> false

i.e., the compile time type (static type) of the variable obj is not the same as the runtime type of the object referenced by obj.


Testing types

If, however, you only want to know whether mycontrol is a TextBox then you can simply test

if (mycontrol is TextBox)

Note that this is not completely equivalent to

if (mycontrol.GetType() == typeof(TextBox))    

because mycontrol could have a type that is derived from TextBox. In that case the first comparison yields true and the second false! The first and easier variant is OK in most cases, since a control derived from TextBox inherits everything that TextBox has, probably adds more to it and is therefore assignment compatible to TextBox.

public class MySpecializedTextBox : TextBox
{
}

MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox)       ==> true

if (specialized.GetType() == typeof(TextBox))        ==> false

Casting

If you have the following test followed by a cast and T is nullable ...

if (obj is T) {
    T x = (T)obj; // The casting tests, whether obj is T again!
    ...
}

... you can change it to ...

T x = obj as T;
if (x != null) {
    ...
}

Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as operator followed by a test for null is more performing.

Starting with C# 7.0 you can simplify the code by using pattern matching:

if (obj is T t) {
    // t is a variable of type T having a non-null value.
    ...
}

Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:

if (o is int? ni) ===> does NOT compile!

This is because either the value is null or it is an int. This works for int? o as well as for object o = new Nullable<int>(x);:

if (o is int i) ===> OK!

I like it, because it eliminates the need to access the Nullable<T>.Value property.

How to store a command in a variable in a shell script?

For bash, store your command like this:

command="ls | grep -c '^'"

Run your command like this:

echo $command | bash

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

Assuming that the *.bak file is on the same machine as the SQL Express instance it might be a permissions issue.

If you download procmon http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx you can filter on that file path, look for ACCESS_DENIED errors and if any are there you can see the account name that's failing get to access.

How to create an empty matrix in R?

The default for matrix is to have 1 column. To explicitly have 0 columns, you need to write

matrix(, nrow = 15, ncol = 0)

A better way would be to preallocate the entire matrix and then fill it in

mat <- matrix(, nrow = 15, ncol = n.columns)
for(column in 1:n.columns){
  mat[, column] <- vector
}

Create a 3D matrix

Create a 3D matrix

A = zeros(20, 10, 3);   %# Creates a 20x10x3 matrix

Add a 3rd dimension to a matrix

B = zeros(4,4);  
C = zeros(size(B,1), size(B,2), 4);  %# New matrix with B's size, and 3rd dimension of size 4
C(:,:,1) = B;                        %# Copy the content of B into C's first set of values

zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0 for a 3D matrix. To confirm the size of your matrices you can run: size(A) which gives 20 10 3.

There is no explicit bound on the number of dimensions a matrix may have.

Installing pip packages to $HOME folder

You can specify the -t option (--target) to specify the destination directory. See pip install --help for detailed information. This is the command you need:

pip install -t path_to_your_home package-name

for example, for installing say mxnet, in my $HOME directory, I type:

pip install -t /home/foivos/ mxnet

Extracting just Month and Year separately from Pandas Datetime column

There is two steps to extract year for all the dataframe without using method apply.

Step1

convert the column to datetime :

df['ArrivalDate']=pd.to_datetime(df['ArrivalDate'], format='%Y-%m-%d')

Step2

extract the year or the month using DatetimeIndex() method

 pd.DatetimeIndex(df['ArrivalDate']).year

Spring MVC UTF-8 Encoding

Easiest solution to force UTF-8 encoding in Spring MVC returning String:

In @RequestMapping, use:

produces = MediaType.APPLICATION_JSON_VALUE + "; charset=utf-8"

Style bottom Line in Android

it is completely transparent Edittext with transparent background.

<item>
    <shape android:shape="rectangle" >
        <solid android:color="@color/transparent" />
    </shape>
</item>

<item android:top="-3dp" android:right="-3dp" android:left="-3dp">
    <shape>
        <solid android:color="@android:color/transparent" />
        <stroke

            android:width="2dp"
            android:color="@color/bottomline" />
    </shape>
</item>

How to create a batch file to run cmd as administrator

Press Ctrl+Shift and double-click a shortcut to run as an elevated process.

Works from the start menu as well.

How to correctly dismiss a DialogFragment?

Here is a simple AppCompatActivity extension function, which closes opened Dialog Fragment:

fun AppCompatActivity.whenDialogOpenDismiss(
    tag: String
) {
    supportFragmentManager.findFragmentByTag(tag)?.let { 
        if(it is DialogFragment) it.dismiss() }
}

Of course you can call it from any activity directly. If you need to call it from a Fragment just make the same extension function about Fragment class

Handling a Menu Item Click Event - Android

Replace Your onOptionsItemSelected as:

  @Override
          public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
              case OK_MENU_ITEM:
                 startActivity(new Intent(DashboardActivity.this, SettingActivity.class));
                 break;

            // You can handle other cases Here.
              default: 
                 super.onOptionsItemSelected(item);
            }
          }

Here, I want to navigate from DashboardActivity to SettingActivity.

How to make node.js require absolute? (instead of relative)

There's a good discussion of this issue here.

I ran into the same architectural problem: wanting a way of giving my application more organization and internal namespaces, without:

  • mixing application modules with external dependencies or bothering with private npm repos for application-specific code
  • using relative requires, which make refactoring and comprehension harder
  • using symlinks or changing the node path, which can obscure source locations and don't play nicely with source control

In the end, I decided to organize my code using file naming conventions rather than directories. A structure would look something like:

  • npm-shrinkwrap.json
  • package.json
  • node_modules
    • ...
  • src
    • app.js
    • app.config.js
    • app.models.bar.js
    • app.models.foo.js
    • app.web.js
    • app.web.routes.js
    • ...

Then in code:

var app_config = require('./app.config');
var app_models_foo = require('./app.models.foo');

or just

var config = require('./app.config');
var foo = require('./app.models.foo');

and external dependencies are available from node_modules as usual:

var express = require('express');

In this way, all application code is hierarchically organized into modules and available to all other code relative to the application root.

The main disadvantage is of course that in a file browser, you can't expand/collapse the tree as though it was actually organized into directories. But I like that it's very explicit about where all code is coming from, and it doesn't use any 'magic'.

AngularJS $watch window resize inside directive

You can listen resize event and fire where some dimension change

directive

(function() {
'use strict';

    angular
    .module('myApp.directives')
    .directive('resize', ['$window', function ($window) {
        return {
            link: link,
            restrict: 'A'
        };

        function link(scope, element, attrs){
            scope.width = $window.innerWidth;
            function onResize(){
                // uncomment for only fire when $window.innerWidth change   
                // if (scope.width !== $window.innerWidth)
                {
                    scope.width = $window.innerWidth;
                    scope.$digest();
                }
            };

            function cleanUp() {
                angular.element($window).off('resize', onResize);
            }

            angular.element($window).on('resize', onResize);
            scope.$on('$destroy', cleanUp);
        }
    }]);
})();

In html

<div class="row" resize> ,
    <div class="col-sm-2 col-xs-6" ng-repeat="v in tag.vod"> 
        <h4 ng-bind="::v.known_as"></h4>
    </div> 
</div> 

Controller :

$scope.$watch('width', function(old, newv){
     console.log(old, newv);
 })

How to get the file name from a full path using JavaScript?

function getFileName(path, isExtension){

  var fullFileName, fileNameWithoutExtension;

  // replace \ to /
  while( path.indexOf("\\") !== -1 ){
    path = path.replace("\\", "/");
  }

  fullFileName = path.split("/").pop();
  return (isExtension) ? fullFileName : fullFileName.slice( 0, fullFileName.lastIndexOf(".") );
}

How to run only one unit test class using Gradle

After much figuring out, the following worked for me:

gradle test --tests "a.b.c.MyTestFile.mySingleTest"

What does a question mark represent in SQL queries?

What you are seeing is a parameterized query. They are frequently used when executing dynamic SQL from a program.

For example, instead of writing this (note: pseudocode):

ODBCCommand cmd = new ODBCCommand("SELECT thingA FROM tableA WHERE thingB = 7")
result = cmd.Execute()

You write this:

ODBCCommand cmd = new ODBCCommand("SELECT thingA FROM tableA WHERE thingB = ?")
cmd.Parameters.Add(7)
result = cmd.Execute()

This has many advantages, as is probably obvious. One of the most important: the library functions which parse your parameters are clever, and ensure that strings are escaped properly. For example, if you write this:

string s = getStudentName()
cmd.CommandText = "SELECT * FROM students WHERE (name = '" + s + "')"
cmd.Execute()

What happens when the user enters this?

Robert'); DROP TABLE students; --

(Answer is here)

Write this instead:

s = getStudentName()
cmd.CommandText = "SELECT * FROM students WHERE name = ?"
cmd.Parameters.Add(s)
cmd.Execute()

Then the library will sanitize the input, producing this:

"SELECT * FROM students where name = 'Robert''); DROP TABLE students; --'"

Not all DBMS's use ?. MS SQL uses named parameters, which I consider a huge improvement:

cmd.Text = "SELECT thingA FROM tableA WHERE thingB = @varname"
cmd.Parameters.AddWithValue("@varname", 7)
result = cmd.Execute()

Best way to parseDouble with comma as decimal separator?

Double.parseDouble(p.replace(',','.'))

...is very quick as it searches the underlying character array on a char-by-char basis. The string replace versions compile a RegEx to evaluate.

Basically replace(char,char) is about 10 times quicker and since you'll be doing these kind of things in low-level code it makes sense to think about this. The Hot Spot optimiser will not figure it out... Certainly doesn't on my system.

git status shows fatal: bad object HEAD

In my case the error came out of nowhere, but didn't let me push to the remote branch.

git fetch origin

And that solved it.

I agree this may not solve the issue for everyone, but before trying a more complex approach give it a shot at this one, nothing to loose.

Global Variable from a different file Python

from file2 import * is making copies. You want to do this:

import file2
print file2.foo
print file2.SomeClass()

Common CSS Media Queries Break Points

I always use Desktop first, mobile first doesn't have highest priority does it? IE< 8 will show mobile css..

normal css here: 

@media screen and (max-width: 768px) {}

@media screen and (max-width: 480px) {}

sometimes some custom sizes. I don't like bootstrap etc.

Fastest way to ping a network range and return responsive hosts?

Try both of these commands and see for yourself why arp is faster:

PING:

for ip in $(seq 1 254); do ping -c 1 10.185.0.$ip > /dev/null; [ $? -eq 0 ] && echo "10.185.0.$ip UP" || : ; done

ARP:

for ip in $(seq 1 254); do arp -n 10.185.0.$ip | grep Address; [ $? -eq 0 ] && echo "10.185.0.$ip UP" || : ; done

how to call a variable in code behind to aspx page

The HelloFromCsharp.aspx look like this

 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HelloFromCsharp.aspx.cs" Inherits="Test.HelloFromCsharp" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <p>
       <%= clients%>
    </p>
    </form>
</body>
</html>

And the HelloFromCsharp.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Test
{
    public partial class HelloFromCsharp : System.Web.UI.Page
    {
        public string clients;
        protected void Page_Load(object sender, EventArgs e)
        {
            clients = "Hello From C#";
        }
    }
}

How to check radio button is checked using JQuery?

Radio buttons are,

<input type="radio" id="radio_1" class="radioButtons" name="radioButton" value="1">
<input type="radio" id="radio_2" class="radioButtons" name="radioButton" value="2">

to check on click,

$('.radioButtons').click(function(){
    if($("#radio_1")[0].checked){
       //logic here
    }
});

Append lines to a file using a StreamWriter

Another option is using System.IO.File.AppendText

This is equivalent to the StreamWriter overloads others have given.

Also File.AppendAllText may give a slightly easier interface without having to worry about opening and closing the stream. Though you may need to then worry about putting in your own linebreaks. :)

Removing a list of characters in string

i think this is simple enough and will do!

list = [",",",","!",";",":"] #the list goes on.....

theString = "dlkaj;lkdjf'adklfaj;lsd'fa'dfj;alkdjf" #is an example string;
newString="" #the unwanted character free string
for i in range(len(TheString)):
    if theString[i] in list:
        newString += "" #concatenate an empty string.
    else:
        newString += theString[i]

this is one way to do it. But if you are tired of keeping a list of characters that you want to remove, you can actually do it by using the order number of the strings you iterate through. the order number is the ascii value of that character. the ascii number for 0 as a char is 48 and the ascii number for lower case z is 122 so:

theString = "lkdsjf;alkd8a'asdjf;lkaheoialkdjf;ad"
newString = ""
for i in range(len(theString)):
     if ord(theString[i]) < 48 or ord(theString[i]) > 122: #ord() => ascii num.
         newString += ""
     else:
        newString += theString[i]

Exception is never thrown in body of corresponding try statement

A catch-block in a try statement needs to catch exactly the exception that the code inside the try {}-block can throw (or a super class of that).

try {
    //do something that throws ExceptionA, e.g.
    throw new ExceptionA("I am Exception Alpha!");
}
catch(ExceptionA e) {
    //do something to handle the exception, e.g.
    System.out.println("Message: " + e.getMessage());
}

What you are trying to do is this:

try {
    throw new ExceptionB("I am Exception Bravo!");
}
catch(ExceptionA e) {
    System.out.println("Message: " + e.getMessage());
}

This will lead to an compiler error, because your java knows that you are trying to catch an exception that will NEVER EVER EVER occur. Thus you would get: exception ExceptionA is never thrown in body of corresponding try statement.

pandas DataFrame: replace nan values with average of columns

In [16]: df = DataFrame(np.random.randn(10,3))

In [17]: df.iloc[3:5,0] = np.nan

In [18]: df.iloc[4:6,1] = np.nan

In [19]: df.iloc[5:8,2] = np.nan

In [20]: df
Out[20]: 
          0         1         2
0  1.148272  0.227366 -2.368136
1 -0.820823  1.071471 -0.784713
2  0.157913  0.602857  0.665034
3       NaN -0.985188 -0.324136
4       NaN       NaN  0.238512
5  0.769657       NaN       NaN
6  0.141951  0.326064       NaN
7 -1.694475 -0.523440       NaN
8  0.352556 -0.551487 -1.639298
9 -2.067324 -0.492617 -1.675794

In [22]: df.mean()
Out[22]: 
0   -0.251534
1   -0.040622
2   -0.841219
dtype: float64

Apply per-column the mean of that columns and fill

In [23]: df.apply(lambda x: x.fillna(x.mean()),axis=0)
Out[23]: 
          0         1         2
0  1.148272  0.227366 -2.368136
1 -0.820823  1.071471 -0.784713
2  0.157913  0.602857  0.665034
3 -0.251534 -0.985188 -0.324136
4 -0.251534 -0.040622  0.238512
5  0.769657 -0.040622 -0.841219
6  0.141951  0.326064 -0.841219
7 -1.694475 -0.523440 -0.841219
8  0.352556 -0.551487 -1.639298
9 -2.067324 -0.492617 -1.675794

select and echo a single field from mysql db using PHP

And escape your values with mysql_real_escape_string since PHP6 won't do that for you anymore! :)

Split Java String by New Line

The above answers did not help me on Android, thanks to the Pshemo response that worked for me on Android. I will leave some of Pshemo's answer here :

split("\\\\n")

Using a Python subprocess call to invoke a Python script

The subprocess call is a very literal-minded system call. it can be used for any generic process...hence does not know what to do with a Python script automatically.

Try

call ('python somescript.py')

If that doesn't work, you might want to try an absolute path, and/or check permissions on your Python script...the typical fun stuff.

Disable button in jQuery

Use .prop instead (and clean up your selector string):

function disable(i){
    $("#rbutton_"+i).prop("disabled",true);
}

generated HTML:

<button id="rbutton_1" onclick="disable(1)">Click me</button>
<!-- wrap your onclick in quotes -->

But the "best practices" approach is to use JavaScript event binding and this instead:

_x000D_
_x000D_
$('.rbutton').on('click',function() {_x000D_
    $(this).prop("disabled",true);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<button class="rbutton">Click me</button>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/mblase75/2Nfu4/

Change a web.config programmatically with C# (.NET)

Since web.config file is xml file you can open web.config using xmldocument class. Get the node from that xml file that you want to update and then save xml file.

here is URL that explains in more detail how you can update web.config file programmatically.

http://patelshailesh.com/index.php/update-web-config-programmatically

Note: if you make any changes to web.config, ASP.NET detects that changes and it will reload your application(recycle application pool) and effect of that is data kept in Session, Application, and Cache will be lost (assuming session state is InProc and not using a state server or database).

How to convert flat raw disk image to vmdk for virtualbox or vmplayer?

To answer TJJ: But is it also possible to do this without copying the whole file? So, just to somehow create an additional vmdk-metafile, that references the raw dd-image.

Yes, it's possible. Here's how to use a flat disk image in VirtualBox:

First you create an image with dd in the usual way:

dd bs=512 count=60000 if=/dev/zero of=usbdrv.img

Then you can create a file for VirtualBox that references this image:

VBoxManage internalcommands createrawvmdk -filename "usbdrv.vmdk" -rawdisk "usbdrv.img"

You can use this image in VirtualBox as is, but depending on the guest OS it might not be visible immediately. For example, I experimented on using this method with a Windows guest OS and I had to do the following to give it a drive letter:

  • Go to the Control Panel.
  • Go to Administrative Tools.
  • Go to Computer Management.
  • Go to Storage\Disk Management in the left side panel.
  • You'll see your disk here. Create a partition on it and format it. Use FAT for small volumes, FAT32 or NTFS for large volumes.

You might want to access your files on Linux. First dismount it from the guest OS to be sure and remove it from the virtual machine. Now we need to create a virtual device that references the partition.

sfdisk -d usbdrv.img

Response:

label: dos
label-id: 0xd367a714
device: usbdrv.img
unit: sectors

usbdrv.img1 : start=          63, size=       48132, type=4

Take note of the start position of the partition: 63. In the command below I used loop4 because it was the first available loop device in my case.

sudo losetup -o $((63*512)) loop4 usbdrv.img
mkdir usbdrv
sudo mount /dev/loop4 usbdrv
ls usbdrv -l

Response:

total 0
-rwxr-xr-x. 1 root root 0 Apr  5 17:13 'Test file.txt'

Yay!

How to use the toString method in Java?

The toString() method returns a textual representation of an object. A basic implementation is already included in java.lang.Object and so because all objects inherit from java.lang.Object it is guaranteed that every object in Java has this method.

Overriding the method is always a good idea, especially when it comes to debugging, because debuggers often show objects by the result of the toString() method. So use a meaningful implementation but use it for technical purposes. The application logic should use getters:

public class Contact {
  private String firstName;
  private String lastName;
  public Contact (String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  public String getFirstName() {return firstName;}
  public String getLastName() {return lastName;}

  public String getContact() {
    return firstName + " " + lastName;
  }

  @Override
  public String toString() {
    return "["+getContact()+"]";
  }
}

Route [login] not defined

In app\Exceptions\Handler.php

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest(route('auth.login'));
}

What is the Record type in typescript?

  1. Can someone give a simple definition of what Record is?

A Record<K, T> is an object type whose property keys are K and whose property values are T. That is, keyof Record<K, T> is equivalent to K, and Record<K, T>[K] is (basically) equivalent to T.

  1. Is Record<K,T> merely a way of saying "all properties on this object will have type T"? Probably not all objects, since K has some purpose...

As you note, K has a purpose... to limit the property keys to particular values. If you want to accept all possible string-valued keys, you could do something like Record<string, T>, but the idiomatic way of doing that is to use an index signature like { [k: string]: T }.

  1. Does the K generic forbid additional keys on the object that are not K, or does it allow them and just indicate that their properties are not transformed to T?

It doesn't exactly "forbid" additional keys: after all, a value is generally allowed to have properties not explicitly mentioned in its type... but it wouldn't recognize that such properties exist:

declare const x: Record<"a", string>;
x.b; // error, Property 'b' does not exist on type 'Record<"a", string>'

and it would treat them as excess properties which are sometimes rejected:

declare function acceptR(x: Record<"a", string>): void;
acceptR({a: "hey", b: "you"}); // error, Object literal may only specify known properties

and sometimes accepted:

const y = {a: "hey", b: "you"};
acceptR(y); // okay
  1. With the given example:

    type ThreeStringProps = Record<'prop1' | 'prop2' | 'prop3', string>
    

    Is it exactly the same as this?:

    type ThreeStringProps = {prop1: string, prop2: string, prop3: string}
    

Yes!

Hope that helps. Good luck!

NodeJS / Express: what is "app.use"?

app.use is a function requires middleware. For example:

 app.use('/user/:id', function (req, res, next) {
       console.log('Request Type:', req.method);
        next();
     });

This example shows the middleware function installed in the /user/:id path. This function is executed for any type of HTTP request in the /user/:id path.

It is similar to the REST Web Server, just use different /xx to represent different actions.

What should every programmer know about security?

The importance of secure defaults in frameworks and APIs:

  • Lots of early web frameworks didn't escape html by default in templates and had XSS problems because of this
  • Lots of early web frameworks made it easier to concatenate SQL than to create parameterized queries leading to lots of SQL injection bugs.
  • Some versions of Erlang (R13B, maybe others) don't verify ssl peer certificates by default and there are probably lots of erlang code that is susceptible to SSL MITM attacks
  • Java's XSLT transformer by default allows execution of arbitrary java code. There has been many serious security bugs created by this.
  • Java's XML parsing APIs by default allow the parsed document to read arbitrary files on the filesystem. More fun :)

How to get hostname from IP (Linux)?

To find a hostname in your local network by IP address you can use:

nmblookup -A <ip>

To find a hostname on the internet you could use the host program:

host <ip>

Or you can install nbtscan by running:

sudo apt-get install nbtscan

And use:

nbtscan <ip>

*Taken from https://askubuntu.com/questions/205063/command-to-get-the-hostname-of-remote-server-using-ip-address/205067#205067

Update 2018-05-13

You can query a name server with nslookup. It works both ways!

nslookup <IP>
nslookup <hostname>

Display tooltip on Label's hover?

Are you find with using standard tooltip? You could use title attribute like

<label for="male" title="Hello This Will Have Some Value">Hello...</label>

You could add the title attribute of same value to the element that label is for as well.

How the single threaded non blocking IO model works in Node.js

Node.js is based on the event loop programming model. The event loop runs in single thread and repeatedly waits for events and then runs any event handlers subscribed to those events. Events can be for example

  • timer wait is complete
  • next chunk of data is ready to be written to this file
  • theres a fresh new HTTP request coming our way

All of this runs in single thread and no JavaScript code is ever executed in parallel. As long as these event handlers are small and wait for yet more events themselves everything works out nicely. This allows multiple request to be handled concurrently by a single Node.js process.

(There's a little bit magic under the hood as where the events originate. Some of it involve low level worker threads running in parallel.)

In this SQL case, there's a lot of things (events) happening between making the database query and getting its results in the callback. During that time the event loop keeps pumping life into the application and advancing other requests one tiny event at a time. Therefore multiple requests are being served concurrently.

event loop high level view

According to: "Event loop from 10,000ft - core concept behind Node.js".

Change first commit of project with Git?

If you want to modify only the first commit, you may try git rebase and amend the commit, which is similar to this post: How to modify a specified commit in git?

And if you want to modify all the commits which contain the raw email, filter-branch is the best choice. There is an example of how to change email address globally on the book Pro Git, and you may find this link useful http://git-scm.com/book/en/Git-Tools-Rewriting-History

Difference between SurfaceView and View?

A few things I've noted:

  • SurfaceViews contain a nice rendering mechanism that allows threads to update the surface's content without using a handler (good for animation).
  • Surfaceviews cannot be transparent, they can only appear behind other elements in the view hierarchy.
  • I've found that they are much faster for animation than rendering onto a View.

For more information (and a great usage example) refer to the LunarLander project in the SDK 's examples section.

How can I draw circle through XML Drawable - Android?

no need for the padding or the corners.

here's a sample:

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval" >
    <gradient android:startColor="#FFFF0000" android:endColor="#80FF00FF"
        android:angle="270"/>
</shape>

based on :

https://stackoverflow.com/a/10104037/878126

NVIDIA NVML Driver/library version mismatch

If you've recently updated, a reboot might solve this problem.

Cannot invoke an expression whose type lacks a call signature

Perhaps create a shared Fruit interface that provides isDecayed. fruits is now of type Fruit[] so the type can be explicit. Like this:

interface Fruit {
    isDecayed: boolean;
}

interface Apple extends Fruit {
    color: string;
}

interface Pear extends Fruit {
    weight: number;
}

interface FruitBasket {
    apples: Apple[];
    pears: Pear[];
}


const fruitBasket: FruitBasket = { apples: [], pears: [] };
const key: keyof FruitBasket = Math.random() > 0.5 ? 'apples': 'pears'; 
const fruits: Fruit[] = fruitBasket[key];

const freshFruits = fruits.filter((fruit) => !fruit.isDecayed);

Regular expression to match URLs in Java

((http?|https|ftp|file)://)?((W|w){3}.)?[a-zA-Z0-9]+\.[a-zA-Z]+

check here:- https://www.freeformatter.com/java-regex-tester.html#ad-output

It sorts out theses entries correctly

php codeigniter count rows

You may try this one

    $this->db->where('field1',$filed1);
    $this->db->where('filed2',$filed2);
    $result = $this->db->get('table_name')->num_rows();

how to delete all cookies of my website in php

The provided Answers did not solve my problem,

It did not:

  1. Remove parent domain cookies (from a.b.c; remove b.c; cookies),
  2. Remove cookies from a higher path other then root.

My script does, see.

<?php function unset_cookie($name)
{
    $host = $_SERVER['HTTP_HOST'];
    $domain = explode(':', $host)[0];

    $uri = $_SERVER['REQUEST_URI'];
    $uri = rtrim(explode('?', $uri)[0], '/');

    if ($uri && !filter_var('file://' . $uri, FILTER_VALIDATE_URL)) {
        throw new Exception('invalid uri: ' . $uri);
    }

    $parts = explode('/', $uri);

    $cookiePath = '';
    foreach ($parts as $part) {
        $cookiePath = '/'.ltrim($cookiePath.'/'.$part, '//');

        setcookie($name, '', 1, $cookiePath);

        $_domain = $domain;
        do {
            setcookie($name, '', 1, $cookiePath, $_domain);
        } while (strpos($_domain, '.') !== false && $_domain = substr($_domain, 1 + strpos($_domain, '.')));
    }
}

It is not the most pretty/safe/optimal solution, so use this only if you do not known the cookie-path and/or cookie-domain's. Or use the idea in order to create your version.

MS Access: how to compact current database in VBA

There's also Michael Kaplan's SOON ("Shut One, Open New") add-in. You'd have to chain it, but it's one way to do this.

I can't say I've had much reason to ever want to do this programatically, since I'm programming for end users, and they are never using anything but the front end in the Access user interface, and there's no reason to regularly compact a properly-designed front end.

TortoiseSVN icons not showing up under Windows 7

Changing the registry worked for me.

If its helpful to anyone, I initially prefixed "z_" to the entries in "ShellIconOverlayIdentifiers" that I wanted to move down. However that didn't seem to bring up the TortoiseSVN entries. It might be due to case sensitivity wherein lowercase "z" still precedes uppercase "T". Finally, prefixing with "Z_" instead did the trick.

How to find unused/dead code in java projects

The Structure101 slice perspective will give a list (and dependency graph) of any "orphans" or "orphan groups" of classes or packages that have no dependencies to or from the "main" cluster.

What is the Oracle equivalent of SQL Server's IsNull() function?

coalesce is supported in both Oracle and SQL Server and serves essentially the same function as nvl and isnull. (There are some important differences, coalesce can take an arbitrary number of arguments, and returns the first non-null one. The return type for isnull matches the type of the first argument, that is not true for coalesce, at least on SQL Server.)

How to get the selected radio button’s value?

Here's a nice way to get the checked radio button's value with plain JavaScript:

const form = document.forms.demo;
const checked = form.querySelector('input[name=characters]:checked');

// log out the value from the :checked radio
console.log(checked.value);

Source: https://ultimatecourses.com/blog/get-value-checked-radio-buttons

Using this HTML:

<form name="demo">
  <label>
    Mario
    <input type="radio" value="mario" name="characters" checked>
  </label>
  <label>
    Luigi
    <input type="radio" value="luigi" name="characters">
  </label>
  <label>
    Toad
    <input type="radio" value="toad" name="characters">
  </label>
</form>

You could also use Array Find the checked property to find the checked item:

Array.from(form.elements.characters).find(radio => radio.checked);

AngularJS dynamic routing

Ok solved it.

Added the solution to GitHub - http://gregorypratt.github.com/AngularDynamicRouting

In my app.js routing config:

$routeProvider.when('/pages/:name', {
    templateUrl: '/pages/home.html', 
    controller: CMSController 
});

Then in my CMS controller:

function CMSController($scope, $route, $routeParams) {

    $route.current.templateUrl = '/pages/' + $routeParams.name + ".html";

    $.get($route.current.templateUrl, function (data) {
        $scope.$apply(function () {
            $('#views').html($compile(data)($scope));
        });
    });
    ...
}
CMSController.$inject = ['$scope', '$route', '$routeParams'];

With #views being my <div id="views" ng-view></div>

So now it works with standard routing and dynamic routing.

To test it I copied about.html called it portfolio.html, changed some of it's contents and entered /#/pages/portfolio into my browser and hey presto portfolio.html was displayed....

Updated Added $apply and $compile to the html so that dynamic content can be injected.

Call a method of a controller from another controller using 'scope' in AngularJS

Here is good Demo in Fiddle how to use shared service in directive and other controllers through $scope.$on

HTML

<div ng-controller="ControllerZero">
    <input ng-model="message" >
    <button ng-click="handleClick(message);">BROADCAST</button>
</div>

<div ng-controller="ControllerOne">
    <input ng-model="message" >
</div>

<div ng-controller="ControllerTwo">
    <input ng-model="message" >
</div>

<my-component ng-model="message"></my-component>

JS

var myModule = angular.module('myModule', []);

myModule.factory('mySharedService', function($rootScope) {
    var sharedService = {};

    sharedService.message = '';

    sharedService.prepForBroadcast = function(msg) {
        this.message = msg;
        this.broadcastItem();
    };

    sharedService.broadcastItem = function() {
        $rootScope.$broadcast('handleBroadcast');
    };

    return sharedService;
});

By the same way we can use shared service in directive. We can implement controller section into directive and use $scope.$on

myModule.directive('myComponent', function(mySharedService) {
    return {
        restrict: 'E',
        controller: function($scope, $attrs, mySharedService) {
            $scope.$on('handleBroadcast', function() {
                $scope.message = 'Directive: ' + mySharedService.message;
            });
        },
        replace: true,
        template: '<input>'
    };
});

And here three our controllers where ControllerZero used as trigger to invoke prepForBroadcast

function ControllerZero($scope, sharedService) {
    $scope.handleClick = function(msg) {
        sharedService.prepForBroadcast(msg);
    };

    $scope.$on('handleBroadcast', function() {
        $scope.message = sharedService.message;
    });
}

function ControllerOne($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'ONE: ' + sharedService.message;
    });
}

function ControllerTwo($scope, sharedService) {
    $scope.$on('handleBroadcast', function() {
        $scope.message = 'TWO: ' + sharedService.message;
    });
}

The ControllerOne and ControllerTwo listen message change by using $scope.$on handler.

How can I find a file/directory that could be anywhere on linux command line?

I hope this comment will help you to find out your local & server file path using terminal

 find "$(cd ..; pwd)" -name "filename"

Or just you want to see your Current location then run

 pwd "filename"

What's the HTML to have a horizontal space between two objects?

PHP does not do styling. You need to use html or css. Take a look at http://www.w3schools.com/tags/tag_hr.asp

In HTML 4.01, the


tag represents a horizontal rule.

In HTML 4.01, the <hr> tag represents a horizontal rule.

Detect a finger swipe through JavaScript on the iPhone and Android

I had to write a simple script for a carousel to detect swipe left or right.

I utilised Pointer Events instead of Touch Events.

I hope this is useful to individuals and I welcome any insights to improve my code; I feel rather sheepish to join this thread with significantly superior JS developers.

function getSwipeX({elementId}) {

  this.e               = document.getElementsByClassName(elementId)[0];
  this.initialPosition = 0;
  this.lastPosition    = 0;
  this.threshold       = 200;
  this.diffInPosition  = null;
  this.diffVsThreshold = null;
  this.gestureState    = 0;

  this.getTouchStart = (event) => {
    event.preventDefault();
    if (window.PointerEvent) {
      this.e.setPointerCapture(event.pointerId);
    }
    return this.initalTouchPos = this.getGesturePoint(event);
  }

  this.getTouchMove  = (event) => {
    event.preventDefault();
    return this.lastPosition = this.getGesturePoint(event);
  }

  this.getTouchEnd   = (event) => {
    event.preventDefault();
    if (window.PointerEvent) {
      this.e.releasePointerCapture(event.pointerId);
    }
    this.doSomething();
    this.initialPosition = 0;
  }

  this.getGesturePoint = (event) => {
    this.point = event.pageX
    return this.point;
  }

  this.whatGestureDirection = (event) => {
    this.diffInPosition  = this.initalTouchPos - this.lastPosition;
    this.diffVsThreshold = Math.abs(this.diffInPosition) > this.threshold;
    (Math.sign(this.diffInPosition) > 0) ? this.gestureState = 'L' : (Math.sign(this.diffInPosition) < 0) ? this.gestureState = 'R' : this.gestureState = 'N';
    
    return [this.diffInPosition, this.diffVsThreshold, this.gestureState];
  }

  this.doSomething = (event) => {
    let [gestureDelta,gestureThreshold,gestureDirection] = this.whatGestureDirection();

    // USE THIS TO DEBUG
    console.log(gestureDelta,gestureThreshold,gestureDirection);

    if (gestureThreshold) {
      (gestureDirection == 'L') ? // LEFT ACTION : // RIGHT ACTION
    }
  }

  if (window.PointerEvent) {
    this.e.addEventListener('pointerdown', this.getTouchStart, true);
    this.e.addEventListener('pointermove', this.getTouchMove, true);
    this.e.addEventListener('pointerup', this.getTouchEnd, true);
    this.e.addEventListener('pointercancel', this.getTouchEnd, true);
  }
}

You can call the function using new.

window.addEventListener('load', () => {
  let test = new getSwipeX({
    elementId: 'your_div_here'
  });
})

How to stop a looping thread in Python?

I find it useful to have a class, derived from threading.Thread, to encapsulate my thread functionality. You simply provide your own main loop in an overridden version of run() in this class. Calling start() arranges for the object’s run() method to be invoked in a separate thread.

Inside the main loop, periodically check whether a threading.Event has been set. Such an event is thread-safe.

Inside this class, you have your own join() method that sets the stop event object before calling the join() method of the base class. It can optionally take a time value to pass to the base class's join() method to ensure your thread is terminated in a short amount of time.

import threading
import time

class MyThread(threading.Thread):
    def __init__(self, sleep_time=0.1):
        self._stop_event = threading.Event()
        self._sleep_time = sleep_time
        """call base class constructor"""
        super().__init__()

    def run(self):
        """main control loop"""
        while not self._stop_event.isSet():
            #do work
            print("hi")
            self._stop_event.wait(self._sleep_time)

    def join(self, timeout=None):
        """set stop event and join within a given time period"""
        self._stop_event.set()
        super().join(timeout)


if __name__ == "__main__":
    t = MyThread()
    t.start()

    time.sleep(5)

    t.join(1) #wait 1s max

Having a small sleep inside the main loop before checking the threading.Event is less CPU intensive than looping continuously. You can have a default sleep time (e.g. 0.1s), but you can also pass the value in the constructor.

Nested iframes, AKA Iframe Inception

Hey I got something that seems to be doing what you want a do. It involves some dirty copying but works. You can find the working code here

So here is the main html file :

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function(){
            Iframe = $('#frame1');

            Iframe.on('load', function(){
                IframeInner = Iframe.contents().find('iframe');

                IframeInnerClone = IframeInner.clone();

                IframeInnerClone.insertAfter($('#insertIframeAfter')).css({display:'none'});

                IframeInnerClone.on('load', function(){
                    IframeContents = IframeInner.contents();

                    YourNestedEl = IframeContents.find('div');

                    $('<div>Yeepi! I can even insert stuff!</div>').insertAfter(YourNestedEl)
                });
            });
        });
    </script>
</head>
<body>
    <div id="insertIframeAfter">Hello!!!!</div>
    <iframe id="frame1" src="Test_Iframe.html">

    </iframe>
</body>
</html>

As you can see, once the first Iframe is loaded, I get the second one and clone it. I then reinsert it in the dom, so I can get access to the onload event. Once this one is loaded, I retrieve the content from non-cloned one (must have loaded as well, since they use the same src). You can then do wathever you want with the content.

Here is the Test_Iframe.html file :

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div>Test_Iframe</div>
    <iframe src="Test_Iframe2.html">
    </iframe>
</body>
</html>

and the Test_Iframe2.html file :

<!DOCTYPE html>
<html>
<head>
</head>
<body>
    <div>I am the second nested iframe</div>
</body>
</html>

Why does only the first line of this Windows batch file execute but all three lines execute in a command shell?

Maven uses batch files to do its business. With any batch script, you must call another script using the call command so it knows to return back to your script after the called script completes. Try prepending call to all commands.

Another thing you could try is using the start command which should work similarly.

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

Add the JSON MIME type to IIS 6. Follow the directions at MSDN's Configure MIME Types (IIS 6.0).

  • Extension: .json
  • MIME type: application/json

Don't forget to restart IIS after the change.

UPDATE: There are easy ways to do this on IIS7 and newer. The op specifically asked for IIS6 help so I'm leaving this answer as-is. But this answer is still getting a lot of traffic even though IIS6 is very old now. Hopefully you're using something newer, so I wanted to mention that if you have a newer IIS7 or newer version see @ProVega's answer below for a simpler solution for those newer versions.

RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

Technically redirect should be used either if we need to transfer control to different domain or to achieve separation of task.

For example in the payment application we do the PaymentProcess first and then redirect to displayPaymentInfo. If the client refreshes the browser only the displayPaymentInfo will be done again and PaymentProcess will not be repeated. But if we use forward in this scenario, both PaymentProcess and displayPaymentInfo will be re-executed sequentially, which may result in incosistent data.

For other scenarios, forward is efficient to use since as it is faster than sendRedirect

What is thread safe or non-thread safe in PHP?

Needed background on concurrency approaches:

Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.

There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.

Needed background on how PHP "integrates" with web servers:

PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.

There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.

You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.

Now, onto your question!

Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!

At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.

Final notes

In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!

Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?> on your site and look for the Server API entry. This could say something like CGI/FastCGI or Apache 2.0 Handler.

If you also look at the command-line version of PHP -- thread safety does not matter.

Finally, if thread-safety doesn't matter so which version should you use -- the thread-safe or the non-thread-safe? Frankly, I don't have a scientific answer! But I'd guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!

How to disassemble a memory range with GDB?

gdb disassemble has a /m to include source code alongside the instructions. This is equivalent of objdump -S, with the extra benefit of confining to just the one function (or address-range) of interest.