Programs & Examples On #Dropdownextender

How can I get the current page name in WordPress?

I've now found this function on WordPress Codec,

get queried

which is a wrapper for $wp_query->get_queried_object.

This post put me in the right direction, but it seems that it needs this update.

Selecting Folder Destination in Java?

You could try something like this (as shown here: Select a Directory with a JFileChooser):

import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
import java.util.*;


public class DemoJFileChooser extends JPanel
   implements ActionListener {
   JButton go;

   JFileChooser chooser;
   String choosertitle;

  public DemoJFileChooser() {
    go = new JButton("Do it");
    go.addActionListener(this);
    add(go);
   }

  public void actionPerformed(ActionEvent e) {            
    chooser = new JFileChooser(); 
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle(choosertitle);
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    //
    // disable the "All files" option.
    //
    chooser.setAcceptAllFileFilterUsed(false);
    //    
    if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { 
      System.out.println("getCurrentDirectory(): " 
         +  chooser.getCurrentDirectory());
      System.out.println("getSelectedFile() : " 
         +  chooser.getSelectedFile());
      }
    else {
      System.out.println("No Selection ");
      }
     }

  public Dimension getPreferredSize(){
    return new Dimension(200, 200);
    }

  public static void main(String s[]) {
    JFrame frame = new JFrame("");
    DemoJFileChooser panel = new DemoJFileChooser();
    frame.addWindowListener(
      new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
          System.exit(0);
          }
        }
      );
    frame.getContentPane().add(panel,"Center");
    frame.setSize(panel.getPreferredSize());
    frame.setVisible(true);
    }
}

"Adaptive Server is unavailable or does not exist" error connecting to SQL Server from PHP

It sounds like you have a problem with your dsn or odbc data source.

Try bypassing the dsn first and connect using:

TDSVER=8.0 tsql -S *serverIPAddress* -U *username* -P *password*

If that works, you know its an issue with your dsn or with freetds using your dsn. Also, it is possible that your tds version is not compatible with your server. You might want to try other TDSVER settings (5.0, 7.0, 7.1).

DOS: find a string, if found then run another script

We have two commands, first is "condition_command", second is "result_command". If we need run "result_command" when "condition_command" is successful (errorlevel=0):

condition_command && result_command

If we need run "result_command" when "condition_command" is fail:

condition_command || result_command

Therefore for run "some_command" in case when we have "string" in the file "status.txt":

find "string" status.txt 1>nul && some_command

in case when we have not "string" in the file "status.txt":

find "string" status.txt 1>nul || some_command

PHP cURL vs file_get_contents

file_get_contents() is a simple screwdriver. Great for simple GET requests where the header, HTTP request method, timeout, cookiejar, redirects, and other important things do not matter.

fopen() with a stream context or cURL with setopt are powerdrills with every bit and option you can think of.

how to execute a scp command with the user name and password in one line

Using sshpass works best. To just include your password in scp use the ' ':

scp user1:'password'@xxx.xxx.x.5:sys_config /var/www/dev/

implements Closeable or implements AutoCloseable

The try-with-resources Statement.

The try-with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try-with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable, which includes all objects which implement java.io.Closeable, can be used as a resource.

The following example reads the first line from a file. It uses an instance of BufferedReader to read data from the file. BufferedReader is a resource that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

In this example, the resource declared in the try-with-resources statement is a BufferedReader. The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try-with-resources statement:

static String readFirstLineFromFileWithFinallyBlock(String path)
                                                     throws IOException {
    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }

}

Please refer to the docs.

How can I update npm on Windows?

The easiest way I found so far to update Node.js is using Chocolatey. Use Chocolatey to install or update the latest version of Node.js on Windows:

Step 1: First, ensure that you already have Chocolatey installed. If not, use an administrative shell to install chocolatey through cmd.exe or PowerShell.exe. For more information, visit: https://chocolatey.org/docs/installation

Step 2: Install with cmd.exe. Run the following command:

@"%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -InputFormat None -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"

To install with PowerShell.exe, visit: https://chocolatey.org/docs/installation

Step 3: Install or Update with following commands on cmd.exe (on administrative mode)

To Install Node.js: cinst nodejs.install

To Update Node.js: cup nodejs.install

Map isn't showing on Google Maps JavaScript API v3 when nested in a div tag

FIXED

Give initial height of div and specify height in percentage in your style;

#map {
   height: 100%;
}

<div id="map" style="clear:both; height:200px;"></div> 

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

What ended up working for me after a few hours of pain..

if you're running brew..

brew install ruby

in the terminal output/log, identify the path where ruby was installed, brew suggests 'You may want to add this to your PATH', so that's what we'll do. For example, mine is

/usr/local/lib/ruby/gems/3.0.0/bin

Add this to your path by running (omitting braces)

echo 'export PATH"{the_path_you_found_above}:$PATH"' >> ~/.bash_profile

then update your environment by running

source ~/.bash_profile

now, try running your install, i.e.,

sudo gem install middleman

How can I stop a While loop?

def determine_period(universe_array):
    period=0
    tmp=universe_array
    while period<12:
        tmp=apply_rules(tmp)#aplly_rules is a another function
        if numpy.array_equal(tmp,universe_array) is True:
            break 
        period+=1

    return period

Lists in ConfigParser

There is nothing stopping you from packing the list into a delimited string and then unpacking it once you get the string from the config. If you did it this way your config section would look like:

[Section 3]
barList=item1,item2

It's not pretty but it's functional for most simple lists.

Adding ID's to google map markers

Why not use an cache that stores each marker object and references an ID?

var markerCache= {};
var idGen= 0;

function codeAddress(addr, contentStr){
    // create marker
    // store
    markerCache[idGen++]= marker;
}

Edit: of course this relies on a numeric index system that doesn't offer a length property like an array. You could of course prototype the Object object and create a length, etc for just such a thing. OTOH, generating a unique ID value (MD5, etc) of each address might be the way to go.

How to inherit constructors?

Too bad we're kind of forced to tell the compiler the obvious:

Subclass(): base() {}
Subclass(int x): base(x) {}
Subclass(int x,y): base(x,y) {}

I only need to do 3 constructors in 12 subclasses, so it's no big deal, but I'm not too fond of repeating that on every subclass, after being used to not having to write it for so long. I'm sure there's a valid reason for it, but I don't think I've ever encountered a problem that requires this kind of restriction.

How to set an iframe src attribute from a variable in AngularJS

You need also $sce.trustAsResourceUrl or it won't open the website inside the iframe:

_x000D_
_x000D_
angular.module('myApp', [])_x000D_
    .controller('dummy', ['$scope', '$sce', function ($scope, $sce) {_x000D_
_x000D_
    $scope.url = $sce.trustAsResourceUrl('https://www.angularjs.org');_x000D_
_x000D_
    $scope.changeIt = function () {_x000D_
        $scope.url = $sce.trustAsResourceUrl('https://docs.angularjs.org/tutorial');_x000D_
    }_x000D_
}]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="myApp" ng-controller="dummy">_x000D_
    <iframe ng-src="{{url}}" width="300" height="200"></iframe>_x000D_
    <br>_x000D_
    <button ng-click="changeIt()">Change it</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to express a NOT IN query with ActiveRecord/Rails?

You can try something like:

Topic.find(:all, :conditions => ['forum_id not in (?)', @forums.map(&:id)])

You might need to do @forums.map(&:id).join(','). I can't remember if Rails will the argument into a CSV list if it is enumerable.

You could also do this:

# in topic.rb
named_scope :not_in_forums, lambda { |forums| { :conditions => ['forum_id not in (?)', forums.select(&:id).join(',')] }

# in your controller 
Topic.not_in_forums(@forums)

How create Date Object with values in java

tl;dr

LocalDate.of( 2014 , 2 , 11 )

If you insist on using the terrible old java.util.Date class, convert from the modern java.time classes.

java.util.Date                        // Terrible old legacy class, avoid using. Represents a moment in UTC. 
.from(                                // New conversion method added to old classes for converting between legacy classes and modern classes.
    LocalDate                         // Represents a date-only value, without time-of-day and without time zone.
    .of( 2014 , 2 , 11 )              // Specify year-month-day. Notice sane counting, unlike legacy classes: 2014 means year 2014, 1-12 for Jan-Dec.
    .atStartOfDay(                    // Let java.time determine first moment of the day. May *not* start at 00:00:00 because of anomalies such as Daylight Saving Time (DST).
        ZoneId.of( "Africa/Tunis" )   // Specify time zone as `Continent/Region`, never the 3-4 letter pseudo-zones like `PST`, `EST`, or `IST`. 
    )                                 // Returns a `ZonedDateTime`.
    .toInstant()                      // Adjust from zone to UTC. Returns a `Instant` object, always in UTC by definition.
)                                     // Returns a legacy `java.util.Date` object. Beware of possible data-loss as any microseconds or nanoseconds in the `Instant` are truncated to milliseconds in this `Date` object.   

Details

If you want "easy", you should be using the new java.time package in Java 8 rather than the notoriously troublesome java.util.Date & .Calendar classes bundled with Java.

java.time

The java.time framework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes.

Date-only

enter image description here

A LocalDate class is offered by java.time to represent a date-only value without any time-of-day or time zone. You do need a time zone to determine a date, as a new day dawns earlier in Paris than in Montréal for example. The ZoneId class is for time zones.

ZoneId zoneId = ZoneId.of( "Asia/Singapore" );
LocalDate today = LocalDate.now( zoneId );

Dump to console:

System.out.println ( "today: " + today + " in zone: " + zoneId );

today: 2015-11-26 in zone: Asia/Singapore

Or use a factory method to specify the year, month, day.

LocalDate localDate = LocalDate.of( 2014 , Month.FEBRUARY , 11 );

localDate: 2014-02-11

Or pass a month number 1-12 rather than a DayOfWeek enum object.

LocalDate localDate = LocalDate.of( 2014 , 2 , 11 );

Time zone

enter image description here

A LocalDate has no real meaning until you adjust it into a time zone. In java.time, we apply a time zone to generate a ZonedDateTime object. That also means a time-of-day, but what time? Usually makes sense to go with first moment of the day. You might think that means the time 00:00:00.000, but not always true because of Daylight Saving Time (DST) and perhaps other anomalies. Instead of assuming that time, we ask java.time to determine the first moment of the day by calling atStartOfDay.

Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId zoneId = ZoneId.of( "Asia/Singapore" );
ZonedDateTime zdt = localDate.atStartOfDay( zoneId );

zdt: 2014-02-11T00:00+08:00[Asia/Singapore]

UTC

enter image description here

For back-end work (business logic, database, data storage & exchange) we usually use UTC time zone. In java.time, the Instant class represents a moment on the timeline in UTC. An Instant object can be extracted from a ZonedDateTime by calling toInstant.

Instant instant = zdt.toInstant();

instant: 2014-02-10T16:00:00Z

Convert

You should avoid using java.util.Date class entirely. But if you must interoperate with old code not yet updated for java.time, you can convert back-and-forth. Look to new conversion methods added to the old classes.

java.util.Date d = java.util.from( instant ) ;

…and…

Instant instant = d.toInstant() ;

Table of all date-time types in Java, both modern and legacy


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?


UPDATE: The Joda-Time library is now in maintenance mode, and advises migration to the java.time classes. I am leaving this section in place for history.

Joda-Time

For one thing, Joda-Time uses sensible numbering so February is 2 not 1. Another thing, a Joda-Time DateTime truly knows its assigned time zone unlike a java.util.Date which seems to have time zone but does not.

And don't forget the time zone. Otherwise you'll be getting the JVM’s default.

DateTimeZone timeZone = DateTimeZone.forID( "Asia/Singapore" );
DateTime dateTimeSingapore = new DateTime( 2014, 2, 11, 0, 0, timeZone );
DateTime dateTimeUtc = dateTimeSingapore.withZone( DateTimeZone.UTC );

java.util.Locale locale = new java.util.Locale( "ms", "SG" ); // Language: Bahasa Melayu (?). Country: Singapore.
String output = DateTimeFormat.forStyle( "FF" ).withLocale( locale ).print( dateTimeSingapore );

Dump to console…

System.out.println( "dateTimeSingapore: " + dateTimeSingapore );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "output: " + output );

When run…

dateTimeSingapore: 2014-02-11T00:00:00.000+08:00
dateTimeUtc: 2014-02-10T16:00:00.000Z
output: Selasa, 2014 Februari 11 00:00:00 SGT

Conversion

If you need to convert to a java.util.Date for use with other classes…

java.util.Date date = dateTimeSingapore.toDate();

Change the location of the ~ directory in a Windows install of Git Bash

In my case, all I had to do was add the following User variable on Windows:

Variable name: HOME
Variable value: %USERPROFILE%

How to set a Environment Variable (You can use the User variables for username section if you are not a system administrator)

How do I reference a local image in React?

You need to wrap you image source path within {}

<img src={'path/to/one.jpeg'} />

You need to use require if using webpack

<img src={require('path/to/one.jpeg')} />

arranging div one below the other

If you want the two divs to be displayed one above the other, the simplest answer is to remove the float: left;from the css declaration, as this causes them to collapse to the size of their contents (or the css defined size), and, well float up against each other.

Alternatively, you could simply add clear:both; to the divs, which will force the floated content to clear previous floats.

.gitignore after commit

I had to remove .idea and target folders and after reading all comments this worked for me:

git rm -r .idea
git rm -r target
git commit -m 'removed .idea folder'

and then push to master

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

I found the answer, and in spite of what I reported, it was NOT browser specific. The bug was in my function code, and would have occurred in any browser. It boils down to this. I had two lines in my code that were FireFox/FireBug specific. They used console.log. In IE, they threw an error, so I commented them out (or so I thought). I did a crappy job commenting them out, and broke the bracketing in my function.

Original Code (with console.log in it):

if (sxti.length <= 50) console.log('sxti=' + sxti);
if (sxph.length <= 50) console.log('sxph=' + sxph);

Broken Code (misplaced brackets inside comments):

if (sxti.length <= 50) { //console.log('sxti=' + sxti); }
if (sxph.length <= 50) { //console.log('sxph=' + sxph); }

Fixed Code (fixed brackets outside comments):

if (sxti.length <= 50) { }//console.log('sxti=' + sxti);
if (sxph.length <= 50) { }//console.log('sxph=' + sxph);

So, it was my own sloppy coding. The function really wasn't defined, because a syntax error kept it from being closed.

Oh well, live and learn. ;)

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

No it is not possible, hence your runtime error.

But you can assign an instance of a derived class to a variable of base class type.

Getting Access Denied when calling the PutObject operation with bucket-level permission

I encountered the same issue. My bucket was private and had KMS encryption. I was able to resolve this issue by putting in additional KMS permissions in the role. The following list is the bare minimum set of roles needed.

{
  "Version": "2012-10-17",
  "Statement": [
    {
        "Sid": "AllowAttachmentBucketWrite",
        "Effect": "Allow",
        "Action": [
            "s3:PutObject",
            "kms:Decrypt",
            "s3:AbortMultipartUpload",
            "kms:Encrypt",
            "kms:GenerateDataKey"
        ],
        "Resource": [
            "arn:aws:s3:::bucket-name/*",
            "arn:aws:kms:kms-key-arn"
        ]
    }
  ]
}

Reference: https://aws.amazon.com/premiumsupport/knowledge-center/s3-large-file-encryption-kms-key/

seek() function?

Regarding seek() there's not too much to worry about.

First of all, it is useful when operating over an open file.

It's important to note that its syntax is as follows:

fp.seek(offset, from_what)

where fp is the file pointer you're working with; offset means how many positions you will move; from_what defines your point of reference:

  • 0: means your reference point is the beginning of the file
  • 1: means your reference point is the current file position
  • 2: means your reference point is the end of the file

if omitted, from_what defaults to 0.

Never forget that when managing files, there'll always be a position inside that file where you are currently working on. When just open, that position is the beginning of the file, but as you work with it, you may advance.
seek will be useful to you when you need to walk along that open file, just as a path you are traveling into.

Check folder size in Bash

if you just want to see the folder size and not the sub-folders, you can use:

du -hs /path/to/directory

Update:

You should know that du shows the used disk space; and not the file size.

You can use --apparent-size if u want to see sum of actual file sizes.

--apparent-size
      print  apparent  sizes,  rather  than  disk  usage; although the apparent size is usually smaller, it may be larger due to holes in ('sparse')
      files, internal fragmentation, indirect blocks, and the like

And of course theres no need for -h (Human readable) option inside a script.

Instead You can use -b for easier comparison inside script.

But You should Note that -b applies --apparent-size by itself. And it might not be what you need.

-b, --bytes
      equivalent to '--apparent-size --block-size=1'

so I think, you should use --block-size or -B

#!/bin/bash
SIZE=$(du -B 1 /path/to/directory | cut -f 1 -d "   ")    
# 2GB = 2147483648 bytes
# 10GB = 10737418240 bytes
if [[ $SIZE -gt 2147483648 && $SIZE -lt 10737418240 ]]; then
    echo 'Condition returned True'
fi

Plot multiple columns on the same graph in R

A very simple solution:

df <- read.csv("df.csv",sep=",",head=T)
x <- cbind(df$Xax,df$Xax,df$Xax,df$Xax)
y <- cbind(df$A,df$B,df$C,df$D)
matplot(x,y,type="p")

please note it just plots the data and it does not plot any regression line.

What's the UIScrollView contentInset property for?

Content insets solve the problem of having content that goes underneath other parts of the User Interface and yet still remains reachable using scroll bars. In other words, the purpose of the Content Inset is to make the interaction area smaller than its actual area.

Consider the case where we have three logical areas of the screen:

TOP BUTTONS

TEXT

BOTTOM TAB BAR

and we want the TEXT to never appear transparently underneath the TOP BUTTONS, but we want the Text to appear underneath the BOTTOM TAB BAR and yet still allow scrolling so we could update the text sitting transparently under the BOTTOM TAB BAR.

Then we would set the top origin to be below the TOP BUTTONS, and the height to include the bottom of BOTTOM TAB BAR. To gain access to the Text sitting underneath the BOTTOM TAB BAR content we would set the bottom inset to be the height of the BOTTOM TAB BAR.

Without the inset, the scroller would not let you scroll up the content enough to type into it. With the inset, it is as if the content had extra "BLANK CONTENT" the size of the content inset. Blank text has been "inset" into the real "content" -- that's how I remember the concept.

What Regex would capture everything from ' mark to the end of a line?

In your example I'd go for the following pattern:

'([^\n]+)$

use multiline and global options to match all occurences.

To include the linefeed in the match you could use:

'[^\n]+\n

But this might miss the last line if it has no linefeed.

For a single line, if you don't need to match the linefeed I'd prefer to use:

'[^$]+$

Formatting Numbers by padding with leading zeros in SQL Server

I am posting all at one place, all works for me to pad with 4 leading zero :)

declare @number int =  1;
print right('0000' + cast(@number as varchar(4)) , 4)
print right('0000' + convert(varchar(4), @number) , 4)
print right(replicate('0',4) + convert(varchar(4), @number) , 4)
print  cast(replace(str(@number,4),' ','0')as char(4))
print format(@number,'0000')

Maven2: Missing artifact but jars are in place

If the other solutions didn't work and you know the correct jars are in your repository then:

The problem is that eclipse caches the errors for some reason.

I solved this problem by deleting the errors in the Problems tab and then I refreshed the project explorer and all the exclamation points and errors never returned.

How to read pdf file and write it to outputStream

import java.io.*;


public class FileRead {


    public static void main(String[] args) throws IOException {


        File f=new File("C:\\Documents and Settings\\abc\\Desktop\\abc.pdf");

        OutputStream oos = new FileOutputStream("test.pdf");

        byte[] buf = new byte[8192];

        InputStream is = new FileInputStream(f);

        int c = 0;

        while ((c = is.read(buf, 0, buf.length)) > 0) {
            oos.write(buf, 0, c);
            oos.flush();
        }

        oos.close();
        System.out.println("stop");
        is.close();

    }

}

The easiest way so far. Hope this helps.

How to remove white space characters from a string in SQL Server

Looks like the invisible character -

ALT+255

Try this

select REPLACE(ProductAlternateKey, ' ', '@')
--type ALT+255 instead of space for the second expression in REPLACE 
from DimProducts
where ProductAlternateKey  like '46783815%'

Raj

Edit: Based on ASCII() results, try ALT+10 - use numeric keypad

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

The issue here is that you just Added the reference to System.IO.Compression it is missing the reference to System.IO.Compression.Filesystem.dll

And you need to do it on .net 4.5 or later (because it doesn't exist on older versions).

I just posted a script on TechNet Maybe somebody would find it useful it requires .net 4.5 or 4.7

https://gallery.technet.microsoft.com/scriptcenter/Create-a-Zip-file-from-a-b23a7530

Fill remaining vertical space - only CSS

All you need is a bit of improved markup. Wrap the second within the first and it will render under.

<div id="wrapper">
    <div id="first">
        Here comes the first content
        <div id="second">I will render below the first content</div>
    </div>
</div>

Demo

Best way to implement multi-language/globalization in large .NET project

Use a separate project with Resources

I can tell this from out experience, having a current solution with 12 24 projects that includes API, MVC, Project Libraries (Core functionalities), WPF, UWP and Xamarin. It is worth reading this long post as I think it is the best way to do so. With the help of VS tools easily exportable and importable to sent to translation agencies or review by other people.

EDIT 02/2018: Still going strong, converting it to a .NET Standard library makes it possible to even use it across .NET Framework and NET Core. I added an extra section for converting it to JSON so for example angular can use it.

EDIT 2019: Going forward with Xamarin, this still works across all platforms. E.g. Xamarin.Forms advices to use resx files as well. (I did not develop an app in Xamarin.Forms yet, but the documentation, that is way to detailed to just get started, covers it: Xamarin.Forms Documentation). Just like converting it to JSON we can also convert it to a .xml file for Xamarin.Android.

EDIT 2019 (2): While upgrading to UWP from WPF, I encountered that in UWP they prefer to use another filetype .resw, which is is in terms of content identical but the usage is different. I found a different way of doing this which, in my opinion, works better then the default solution.

EDIT 2020: Updated some suggestions for larger (modulair) projects that might require multiple language projects.

So, lets get to it.

Pro's

  • Strongly typed almost everywhere.
  • In WPF you don't have to deal with ResourceDirectories.
  • Supported for ASP.NET, Class Libraries, WPF, Xamarin, .NET Core, .NET Standard as far as I have tested.
  • No extra third-party libraries needed.
  • Supports culture fallback: en-US -> en.
  • Not only back-end, works also in XAML for WPF and Xamarin.Forms, in .cshtml for MVC.
  • Easily manipulate the language by changing the Thread.CurrentThread.CurrentCulture
  • Search engines can Crawl in different languages and user can send or save language-specific urls.

Con's

  • WPF XAML is sometimes buggy, newly added strings don't show up directly. Rebuild is the temp fix (vs2015).
  • UWP XAML does not show intellisense suggestions and does not show the text while designing.
  • Tell me.

Setup

Create language project in your solution, give it a name like MyProject.Language. Add a folder to it called Resources, and in that folder, create two Resources files (.resx). One called Resources.resx and another called Resources.en.resx (or .en-GB.resx for specific). In my implementation, I have NL (Dutch) language as the default language, so that goes in my first file, and English goes in my second file.

Setup should look like this:

language setup project

The properties for Resources.resx must be: properties

Make sure that the custom tool namespace is set to your project namespace. Reason for this is that in WPF, you cannot reference to Resources inside XAML.

And inside the resource file, set the access modifier to Public:

access modifier

If you have such a large application (let's say different modules) you can consider creating multiple projects like above. In that case you could prefix your Keys and resource classes with the particular Module. Use the best language editor there is for Visual Studio to combine all files into a single overview.

Using in another project

Reference to your project: Right click on References -> Add Reference -> Prjects\Solutions.

Use namespace in a file: using MyProject.Language;

Use it like so in back-end: string someText = Resources.orderGeneralError; If there is something else called Resources, then just put in the entire namespace.

Using in MVC

In MVC you can do however you like to set the language, but I used parameterized url's, which can be setup like so:

RouteConfig.cs Below the other mappings

routes.MapRoute(
    name: "Locolized",
    url: "{lang}/{controller}/{action}/{id}",
    constraints: new { lang = @"(\w{2})|(\w{2}-\w{2})" },   // en or en-US
    defaults: new { controller = "shop", action = "index", id = UrlParameter.Optional }
);

FilterConfig.cs (might need to be added, if so, add FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); to the Application_start() method in Global.asax

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new ErrorHandler.AiHandleErrorAttribute());
        //filters.Add(new HandleErrorAttribute());
        filters.Add(new LocalizationAttribute("nl-NL"), 0);
    }
}

LocalizationAttribute

public class LocalizationAttribute : ActionFilterAttribute
{
    private string _DefaultLanguage = "nl-NL";
    private string[] allowedLanguages = { "nl", "en" };

    public LocalizationAttribute(string defaultLanguage)
    {
        _DefaultLanguage = defaultLanguage;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string lang = (string) filterContext.RouteData.Values["lang"] ?? _DefaultLanguage;
        LanguageHelper.SetLanguage(lang);
    }
}

LanguageHelper just sets the Culture info.

//fixed number and date format for now, this can be improved.
public static void SetLanguage(LanguageEnum language)
{
    string lang = "";
    switch (language)
    {
        case LanguageEnum.NL:
            lang = "nl-NL";
            break;
        case LanguageEnum.EN:
            lang = "en-GB";
            break;
        case LanguageEnum.DE:
            lang = "de-DE";
            break;
    }
    try
    {
        NumberFormatInfo numberInfo = CultureInfo.CreateSpecificCulture("nl-NL").NumberFormat;
        CultureInfo info = new CultureInfo(lang);
        info.NumberFormat = numberInfo;
        //later, we will if-else the language here
        info.DateTimeFormat.DateSeparator = "/";
        info.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
        Thread.CurrentThread.CurrentUICulture = info;
        Thread.CurrentThread.CurrentCulture = info;
    }
    catch (Exception)
    {

    }
}

Usage in .cshtml

@using MyProject.Language;
<h3>@Resources.w_home_header</h3>

or if you don't want to define usings then just fill in the entire namespace OR you can define the namespace under /Views/web.config:

<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    ...
    <add namespace="MyProject.Language" />
  </namespaces>
</pages>
</system.web.webPages.razor>

This mvc implementation source tutorial: Awesome tutorial blog

Using in class libraries for models

Back-end using is the same, but just an example for using in attributes

using MyProject.Language;
namespace MyProject.Core.Models
{
    public class RegisterViewModel
    {
        [Required(ErrorMessageResourceName = "accountEmailRequired", ErrorMessageResourceType = typeof(Resources))]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }
    }
}

If you have reshaper it will automatically check if the given resource name exists. If you prefer type safety you can use T4 templates to generate an enum

Using in WPF.

Ofcourse add a reference to your MyProject.Language namespace, we know how to use it in back-end.

In XAML, inside the header of a Window or UserControl, add a namespace reference called lang like so:

<UserControl x:Class="Babywatcher.App.Windows.Views.LoginView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:MyProject.App.Windows.Views"
              xmlns:lang="clr-namespace:MyProject.Language;assembly=MyProject.Language" <!--this one-->
             mc:Ignorable="d" 
            d:DesignHeight="210" d:DesignWidth="300">

Then, inside a label:

    <Label x:Name="lblHeader" Content="{x:Static lang:Resources.w_home_header}" TextBlock.FontSize="20" HorizontalAlignment="Center"/>

Since it is strongly typed you are sure the resource string exists. You might need to recompile the project sometimes during setup, WPF is sometimes buggy with new namespaces.

One more thing for WPF, set the language inside the App.xaml.cs. You can do your own implementation (choose during installation) or let the system decide.

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        SetLanguageDictionary();
    }

    private void SetLanguageDictionary()
    {
        switch (Thread.CurrentThread.CurrentCulture.ToString())
        {
            case "nl-NL":
                MyProject.Language.Resources.Culture = new System.Globalization.CultureInfo("nl-NL");
                break;
            case "en-GB":
                MyProject.Language.Resources.Culture = new System.Globalization.CultureInfo("en-GB");
                break;
            default://default english because there can be so many different system language, we rather fallback on english in this case.
                MyProject.Language.Resources.Culture = new System.Globalization.CultureInfo("en-GB");
                break;
        }
       
    }
}

Using in UWP

In UWP, Microsoft uses this solution, meaning you will need to create new resource files. Plus you can not re-use the text either because they want you to set the x:Uid of your control in XAML to a key in your resources. And in your resources you have to do Example.Text to fill a TextBlock's text. I didn't like that solution at all because I want to re-use my resource files. Eventually I came up with the following solution. I just found this out today (2019-09-26) so I might come back with something else if it turns out this doesn't work as desired.

Add this to your project:

using Windows.UI.Xaml.Resources;

public class MyXamlResourceLoader : CustomXamlResourceLoader
{
    protected override object GetResource(string resourceId, string objectType, string propertyName, string propertyType)
    {
        return MyProject.Language.Resources.ResourceManager.GetString(resourceId);
    }
}

Add this to App.xaml.cs in the constructor:

CustomXamlResourceLoader.Current = new MyXamlResourceLoader();

Where ever you want to in your app, use this to change the language:

ApplicationLanguages.PrimaryLanguageOverride = "nl";
Frame.Navigate(this.GetType());

The last line is needed to refresh the UI. While I am still working on this project I noticed that I needed to do this 2 times. I might end up with a language selection at the first time the user is starting. But since this will be distributed via Windows Store, the language is usually equal to the system language.

Then use in XAML:

<TextBlock Text="{CustomResource ExampleResourceKey}"></TextBlock>

Using it in Angular (convert to JSON)

Now days it is more common to have a framework like Angular in combination with components, so without cshtml. Translations are stored in json files, I am not going to cover how that works, I would just highly recommend ngx-translate instead of the angular multi-translation. So if you want to convert translations to a JSON file, it is pretty easy, I use a T4 template script that converts the Resources file to a json file. I recommend installing T4 editor to read the syntax and use it correctly because you need to do some modifications.

Only 1 thing to note: It is not possible to generate the data, copy it, clean the data and generate it for another language. So you have to copy below code as many times as languages you have and change the entry before '//choose language here'. Currently no time to fix this but probably will update later (if interested).

Path: MyProject.Language/T4/CreateLocalizationEN.tt

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Resources" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.ComponentModel.Design" #>
<#@ output extension=".json" #>
<#


var fileNameNl = "../Resources/Resources.resx";
var fileNameEn = "../Resources/Resources.en.resx";
var fileNameDe = "../Resources/Resources.de.resx";
var fileNameTr = "../Resources/Resources.tr.resx";

var fileResultName = "../T4/CreateLocalizationEN.json";//choose language here
var fileResultPath = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath("")), "MyProject.Language", fileResultName);
//var fileDestinationPath = "../../MyProject.Web/ClientApp/app/i18n/";

var fileNameDestNl = "nl.json";
var fileNameDestEn = "en.json";
var fileNameDestDe = "de.json";
var fileNameDestTr = "tr.json";

var pathBaseDestination = Directory.GetParent(Directory.GetParent(this.Host.ResolvePath("")).ToString()).ToString();

string[] fileNamesResx = new string[] {fileNameEn }; //choose language here
string[] fileNamesDest = new string[] {fileNameDestEn }; //choose language here

for(int x = 0; x < fileNamesResx.Length; x++)
{
    var currentFileNameResx = fileNamesResx[x];
    var currentFileNameDest = fileNamesDest[x];
    var currentPathResx = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath("")), "MyProject.Language", currentFileNameResx);
    var currentPathDest =pathBaseDestination + "/MyProject.Web/ClientApp/app/i18n/" + currentFileNameDest;
    using(var reader = new ResXResourceReader(currentPathResx))
    {
        reader.UseResXDataNodes = true;
#>
        {
<#
            foreach(DictionaryEntry entry in reader)
            {
                var name = entry.Key;
                var node = (ResXDataNode)entry.Value;
                var value = node.GetValue((ITypeResolutionService) null); 
                 if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("\n", "");
                 if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("\r", "");
#>
            "<#=name#>": "<#=value#>",
<#

    
            }
#>
        "WEBSHOP_LASTELEMENT": "just ignore this, for testing purpose"
        }
<#
    }
    File.Copy(fileResultPath, currentPathDest, true);
}


#>

If you have a modulair application and you followed my suggestion to create multiple language projects, then you will have to create a T4 file for each of them. Make sure the json files are logically defined, it doesn't have to be en.json, it can also be example-en.json. To combine multiple json files for using with ngx-translate, follow the instructions here

Use in Xamarin.Android

As explained above in the updates, I use the same method as I have done with Angular/JSON. But Android uses XML files, so I wrote a T4 file that generates those XML files.

Path: MyProject.Language/T4/CreateAppLocalizationEN.tt

#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Resources" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.ComponentModel.Design" #>
<#@ output extension=".xml" #>
<#
var fileName = "../Resources/Resources.en.resx";
var fileResultName = "../T4/CreateAppLocalizationEN.xml";
var fileResultRexPath = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath("")), "MyProject.Language", fileName);
var fileResultPath = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath("")), "MyProject.Language", fileResultName);

    var fileNameDest = "strings.xml";

    var pathBaseDestination = Directory.GetParent(Directory.GetParent(this.Host.ResolvePath("")).ToString()).ToString();

    var currentPathDest =pathBaseDestination + "/MyProject.App.AndroidApp/Resources/values-en/" + fileNameDest;

    using(var reader = new ResXResourceReader(fileResultRexPath))
    {
        reader.UseResXDataNodes = true;
        #>
        <resources>
        <#

                foreach(DictionaryEntry entry in reader)
                {
                    var name = entry.Key;
                    //if(!name.ToString().Contains("WEBSHOP_") && !name.ToString().Contains("DASHBOARD_"))//only include keys with these prefixes, or the country ones.
                    //{
                    //  if(name.ToString().Length != 2)
                    //  {
                    //      continue;
                    //  }
                    //}
                    var node = (ResXDataNode)entry.Value;
                    var value = node.GetValue((ITypeResolutionService) null); 
                     if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("\n", "");
                     if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("\r", "");
                     if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("&", "&amp;");
                     if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("<<", "");
                     //if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("'", "\'");
#>
              <string name="<#=name#>">"<#=value#>"</string>
<#      
                }
#>
            <string name="WEBSHOP_LASTELEMENT">just ignore this</string>
<#
        #>
        </resources>
        <#
        File.Copy(fileResultPath, currentPathDest, true);
    }

#>

Android works with values-xx folders, so above is for English for in the values-en folder. But you also have to generate a default which goes into the values folder. Just copy above T4 template and change the folder in the above code.

There you go, you can now use one single resource file for all your projects. This makes it very easy exporting everything to an excl document and let someone translate it and import it again.

Special thanks to this amazing VS extension which works awesome with resx files. Consider donating to him for his awesome work (I have nothing to do with that, I just love the extension).

swift UITableView set rowHeight

Problem Cause:
The problem is that the cell has not been created yet. TableView first calculates the height for row and then populates the data for each row, so the rows array has not been created when heightForRow method gets called. So your app is trying to access a memory location which it does not have the permission to and therefor you get the EXC_BAD_ACCESS message.

How to achieve self sizing TableViewCell in UITableView:
Just set proper constraints for your views contained in TableViewCell's view in StoryBoard. Remember you shouldn't set height constraints to TableViewCell's root view, its height should be properly computable by the height of its subviews -- This is like what you do to set proper constraints for UIScrollView. This way your cells will get different heights according to their subviews. No additional action needed

How to convert a JSON string to a dictionary?

Details

  • Xcode Version 10.3 (10G8), Swift 5

Solution

import Foundation

// MARK: - CastingError

struct CastingError: Error {
    let fromType: Any.Type
    let toType: Any.Type
    init<FromType, ToType>(fromType: FromType.Type, toType: ToType.Type) {
        self.fromType = fromType
        self.toType = toType
    }
}

extension CastingError: LocalizedError {
    var localizedDescription: String { return "Can not cast from \(fromType) to \(toType)" }
}

extension CastingError: CustomStringConvertible { var description: String { return localizedDescription } }

// MARK: - Data cast extensions

extension Data {
    func toDictionary(options: JSONSerialization.ReadingOptions = []) throws -> [String: Any] {
        return try to(type: [String: Any].self, options: options)
    }

    func to<T>(type: T.Type, options: JSONSerialization.ReadingOptions = []) throws -> T {
        guard let result = try JSONSerialization.jsonObject(with: self, options: options) as? T else {
            throw CastingError(fromType: type, toType: T.self)
        }
        return result
    }
}

// MARK: - String cast extensions

extension String {
    func asJSON<T>(to type: T.Type, using encoding: String.Encoding = .utf8) throws -> T {
        guard let data = data(using: encoding) else { throw CastingError(fromType: type, toType: T.self) }
        return try data.to(type: T.self)
    }

    func asJSONToDictionary(using encoding: String.Encoding = .utf8) throws -> [String: Any] {
        return try asJSON(to: [String: Any].self, using: encoding)
    }
}

// MARK: - Dictionary cast extensions

extension Dictionary {
    func toData(options: JSONSerialization.WritingOptions = []) throws -> Data {
        return try JSONSerialization.data(withJSONObject: self, options: options)
    }
}

Usage

let value1 = try? data.toDictionary()
let value2 = try? data.to(type: [String: Any].self)
let value3 = try? data.to(type: [String: String].self)
let value4 = try? string.asJSONToDictionary()
let value5 = try? string.asJSON(to: [String: String].self)

Test sample

Do not forget to paste the solution code here

func testDescriber(text: String, value: Any) {
    print("\n//////////////////////////////////////////")
    print("-- \(text)\n\n  type: \(type(of: value))\n  value: \(value)")
}

let json1: [String: Any] = ["key1" : 1, "key2": true, "key3" : ["a": 1, "b": 2], "key4": [1,2,3]]
var jsonData = try? json1.toData()
testDescriber(text: "Sample test of func toDictionary()", value: json1)
if let data = jsonData {
    print("  Result: \(String(describing: try? data.toDictionary()))")
}

testDescriber(text: "Sample test of func to<T>() -> [String: Any]", value: json1)
if let data = jsonData {
    print("  Result: \(String(describing: try? data.to(type: [String: Any].self)))")
}

testDescriber(text: "Sample test of func to<T>() -> [String] with cast error", value: json1)
if let data = jsonData {
    do {
        print("  Result: \(String(describing: try data.to(type: [String].self)))")
    } catch {
        print("  ERROR: \(error)")
    }
}

let array = [1,4,5,6]
testDescriber(text: "Sample test of func to<T>() -> [Int]", value: array)
if let data = try? JSONSerialization.data(withJSONObject: array) {
    print("  Result: \(String(describing: try? data.to(type: [Int].self)))")
}

let json2 = ["key1": "a", "key2": "b"]
testDescriber(text: "Sample test of func to<T>() -> [String: String]", value: json2)
if let data = try? JSONSerialization.data(withJSONObject: json2) {
    print("  Result: \(String(describing: try? data.to(type: [String: String].self)))")
}

let jsonString = "{\"key1\": \"a\", \"key2\": \"b\"}"
testDescriber(text: "Sample test of func to<T>() -> [String: String]", value: jsonString)
print("  Result: \(String(describing: try? jsonString.asJSON(to: [String: String].self)))")

testDescriber(text: "Sample test of func to<T>() -> [String: String]", value: jsonString)
print("  Result: \(String(describing: try? jsonString.asJSONToDictionary()))")

let wrongJsonString = "{\"key1\": \"a\", \"key2\":}"
testDescriber(text: "Sample test of func to<T>() -> [String: String] with JSONSerialization error", value: jsonString)
do {
    let json = try wrongJsonString.asJSON(to: [String: String].self)
    print("  Result: \(String(describing: json))")
} catch {
    print("  ERROR: \(error)")
}

Test log

//////////////////////////////////////////
-- Sample test of func toDictionary()

  type: Dictionary<String, Any>
  value: ["key4": [1, 2, 3], "key2": true, "key3": ["a": 1, "b": 2], "key1": 1]
  Result: Optional(["key4": <__NSArrayI 0x600002a35380>(
1,
2,
3
)
, "key2": 1, "key3": {
    a = 1;
    b = 2;
}, "key1": 1])

//////////////////////////////////////////
-- Sample test of func to<T>() -> [String: Any]

  type: Dictionary<String, Any>
  value: ["key4": [1, 2, 3], "key2": true, "key3": ["a": 1, "b": 2], "key1": 1]
  Result: Optional(["key4": <__NSArrayI 0x600002a254d0>(
1,
2,
3
)
, "key2": 1, "key1": 1, "key3": {
    a = 1;
    b = 2;
}])

//////////////////////////////////////////
-- Sample test of func to<T>() -> [String] with cast error

  type: Dictionary<String, Any>
  value: ["key4": [1, 2, 3], "key2": true, "key3": ["a": 1, "b": 2], "key1": 1]
  ERROR: Can not cast from Array<String> to Array<String>

//////////////////////////////////////////
-- Sample test of func to<T>() -> [Int]

  type: Array<Int>
  value: [1, 4, 5, 6]
  Result: Optional([1, 4, 5, 6])

//////////////////////////////////////////
-- Sample test of func to<T>() -> [String: String]

  type: Dictionary<String, String>
  value: ["key1": "a", "key2": "b"]
  Result: Optional(["key1": "a", "key2": "b"])

//////////////////////////////////////////
-- Sample test of func to<T>() -> [String: String]

  type: String
  value: {"key1": "a", "key2": "b"}
  Result: Optional(["key1": "a", "key2": "b"])

//////////////////////////////////////////
-- Sample test of func to<T>() -> [String: String]

  type: String
  value: {"key1": "a", "key2": "b"}
  Result: Optional(["key1": a, "key2": b])

//////////////////////////////////////////
-- Sample test of func to<T>() -> [String: String] with JSONSerialization error

  type: String
  value: {"key1": "a", "key2": "b"}
  ERROR: Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around character 21." UserInfo={NSDebugDescription=Invalid value around character 21.}

Debug/run standard java in Visual Studio Code IDE and OS X?

I can tell you for Windows.

  1. Install Java Extension Pack and Code Runner Extension from VS Code Extensions.

  2. Edit your java home location in VS Code settings, "java.home": "C:\\Program Files\\Java\\jdk-9.0.4".

  3. Check if javac is recognized in VS Code internal terminal. If this check fails, try opening VS Code as administrator.

  4. Create a simple Java program in Main.java file as:

public class Main {
    public static void main(String[] args) {
        System.out.println("Hello world");     
    }
}

Note: Do not add package in your main class.

  1. Right click anywhere on the java file and select run code.

  2. Check the output in the console.

Done, hope this helps.

how to get the selected index of a drop down

If you are actually looking for the index number (and not the value) of the selected option then it would be

document.forms[0].elements["CCards"].selectedIndex 
/* You may need to change document.forms[0] to reference the correct form */

or using jQuery

$('select[name="CCards"]')[0].selectedIndex 

CUDA incompatible with my gcc version

gcc 4.5 and 4.6 are not supported with CUDA - code won't compile and the rest of the toolchain, including cuda-gdb, won't work properly. You cannot use them, and the restriction is non-negotiable.

Your only solution is to install a gcc 4.4 version as a second compiler (most distributions will allow that). There is an option to nvcc --compiler-bindir which can be used to point to an alternative compiler. Create a local directory and then make symbolic links to the supported gcc version executables. Pass that local directory to nvcc via the --compiler-bindir option, and you should be able to compile CUDA code without affecting the rest of your system.


EDIT:

Note that this question, and answer, pertain to CUDA 4.

Since it was written, NVIDIA has continued to expand support for later gcc versions in newer CUDA toolchain release

  • As of the CUDA 4.1 release, gcc 4.5 is now supported. gcc 4.6 and 4.7 are unsupported.
  • As of the CUDA 5.0 release, gcc 4.6 is now supported. gcc 4.7 is unsupported.
  • As of the CUDA 6.0 release, gcc 4.7 is now supported.
  • As of the CUDA 7.0 release, gcc 4.8 is fully supported, with 4.9 support on Ubuntu 14.04 and Fedora 21.
  • As of the CUDA 7.5 release, gcc 4.8 is fully supported, with 4.9 support on Ubuntu 14.04 and Fedora 21.
  • As of the CUDA 8 release, gcc 5.3 is fully supported on Ubuntu 16.06 and Fedora 23.
  • As of the CUDA 9 release, gcc 6 is fully supported on Ubuntu 16.04, Ubuntu 17.04 and Fedora 25.
  • The CUDA 9.2 release adds support for gcc 7
  • The CUDA 10.1 release adds support for gcc 8
  • The CUDA 10.2 release continues support for gcc 8
  • The CUDA 11.0 release adds support for gcc 9 on Ubuntu 20.04
  • The CUDA 11.1 release expands gcc 9 support across most distributions and adds support for gcc 10 on Fedora linux

There is presently (as of CUDA 11.1) no gcc 10 support in CUDA other than Fedora linux

Note that NVIDIA has recently added a very useful table here which contains the supported compiler and OS matrix for the current CUDA release.

Url to a google maps page to show a pin given a latitude / longitude?

You should be able to do something like this:

http://maps.google.com/maps?q=24.197611,120.780512

Some more info on the query parameters available at this location

Here's another link to an SO thread

XmlSerializer giving FileNotFoundException at constructor

Had a similar problem in one of my .Net Standard dlls.

I used Microsoft.XmlSerializer.Generator nuget, which pre-generating XmlSerializer on .Net Core and .Net Standard.

jquery find class and get the value

var myVar = $("#start").find('.myClass').first().val();

How to invoke bash, run commands inside the new shell, and then give control back to user?

You can get the functionality you want by sourcing the script instead of running it. eg:

$cat script
cmd1
cmd2
$ . script
$ at this point cmd1 and cmd2 have been run inside this shell

How to unmerge a Git merge?

If you haven't committed the merge, then use:

git merge --abort

Set View Width Programmatically

hsThumbList.setLayoutParams(new LayoutParams(100, 400));

How do you Encrypt and Decrypt a PHP String?

In PHP, Encryption and Decryption of a string is possible using one of the Cryptography Extensions called OpenSSL function for encrypt and decrypt.

openssl_encrypt() Function: The openssl_encrypt() function is used to encrypt the data.

Syntax is as follows :

string openssl_encrypt( string $data, string $method, string $key, $options = 0, string $iv, string $tag= NULL, string $aad, int $tag_length = 16 )

Parameters are as follows :

$data: It holds the string or data which need to be encrypted.

$method: The cipher method is adopted using openssl_get_cipher_methods() function.

$key: It holds the encryption key.

$options: It holds the bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING.

$iv: It holds the initialization vector which is not NULL.

$tag: It holds the authentication tag which is passed by reference when using AEAD cipher mode (GCM or CCM).

$aad: It holds the additional authentication data.

$tag_length: It holds the length of the authentication tag. The length of authentication tag lies between 4 to 16 for GCM mode.

Return Value: It returns the encrypted string on success or FALSE on failure.

openssl_decrypt() Function The openssl_decrypt() function is used to decrypt the data.

Syntax is as follows :

string openssl_decrypt( string $data, string $method, string $key, int $options = 0, string $iv, string $tag, string $aad)

Parameters are as follows :

$data: It holds the string or data which need to be encrypted.

$method: The cipher method is adopted using openssl_get_cipher_methods() function.

$key: It holds the encryption key.

$options: It holds the bitwise disjunction of the flags OPENSSL_RAW_DATA and OPENSSL_ZERO_PADDING.

$iv: It holds the initialization vector which is not NULL.

$tag: It holds the authentication tag using AEAD cipher mode (GCM or CCM). When authentication fails openssl_decrypt() returns FALSE.

$aad: It holds the additional authentication data.

Return Value: It returns the decrypted string on success or FALSE on failure.

Approach: First declare a string and store it into variable and use openssl_encrypt() function to encrypt the given string and use openssl_decrypt() function to descrypt the given string.

You can find the examples at : https://www.geeksforgeeks.org/how-to-encrypt-and-decrypt-a-php-string/

Create component to specific module with Angular-CLI

To create a component as part of a module you should

  1. ng g module newModule to generate a module,
  2. cd newModule to change directory into the newModule folder
  3. ng g component newComponent to create a component as a child of the module.

UPDATE: Angular 9

Now it doesn't matter what folder you are in when generating the component.

  1. ng g module NewMoudle to generate a module.
  2. ng g component new-module/new-component to create NewComponent.

Note: When the Angular CLI sees new-module/new-component, it understands and translates the case to match new-module -> NewModule and new-component -> NewComponent. It can get confusing in the beginning, so easy way is to match the names in #2 with the folder names for the module and component.

How to get String Array from arrays.xml file

Your array.xml is not right. change it to like this

Here is array.xml file

<?xml version="1.0" encoding="utf-8"?>  
<resources>  
    <string-array name="testArray">  
        <item>first</item>  
        <item>second</item>  
        <item>third</item>  
        <item>fourth</item>  
        <item>fifth</item>  
   </string-array>
</resources>

How to write header row with csv.DictWriter?

A few options:

(1) Laboriously make an identity-mapping (i.e. do-nothing) dict out of your fieldnames so that csv.DictWriter can convert it back to a list and pass it to a csv.writer instance.

(2) The documentation mentions "the underlying writer instance" ... so just use it (example at the end).

dw.writer.writerow(dw.fieldnames)

(3) Avoid the csv.Dictwriter overhead and do it yourself with csv.writer

Writing data:

w.writerow([d[k] for k in fieldnames])

or

w.writerow([d.get(k, restval) for k in fieldnames])

Instead of the extrasaction "functionality", I'd prefer to code it myself; that way you can report ALL "extras" with the keys and values, not just the first extra key. What is a real nuisance with DictWriter is that if you've verified the keys yourself as each dict was being built, you need to remember to use extrasaction='ignore' otherwise it's going to SLOWLY (fieldnames is a list) repeat the check:

wrong_fields = [k for k in rowdict if k not in self.fieldnames]

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

>>> f = open('csvtest.csv', 'wb')
>>> import csv
>>> fns = 'foo bar zot'.split()
>>> dw = csv.DictWriter(f, fns, restval='Huh?')
# dw.writefieldnames(fns) -- no such animal
>>> dw.writerow(fns) # no such luck, it can't imagine what to do with a list
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\python26\lib\csv.py", line 144, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "C:\python26\lib\csv.py", line 141, in _dict_to_list
    return [rowdict.get(key, self.restval) for key in self.fieldnames]
AttributeError: 'list' object has no attribute 'get'
>>> dir(dw)
['__doc__', '__init__', '__module__', '_dict_to_list', 'extrasaction', 'fieldnam
es', 'restval', 'writer', 'writerow', 'writerows']
# eureka
>>> dw.writer.writerow(dw.fieldnames)
>>> dw.writerow({'foo':'oof'})
>>> f.close()
>>> open('csvtest.csv', 'rb').read()
'foo,bar,zot\r\noof,Huh?,Huh?\r\n'
>>>

How to stop line breaking in vim

set formatoptions-=t Keeps the visual textwidth but doesn't add new line in insert mode.

MySQL: selecting rows where a column is null

As all are given answers I want to add little more. I had also faced the same issue.

Why did your query fail? You have,

SELECT pid FROM planets WHERE userid = NULL;

This will not give you the expected result, because from mysql doc

In SQL, the NULL value is never true in comparison to any other value, even NULL. An expression that contains NULL always produces a NULL value unless otherwise indicated in the documentation for the operators and functions involved in the expression.

Emphasis mine.

To search for column values that are NULL, you cannot use an expr = NULL test. The following statement returns no rows, because expr = NULL is never true for any expression

Solution

SELECT pid FROM planets WHERE userid IS NULL; 

To test for NULL, use the IS NULL and IS NOT NULL operators.

How to delete a column from a table in MySQL

It is worth mentioning that MySQL 8.0.23 and above supports Invisible Columns

CREATE TABLE tbl_Country(
  CountryId INT NOT NULL AUTO_INCREMENT,
  IsDeleted bit,
  PRIMARY KEY (CountryId) 
);

INSERT INTO tbl_Country VALUES (1, 1), (2,0);

ALTER TABLE tbl_Country ALTER COLUMN IsDeleted SET INVISIBLE;

SELECT * FROM tbl_Country;
CountryId
1
2

ALTER TABLE tbl_Country DROP COLUMN IsDeleted;

db<>fiddle demo

It may be useful in scenarios when there is need to "hide" a column for a time being before it could be safely dropped(like reworking corresponding application/reports etc.).

How to replace all dots in a string using JavaScript

One more solution which is easy to understand :)

var newstring = mystring.split('.').join(' ');

How can I get form data with JavaScript/jQuery?

Based on jQuery.serializeArray, returns key-value pairs.

var data = $('#form').serializeArray().reduce(function(obj, item) {
    obj[item.name] = item.value;
    return obj;
}, {});

What is a practical, real world example of the Linked List?

Best and straight forward example of doubly linked list is Train!

enter image description here

Here Each coach is connected to its previous and next coach(Except first and last)

In terms of programming consider coach body as data(value) node and connector as reference node.

How to Convert unsigned char* to std::string in C++?

BYTE* is probably a typedef for unsigned char*, but I can't say for sure. It would help if you tell us what BYTE is.

If BYTE* is unsigned char*, you can convert it to an std::string using the std::string range constructor, which will take two generic Iterators.

const BYTE* str1 = reinterpret_cast<const BYTE*> ("Hello World");
int len = strlen(reinterpret_cast<const char*>(str1));
std::string str2(str1, str1 + len);

That being said, are you sure this is a good idea? If BYTE is unsigned char it may contain non-ASCII characters, which can include NULLs. This will make strlen give an incorrect length.

Login failed for user 'DOMAIN\MACHINENAME$'

  1. Change the App Pool Identity to Local System
  2. On SQL Mgmt > Security > Logins
    1. Find NT AUTHORITY\SYSTEM double click
    2. User Mappings > Check your database and give it a role below.
    3. Remember also to create the user data base o security logins with a correct password.

How to replace multiple strings in a file using PowerShell

A third option, for a pipelined one-liner is to nest the -replaces:

PS> ("ABC" -replace "B","C") -replace "C","D"
ADD

And:

PS> ("ABC" -replace "C","D") -replace "B","C"
ACD

This preserves execution order, is easy to read, and fits neatly into a pipeline. I prefer to use parentheses for explicit control, self-documentation, etc. It works without them, but how far do you trust that?

-Replace is a Comparison Operator, which accepts an object and returns a presumably modified object. This is why you can stack or nest them as shown above.

Please see:

help about_operators

Operator overloading ==, !=, Equals

I think you declared the Equals method like this:

public override bool Equals(BOX obj)

Since the object.Equals method takes an object, there is no method to override with this signature. You have to override it like this:

public override bool Equals(object obj)

If you want type-safe Equals, you can implement IEquatable<BOX>.

What is "android.R.layout.simple_list_item_1"?

android.R.layout.simple_list_item_1, this is row layout file in your res/layout folder which contains the corresponding design for your row in listview. Now we just bind the array list items to the row layout by using mylistview.setadapter(aa);

Getting the HTTP Referrer in ASP.NET

Use the Request.UrlReferrer property.

Underneath the scenes it is just checking the ServerVariables("HTTP_REFERER") property.

Mapping object to dictionary and vice versa

Using some reflection and generics in two extension methods you can achieve that.

Right, others did mostly the same solution, but this uses less reflection which is more performance-wise and way more readable:

public static class ObjectExtensions
{
    public static T ToObject<T>(this IDictionary<string, object> source)
        where T : class, new()
    {
            var someObject = new T();
            var someObjectType = someObject.GetType();

            foreach (var item in source)
            {
                someObjectType
                         .GetProperty(item.Key)
                         .SetValue(someObject, item.Value, null);
            }

            return someObject;
    }

    public static IDictionary<string, object> AsDictionary(this object source, BindingFlags bindingAttr = BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
    {
        return source.GetType().GetProperties(bindingAttr).ToDictionary
        (
            propInfo => propInfo.Name,
            propInfo => propInfo.GetValue(source, null)
        );

    }
}

class A
{
    public string Prop1
    {
        get;
        set;
    }

    public int Prop2
    {
        get;
        set;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, object> dictionary = new Dictionary<string, object>();
        dictionary.Add("Prop1", "hello world!");
        dictionary.Add("Prop2", 3893);
        A someObject = dictionary.ToObject<A>();

        IDictionary<string, object> objectBackToDictionary = someObject.AsDictionary();
    }
}

How to overlay image with color in CSS?

You can do that in one line of CSS.

  background: linear-gradient(to right, #3204fdba, #9907facc), url(https://picsum.photos/1280/853/?random=1) no-repeat top center;

Also hover on the color in VS Code, and click on the color to be a hex color, and you can change the colors opacity easy, instead of the rgba (rgba(48, 3, 252, 0.902), rgba(153, 7, 250, 0.902)), It can be short to (#3204fde6, #9907fae6)

enter image description here

_x000D_
_x000D_
header{
   height: 100vh;
   color: white;
   font: bold 2em/2em monospace;
   display: flex;
   justify-content: center;
   align-items: center;
  
  background: linear-gradient(to right,#3204fdba, #9907facc), url(https://picsum.photos/1280/853/?random=1) no-repeat top center;
}
_x000D_
<header>is simply dummy text of the printing and<br> typesetting industry.</header>
_x000D_
_x000D_
_x000D_

See here CodePen

enter image description here

How can I uninstall Ruby on ubuntu?

Why you are removing old version of the ruby?

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

Using rvm you can install multiple ruby version in the system

Please follow below steps install ruby using rvm

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

The installation step will change for different Ubuntu version

For more info,

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

Load CSV data into MySQL in Python

using pymsql if it helps

import pymysql
import csv
db = pymysql.connect("localhost","root","12345678","data" )

cursor = db.cursor()
csv_data = csv.reader(open('test.csv'))
next(csv_data)
for row in csv_data:
    cursor.execute('INSERT INTO PM(col1,col2) VALUES(%s, %s)',row)

db.commit()
cursor.close()

How to search through all Git and Mercurial commits in the repository for a certain string?

One command in git that I think it's much easier to find a string:

git log --pretty=oneline --grep "string to search"

works in Git 2.0.4

Select last N rows from MySQL

select * from Table ORDER BY id LIMIT 30

Notes: * id should be unique. * You can control the numbers of rows returned by replacing the 30 in the query

Given a class, see if instance has method (Ruby)

Actually this doesn't work for both Objects and Classes.

This does:

class TestClass
  def methodName
  end
end

So with the given answer, this works:

TestClass.method_defined? :methodName # => TRUE

But this does NOT work:

t = TestClass.new
t.method_defined? : methodName  # => ERROR!

So I use this for both classes and objects:

Classes:

TestClass.methods.include? 'methodName'  # => TRUE

Objects:

t = TestClass.new
t.methods.include? 'methodName'  # => TRUE

VBA code to show Message Box popup if the formula in the target cell exceeds a certain value

You could add the following VBA code to your sheet:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Range("A1") > 0.5 Then
        MsgBox "Discount too high"
    End If
End Sub

Every time a cell is changed on the sheet, it will check the value of cell A1.

Notes:

  • if A1 also depends on data located in other spreadsheets, the macro will not be called if you change that data.
  • the macro will be called will be called every time something changes on your sheet. If it has lots of formula (as in 1000s) it could be slow.

Widor uses a different approach (Worksheet_Calculate instead of Worksheet_Change):

  • Pros: his method will work if A1's value is linked to cells located in other sheets.
  • Cons: if you have many links on your sheet that reference other sheets, his method will run a bit slower.

Conclusion: use Worksheet_Change if A1 only depends on data located on the same sheet, use Worksheet_Calculate if not.

MySQL: Delete all rows older than 10 minutes

If time_created is a unix timestamp (int), you should be able to use something like this:

DELETE FROM locks WHERE time_created < (UNIX_TIMESTAMP() - 600);

(600 seconds = 10 minutes - obviously)

Otherwise (if time_created is mysql timestamp), you could try this:

DELETE FROM locks WHERE time_created < (NOW() - INTERVAL 10 MINUTE)

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

It might be a conflict with the same port specified in docker-compose.yml and docker-compose.override.yml or the same port specified explicitly and using an environment variable.

I had a docker-compose.yml with ports on a container specified using environment variables, and a docker-compose.override.yml with one of the same ports specified explicitly. Apparently docker tried to open both on the same container. docker container ls -a listed neither because the container could not start and list the ports.

SQL Server - after insert trigger - update another column in the same table

It depends on the recursion level for triggers currently set on the DB.

If you do this:

SP_CONFIGURE 'nested_triggers',0
GO
RECONFIGURE
GO

Or this:

ALTER DATABASE db_name
SET RECURSIVE_TRIGGERS OFF

That trigger above won't be called again, and you would be safe (unless you get into some kind of deadlock; that could be possible but maybe I'm wrong).

Still, I do not think this is a good idea. A better option would be using an INSTEAD OF trigger. That way you would avoid executing the first (manual) update over the DB. Only the one defined inside the trigger would be executed.

An INSTEAD OF INSERT trigger would be like this:

CREATE TRIGGER setDescToUpper ON part_numbers
INSTEAD OF INSERT
AS
BEGIN
    INSERT INTO part_numbers (
        colA,
        colB,
        part_description
    ) SELECT
        colA,
        colB,
        UPPER(part_description)
    ) FROM
        INSERTED
END
GO

This would automagically "replace" the original INSERT statement by this one, with an explicit UPPER call applied to the part_description field.

An INSTEAD OF UPDATE trigger would be similar (and I don't advise you to create a single trigger, keep them separated).

Also, this addresses @Martin comment: it works for multirow inserts/updates (your example does not).

How to open an existing project in Eclipse?

This is How I do it.

File -> Open Project from File System -> Existing Project in WorkSpace

How do I print the type or class of a variable in Swift?

Many of the answers here do not work with the latest Swift (Xcode 7.1.1 at time of writing).

The current way of getting the information is to create a Mirror and interrogate that. For the classname it is as simple as:

let mirror = Mirror(reflecting: instanceToInspect)
let classname:String = mirror.description

Additional information about the object can also be retrieved from the Mirror. See http://swiftdoc.org/v2.1/type/Mirror/ for details.

Add default value of datetime field in SQL Server to a timestamp

This can also be done through the SSMS GUI.

  1. Put your table in design view (Right click on table in object explorer->Design)
  2. Add a column to the table (or click on the column you want to update if it already exists)
  3. In Column Properties, enter (getdate()) in Default Value or Binding field as pictured below

Image of table in design view

How do you use subprocess.check_output() in Python?

Adding on to the one mentioned by @abarnert

a better one is to catch the exception

import subprocess
try:
    py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'],stderr= subprocess.STDOUT)  
    #print('py2 said:', py2output)
    print "here"
except subprocess.CalledProcessError as e:
    print "Calledprocerr"

this stderr= subprocess.STDOUT is for making sure you dont get the filenotfound error in stderr- which cant be usually caught in filenotfoundexception, else you would end up getting

python: can't open file 'py2.py': [Errno 2] No such file or directory

Infact a better solution to this might be to check, whether the file/scripts exist and then to run the file/script

How can I make PHP display the error instead of giving me 500 Internal Server Error

Enabling error displaying from PHP code doesn't work out for me. In my case, using NGINX and PHP-FMP, I track the log file using grep. For instance, I know the file name mycode.php causes the error 500, but don't know which line. From the console, I use this:

/var/log/php-fpm# cat www-error.log | grep mycode.php

And I have the output:

[04-Apr-2016 06:58:27] PHP Parse error:  syntax error, unexpected ';' in /var/www/html/system/mycode.php on line 1458

This helps me find the line where I have the typo.

How to output numbers with leading zeros in JavaScript?

function zfill(num, len) {return (Array(len).join("0") + num).slice(-len);}

How to print binary tree diagram?

Adapted from Vasya Novikov's answer to make it more binary, and use a StringBuilder for efficiency (concatenating String objects together in Java is generally inefficient).

public StringBuilder toString(StringBuilder prefix, boolean isTail, StringBuilder sb) {
    if(right!=null) {
        right.toString(new StringBuilder().append(prefix).append(isTail ? "¦   " : "    "), false, sb);
    }
    sb.append(prefix).append(isTail ? "+-- " : "+-- ").append(value.toString()).append("\n");
    if(left!=null) {
        left.toString(new StringBuilder().append(prefix).append(isTail ? "    " : "¦   "), true, sb);
    }
    return sb;
}

@Override
public String toString() {
    return this.toString(new StringBuilder(), true, new StringBuilder()).toString();
}

Output:

¦       +-- 7
¦   +-- 6
¦   ¦   +-- 5
+-- 4
    ¦   +-- 3
    +-- 2
        +-- 1
            +-- 0

Values of disabled inputs will not be submitted

Disabled controls cannot be successful, and a successful control is "valid" for submission. This is the reason why disabled controls don't submit with the form.

How to print_r $_POST array?

$_POST is already an array, so you don't need to wrap array() around it.

Try this instead:

<?php 

 for ($i=0;$i<count($_POST['id']);$i++) {

  echo "<p>".$_POST['id'][$i]."</p>";
  echo "<p>".$_POST['value'][$i]."</p>";
  echo "<hr />";

} 

 ?>

NOTE: This works because your id and value arrays are symmetrical. If they had different numbers of elements then you'd need to take a different approach.

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

My issue was similar - I had a new table i was creating that ahd to tie in to the identity users. After reading the above answers, realized it had to do with IsdentityUser and the inherited properites. I already had Identity set up as its own Context, so to avoid inherently tying the two together, rather than using the related user table as a true EF property, I set up a non-mapped property with the query to get the related entities. (DataManager is set up to retrieve the current context in which OtherEntity exists.)

    [Table("UserOtherEntity")]
        public partial class UserOtherEntity
        {
            public Guid UserOtherEntityId { get; set; }
            [Required]
            [StringLength(128)]
            public string UserId { get; set; }
            [Required]
            public Guid OtherEntityId { get; set; }
            public virtual OtherEntity OtherEntity { get; set; }
        }

    public partial class UserOtherEntity : DataManager
        {
            public static IEnumerable<OtherEntity> GetOtherEntitiesByUserId(string userId)
            {
                return Connect2Context.UserOtherEntities.Where(ue => ue.UserId == userId).Select(ue => ue.OtherEntity);
            }
        }

public partial class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

        [NotMapped]
        public IEnumerable<OtherEntity> OtherEntities
        {
            get
            {
                return UserOtherEntities.GetOtherEntitiesByUserId(this.Id);
            }
        }
    }

PHP regular expressions: No ending delimiter '^' found in

You can use T-Regx library, that doesn't need delimiters

pattern('^([0-9]+)$')->match($input);

Modulo operator with negative values

The sign in such cases (i.e when one or both operands are negative) is implementation-defined. The spec says in §5.6/4 (C++03),

The binary / operator yields the quotient, and the binary % operator yields the remainder from the division of the first expression by the second. If the second operand of / or % is zero the behavior is undefined; otherwise (a/b)*b + a%b is equal to a. If both operands are nonnegative then the remainder is nonnegative; if not, the sign of the remainder is implementation-defined.

That is all the language has to say, as far as C++03 is concerned.

How can I add new array elements at the beginning of an array in Javascript?

If you want to push elements that are in a array at the beginning of you array use <func>.apply(<this>, <Array of args>) :

_x000D_
_x000D_
const arr = [1, 2];
arr.unshift.apply(arr, [3, 4]);
console.log(arr); // [3, 4, 1, 2]
_x000D_
_x000D_
_x000D_

Assembly - JG/JNLE/JL/JNGE after CMP

When you do a cmp a,b, the flags are set as if you had calculated a - b.

Then the jmp-type instructions check those flags to see if the jump should be made.

In other words, the first block of code you have (with my comments added):

cmp al,dl     ; set flags based on the comparison
jg label1     ; then jump based on the flags

would jump to label1 if and only if al was greater than dl.

You're probably better off thinking of it as al > dl but the two choices you have there are mathematically equivalent:

al > dl
al - dl > dl - dl (subtract dl from both sides)
al - dl > 0       (cancel the terms on the right hand side)

You need to be careful when using jg inasmuch as it assumes your values were signed. So, if you compare the bytes 101 (101 in two's complement) with 200 (-56 in two's complement), the former will actually be greater. If that's not what was desired, you should use the equivalent unsigned comparison.

See here for more detail on jump selection, reproduced below for completeness. First the ones where signed-ness is not appropriate:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JO     | Jump if overflow             |             | OF = 1             |
+--------+------------------------------+-------------+--------------------+
| JNO    | Jump if not overflow         |             | OF = 0             |
+--------+------------------------------+-------------+--------------------+
| JS     | Jump if sign                 |             | SF = 1             |
+--------+------------------------------+-------------+--------------------+
| JNS    | Jump if not sign             |             | SF = 0             |
+--------+------------------------------+-------------+--------------------+
| JE/    | Jump if equal                |             | ZF = 1             |
| JZ     | Jump if zero                 |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNE/   | Jump if not equal            |             | ZF = 0             |
| JNZ    | Jump if not zero             |             |                    |
+--------+------------------------------+-------------+--------------------+
| JP/    | Jump if parity               |             | PF = 1             |
| JPE    | Jump if parity even          |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNP/   | Jump if no parity            |             | PF = 0             |
| JPO    | Jump if parity odd           |             |                    |
+--------+------------------------------+-------------+--------------------+
| JCXZ/  | Jump if CX is zero           |             | CX = 0             |
| JECXZ  | Jump if ECX is zero          |             | ECX = 0            |
+--------+------------------------------+-------------+--------------------+

Then the unsigned ones:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JB/    | Jump if below                | unsigned    | CF = 1             |
| JNAE/  | Jump if not above or equal   |             |                    |
| JC     | Jump if carry                |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNB/   | Jump if not below            | unsigned    | CF = 0             |
| JAE/   | Jump if above or equal       |             |                    |
| JNC    | Jump if not carry            |             |                    |
+--------+------------------------------+-------------+--------------------+
| JBE/   | Jump if below or equal       | unsigned    | CF = 1 or ZF = 1   |
| JNA    | Jump if not above            |             |                    |
+--------+------------------------------+-------------+--------------------+
| JA/    | Jump if above                | unsigned    | CF = 0 and ZF = 0  |
| JNBE   | Jump if not below or equal   |             |                    |
+--------+------------------------------+-------------+--------------------+

And, finally, the signed ones:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JL/    | Jump if less                 | signed      | SF <> OF           |
| JNGE   | Jump if not greater or equal |             |                    |
+--------+------------------------------+-------------+--------------------+
| JGE/   | Jump if greater or equal     | signed      | SF = OF            |
| JNL    | Jump if not less             |             |                    |
+--------+------------------------------+-------------+--------------------+
| JLE/   | Jump if less or equal        | signed      | ZF = 1 or SF <> OF |
| JNG    | Jump if not greater          |             |                    |
+--------+------------------------------+-------------+--------------------+
| JG/    | Jump if greater              | signed      | ZF = 0 and SF = OF |
| JNLE   | Jump if not less or equal    |             |                    |
+--------+------------------------------+-------------+--------------------+

How do you get a query string on Flask?

This can be done using request.args.get(). For example if your query string has a field date, it can be accessed using

date = request.args.get('date')

Don't forget to add "request" to list of imports from flask, i.e.

from flask import request

Adjust plot title (main) position

Try this:

par(adj = 0)
plot(1, 1, main = "Title")

or equivalent:

plot(1, 1, main = "Title", adj = 0)

adj = 0 produces left-justified text, 0.5 (the default) centered text and 1 right-justified text. Any value in [0, 1] is allowed.

However, the issue is that this will also change the position of the label of the x-axis and y-axis.

How can I copy a conditional formatting from one document to another?

To achieve this you can try below steps:

  1. Copy the cell or column which has the conditional formatting you want to copy.
  2. Go to the desired cell or column (maybe other sheets) where you want to apply conditional formatting.
  3. Open the context menu of the desired cell or column (by right-click on it).
  4. Find the "Paste Special" option which has a sub-menu.
  5. Select the "Paste conditional formatting only" option of the sub-menu and done.

How to use underscore.js as a template engine?

I am giving a very simple example

1)

var data = {site:"mysite",name:"john",age:25};
var template = "Welcome you are at <%=site %>.This has been created by <%=name %> whose age is <%=age%>";
var parsedTemplate = _.template(template,data);
console.log(parsedTemplate); 

The result would be

Welcome you are at mysite.This has been created by john whose age is 25.

2) This is a template

   <script type="text/template" id="template_1">
       <% _.each(items,function(item,key,arr) { %>
          <li>
             <span><%= key %></span>
             <span><%= item.name %></span>
             <span><%= item.type %></span>
           </li>
       <% }); %>
   </script>

This is html

<div>
  <ul id="list_2"></ul>
</div>

This is the javascript code which contains json object and putting template into html

   var items = [
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       },
       {
          name:"name1",
          type:"type1"
       } 
   ];
  $(document).ready(function(){
      var template = $("#template_1").html();
      $("#list_2").html(_.template(template,{items:items}));
  });

Remove Select arrow on IE

In case you want to use the class and pseudo-class:

.simple-control is your css class

:disabled is pseudo class

select.simple-control:disabled{
         /*For FireFox*/
        -webkit-appearance: none;
        /*For Chrome*/
        -moz-appearance: none;
}

/*For IE10+*/
select:disabled.simple-control::-ms-expand {
        display: none;
}

How do I monitor the computer's CPU, memory, and disk usage in Java?

Make a batch file "Pc.bat" as, typeperf -sc 1 "\mukit\processor(_Total)\%% Processor Time"

You can use the class MProcess,

/*
 *Md. Mukit Hasan
 *CSE-JU,35
 **/
import java.io.*;

public class MProcessor {

public MProcessor() { String s; try { Process ps = Runtime.getRuntime().exec("Pc.bat"); BufferedReader br = new BufferedReader(new InputStreamReader(ps.getInputStream())); while((s = br.readLine()) != null) { System.out.println(s); } } catch( Exception ex ) { System.out.println(ex.toString()); } }

}

Then after some string manipulation, you get the CPU use. You can use the same process for other tasks.

--Mukit Hasan

Java generics: multiple generic parameters?

Even more, you can inherit generics :)

@SuppressWarnings("unchecked")
public <T extends Something<E>, E extends Enum<E> & SomethingAware> T getSomething(Class<T> clazz) {
        return (T) somethingHolderMap.get(clazz);
    }

How to disable compiler optimizations in gcc?

You can disable optimizations if you pass -O0 with the gcc command-line.

E.g. to turn a .C file into a .S file call:

gcc -O0 -S test.c

Unicode character as bullet for list-item in CSS

EDIT

I probably wouldn't recommend using images anymore. I'd stick to the approach of using a Unicode character, like this:

li:before {
  content: "\2605";
}

OLD ANSWER

I'd probably go for an image background, they're much more efficient versatile and cross-browser-friendly.

Here's an example:

<style type="text/css">
  ul {list-style:none;} /* you should use a css reset too... ;) */
  ul li {background:url(images/icon_star.gif) no-repeat 0 5px;}
</style>

<ul>
  <li>List Item 1</li>
  <li>List Item 2</li>
  <li>List Item 3</li>
</ul>

Add image to layout in ruby on rails

image_tag is the best way to do the job friend

Get request URL in JSP which is forwarded by Servlet

Try this,

<c:set var="pageUrl" scope="request">
    <c:out value="${pageContext.request.scheme}://${pageContext.request.serverName}"/>
    <c:if test="${pageContext.request.serverPort != '80'}">
        <c:out value=":${pageContext.request.serverPort}"/>
    </c:if>
    <c:out value="${requestScope['javax.servlet.forward.request_uri']}"/>
</c:set>

I would like to put it in my base template and use in whole app whenever i need to.

Split Spark Dataframe string column into multiple columns

Here's another approach, in case you want split a string with a delimiter.

import pyspark.sql.functions as f

df = spark.createDataFrame([("1:a:2001",),("2:b:2002",),("3:c:2003",)],["value"])
df.show()
+--------+
|   value|
+--------+
|1:a:2001|
|2:b:2002|
|3:c:2003|
+--------+

df_split = df.select(f.split(df.value,":")).rdd.flatMap(
              lambda x: x).toDF(schema=["col1","col2","col3"])

df_split.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   1|   a|2001|
|   2|   b|2002|
|   3|   c|2003|
+----+----+----+

I don't think this transition back and forth to RDDs is going to slow you down... Also don't worry about last schema specification: it's optional, you can avoid it generalizing the solution to data with unknown column size.

Calculating Page Table Size

My explanation uses elementary building blocks that helped me to understand. Note I am leveraging @Deepak Goyal's answer above since he provided clarity:

We were given a logical 32-bit address space (i.e. We have a 32 bit computer)

Consider a system with a 32-bit logical address space

We were also told that

each page size is 4 KB

  • 1 KB (kilobyte) = 1 x 1024 bytes = 2^10 bytes
  • 4 x 1024 bytes = 2^2 x 2^10 bytes => 4 KB (i.e. 2^12 bytes)
  • The size of each page is thus 4 KB (Kilobytes NOT kilobits).

As Depaak said, we calculate the number of pages in the page table with this formula:

Num_Pages_in_PgTable = Total_Possible_Logical_Address_Entries / page size 
Num_Pages_in_PgTable =         2^32                           /    2^12
Num_Pages_in_PgTable = 2^20 (i.e. 1 million) 

The authors go on to give the case where each entry in the page table takes 4 bytes. That means that the total size of the page table in physical memory will be 4MB:

Memory_Required_Per_Page = Size_of_Page_Entry_in_bytes x Num_Pages_in_PgTable
Memory_Required_Per_Page =           4                 x     2^20
Memory_Required_Per_Page =     4 MB (Megabytes)

So yes, each process would require at least 4MB of memory to run, in increments of 4MB.

Example

Now if a professor wanted to make the question a bit more challenging than the explanation from the book, they might ask about a 64-bit computer. Let's say they want memory in bits. To solve the question, we'd follow the same process, only being sure to convert MB to Mbits.

Let's step through this example.

Givens:

  • Logical address space: 64-bit
  • Page Size: 4KB
  • Entry_Size_Per_Page: 4 bytes

Recall: A 64-bit entry can point to one of 2^64 physical page frames - Since Page size is 4 KB, then we still have 2^12 byte page sizes

  • 1 KB (kilobyte) = 1 x 1024 bytes = 2^10 bytes
  • Size of each page = 4 x 1024 bytes = 2^2 x 2^10 bytes = 2^12 bytes

How Many pages In Page Table?

`Num_Pages_in_PgTable = Total_Possible_Logical_Address_Entries / page size 
Num_Pages_in_PgTable =         2^64                            /    2^12
Num_Pages_in_PgTable =         2^52 
Num_Pages_in_PgTable =      2^2 x 2^50 
Num_Pages_in_PgTable =       4  x 2^50 `  

How Much Memory in BITS Per Page?

Memory_Required_Per_Page = Size_of_Page_Entry_in_bytes x Num_Pages_in_PgTable 
Memory_Required_Per_Page =   4 bytes x 8 bits/byte    x     2^52
Memory_Required_Per_Page =     32 bits                x   2^2 x 2^50
Memory_Required_Per_Page =     32 bits                x    4  x 2^50
Memory_Required_Per_Page =     128 Petabits

[2]: Operating System Concepts (9th Ed) - Gagne, Silberschatz, and Galvin

"Conversion to Dalvik format failed with error 1" on external JAR

All the solutions above didn't work for me. I'm not using any precompiled .jar. I'm using the LVL and the Dalvik errors where all related to the market licensing library.

The problem got solved by deleting the main project and reimporting (create a new project from existing sources).

Releasing memory in Python

First, you may want to install glances:

sudo apt-get install python-pip build-essential python-dev lm-sensors 
sudo pip install psutil logutils bottle batinfo https://bitbucket.org/gleb_zhulik/py3sensors/get/tip.tar.gz zeroconf netifaces pymdstat influxdb elasticsearch potsdb statsd pystache docker-py pysnmp pika py-cpuinfo bernhard
sudo pip install glances

Then run it in the terminal!

glances

In your Python code, add at the begin of the file, the following:

import os
import gc # Garbage Collector

After using the "Big" variable (for example: myBigVar) for which, you would like to release memory, write in your python code the following:

del myBigVar
gc.collect()

In another terminal, run your python code and observe in the "glances" terminal, how the memory is managed in your system!

Good luck!

P.S. I assume you are working on a Debian or Ubuntu system

callback to handle completion of pipe

Code snippet for piping content from web via http(s) to filesystem. As @starbeamrainbowlabs noticed event finish does job

var tmpFile = "/tmp/somefilename.doc";

var ws = fs.createWriteStream(tmpFile);
ws.on('finish', function() {
  // pipe done here, do something with file
});

var client = url.slice(0, 5) === 'https' ? https : http;
client.get(url, function(response) {
  return response.pipe(ws);
});

How to export library to Jar in Android Studio?

It is not possible to export an Android library as a jar file. It is possible, however, to export it as aar file. Aar files being the new binary format for Android libraries. There's info about them in Google I/O, the New Build System video.

First, build the library in Android Studio or from command line issuing gradle build from your library's root directory.

This will result in <yourlibroot>/libs/build/yourlib.aar file.

This aar file is a binary representation of your library and can be added to your project instead of the library as a dependency project.

To add aar file as a dependency you have to publish it to the maven central or to your local maven repository, and then refer the aar file in your project's gradle.build file.

However, this step is a bit convoluted. I've found a good explanation how to do so here:

http://www.flexlabs.org/2013/06/using-local-aar-android-library-packages-in-gradle-builds

Obtain smallest value from array in Javascript?

I think I have an easy-to-understand solution for this, using only the basics of javaScript.

function myFunction() {
            var i = 0;
            var smallestNumber = justPrices[0];
            for(i = 0; i < justPrices.length; i++) {
                if(justPrices[i] < smallestNumber) {
                    smallestNumber = justPrices[i];
                }
            }
            return smallestNumber;
        }

The variable smallestNumber is set to the first element of justPrices, and the for loop loops through the array (I'm just assuming that you know how a for loop works; if not, look it up). If an element of the array is smaller than the current smallestNumber (which at first is the first element), it will replace it's value. When the whole array has gone through the loop, smallestNumber will contain the smallest number in the array.

How a thread should close itself in Java?

If you simply call interrupt(), the thread will not automatically be closed. Instead, the Thread might even continue living, if isInterrupted() is implemented accordingly. The only way to guaranteedly close a thread, as asked for by OP, is

Thread.currentThread().stop();

Method is deprecated, however.

Calling return only returns from the current method. This only terminates the thread if you're at its top level.

Nevertheless, you should work with interrupt() and build your code around it.

Check if SQL Connection is Open or Closed

Check if a MySQL connection is open

ConnectionState state = connection.State;
if (state == ConnectionState.Open)
{
    return true;
}
else
{
    connection.Open();
    return true;
}

How to convert string to long

Do this:

long l = Long.parseLong(str);

However, always check that str contains digits to prevent throwing exceptions. For instance:

String str="ABCDE";
long l = Long.parseLong(str);

would throw an exception but this

String str="1234567";
long l = Long.parseLong(str);

won't.

What is the best way to test for an empty string with jquery-out-of-the-box?

The link you gave seems to be attempting something different to the test you are trying to avoid repeating.

if (a == null || a=='')

tests if the string is an empty string or null. The article you linked to tests if the string consists entirely of whitespace (or is empty).

The test you described can be replaced by:

if (!a)

Because in javascript, an empty string, and null, both evaluate to false in a boolean context.

Twitter bootstrap float div right

To float a div to the right pull-right is the recommend way, I feel you are doing things right may be you only need to use text-align:right;

  <div class="container">
     <div class="row-fluid">
      <div class="span6">
           <p>Text left</p>
      </div>
      <div class="span6 pull-right" style="text-align:right">
           <p>text right</p>
      </div>
  </div>
 </div>      
 </div>

How do I set an un-selectable default description in a select (drop-down) menu in HTML?

Although this question has an accepted answer but I think this is a much cleaner way to achieve the desired output

<select required>
<option value="">Select</option>
<option>English</option>
<option>Spanish</option>
</select>

The required attribute in makes it mandatory to select an option from the list.

value="" inside the option tag combined with the required attribute in select tag makes selection of 'Select' option not permissible, thus achieving the required output

C++ String Declaring

In C++ you can declare a string like this:

#include <string>

using namespace std;

int main()
{
    string str1("argue2000"); //define a string and Initialize str1 with "argue2000"    
    string str2 = "argue2000"; // define a string and assign str2 with "argue2000"
    string str3;  //just declare a string, it has no value
    return 1;
}

How to get the selected value from RadioButtonList?

The ASPX code will look something like this:

 <asp:RadioButtonList ID="rblist1" runat="server">

    <asp:ListItem Text ="Item1" Value="1" />
    <asp:ListItem Text ="Item2" Value="2" />
    <asp:ListItem Text ="Item3" Value="3" />
    <asp:ListItem Text ="Item4" Value="4" />

    </asp:RadioButtonList>

    <asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="select value" />

And the code behind:

protected void Button1_Click(object sender, EventArgs e)
        {
            string selectedValue = rblist1.SelectedValue;
            Response.Write(selectedValue);
        }

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

The JROCKIT JVM currently owned by Oracle supports non-contiguous heap usage, thus allowing the 32 bit JVM to access more then 3.8 GB of memory when the JVM is running on a 64 bit windows OS. (2.8 GB when running on a 32 bit OS).

http://blogs.oracle.com/jrockit/entry/how_to_get_almost_3_gb_heap_on_windows

The JVM can be freely downloaded (registration required) at

http://www.oracle.com/technetwork/middleware/jrockit/downloads/index.html

How do you set a JavaScript onclick event to a class with css

You could do it with jQuery.

$('.myClass').click(function() {
  alert('hohoho');
});

Pyspark: display a spark data frame in a table format

As mentioned by @Brent in the comment of @maxymoo's answer, you can try

df.limit(10).toPandas()

to get a prettier table in Jupyter. But this can take some time to run if you are not caching the spark dataframe. Also, .limit() will not keep the order of original spark dataframe.

Difference between applicationContext.xml and spring-servlet.xml in Spring Framework

Spring lets you define multiple contexts in a parent-child hierarchy.

The applicationContext.xml defines the beans for the "root webapp context", i.e. the context associated with the webapp.

The spring-servlet.xml (or whatever else you call it) defines the beans for one servlet's app context. There can be many of these in a webapp, one per Spring servlet (e.g. spring1-servlet.xml for servlet spring1, spring2-servlet.xml for servlet spring2).

Beans in spring-servlet.xml can reference beans in applicationContext.xml, but not vice versa.

All Spring MVC controllers must go in the spring-servlet.xml context.

In most simple cases, the applicationContext.xml context is unnecessary. It is generally used to contain beans that are shared between all servlets in a webapp. If you only have one servlet, then there's not really much point, unless you have a specific use for it.

Stopword removal with NLTK

@alvas's answer does the job but it can be done way faster. Assuming that you have documents: a list of strings.

from nltk.corpus import stopwords
from nltk.tokenize import wordpunct_tokenize

stop_words = set(stopwords.words('english'))
stop_words.update(['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}']) # remove it if you need punctuation 

for doc in documents:
    list_of_words = [i.lower() for i in wordpunct_tokenize(doc) if i.lower() not in stop_words]

Notice that due to the fact that here you are searching in a set (not in a list) the speed would be theoretically len(stop_words)/2 times faster, which is significant if you need to operate through many documents.

For 5000 documents of approximately 300 words each the difference is between 1.8 seconds for my example and 20 seconds for @alvas's.

P.S. in most of the cases you need to divide the text into words to perform some other classification tasks for which tf-idf is used. So most probably it would be better to use stemmer as well:

from nltk.stem.porter import PorterStemmer
porter = PorterStemmer()

and to use [porter.stem(i.lower()) for i in wordpunct_tokenize(doc) if i.lower() not in stop_words] inside of a loop.

Change all files and folders permissions of a directory to 644/755

This worked for me:

find /A -type d -exec chmod 0755 {} \;
find /A -type f -exec chmod 0644 {} \;

How to Generate Barcode using PHP and Display it as an Image on the same page

There is a library for this BarCode PHP. You just need to include a few files:

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

You can generate many types of barcodes, namely 1D or 2D. Add the required library:

require_once('class/BCGcode39.barcode.php');

Generate the colours:

// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);

After you have added all the codes, you will get this way:

Example

Since several have asked for an example here is what I was able to do to get it done

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

require_once('class/BCGcode128.barcode.php');

header('Content-Type: image/png');

$color_white = new BCGColor(255, 255, 255);

$code = new BCGcode128();
$code->parse('HELLO');

$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);

$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

If you want to actually create the image file so you can save it then change

$drawing = new BCGDrawing('', $color_white);

to

$drawing = new BCGDrawing('image.png', $color_white);

How do you get the current text contents of a QComboBox?

You can convert the QString type to python string by just using the str function. Assuming you are not using any Unicode characters you can get a python string as below:

text = str(combobox1.currentText())

If you are using any unicode characters, you can do:

text = unicode(combobox1.currentText())

How to import component into another root component in Angular 2

Angular RC5 & RC6

If you are getting the above mentioned error in your Jasmine tests, it is most likely because you have to declare the unrenderable component in your TestBed.configureTestingModule({}).

The TestBed configures and initializes an environment for unit testing and provides methods for mocking/creating/injecting components and services in unit tests.

If you don't declare the component before your unit tests are executed, Angular will not know what <courses></courses> is in your template file.

Here is an example:

import {async, ComponentFixture, TestBed} from "@angular/core/testing";
import {AppComponent} from "../app.component";
import {CoursesComponent} from './courses.component';

describe('CoursesComponent', () => {
  let component: CoursesComponent;
  let fixture: ComponentFixture<CoursesComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent,
        CoursesComponent
      ],
      imports: [
        BrowserModule
        // If you have any other imports add them here
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(CoursesComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

Call to getLayoutInflater() in places not in activity

Or ...

LayoutInflater inflater = LayoutInflater.from(context);

Connect Java to a MySQL database

Short Code

public class DB {

    public static Connection c;

    public static Connection getConnection() throws Exception {
        if (c == null) {
            Class.forName("com.mysql.jdbc.Driver");
            c =DriverManager.getConnection("jdbc:mysql://localhost:3306/DATABASE", "USERNAME", "Password");
        }
        return c;
    }

    // Send data TO Database
    public static void setData(String sql) throws Exception {
        DB.getConnection().createStatement().executeUpdate(sql);
    }

    // Get Data From Database
    public static ResultSet getData(String sql) throws Exception {
        ResultSet rs = DB.getConnection().createStatement().executeQuery(sql);
        return rs;
    }
}

Unsupported method: BaseConfig.getApplicationIdSuffix()

I did the following to make this run on AS 3.5

  1. app/ build.gradle

    apply plugin: 'com.android.application'

    android { compileSdkVersion 21 buildToolsVersion "25.0.0"

    defaultConfig {
        applicationId "com.example.android.mobileperf.render"
        minSdkVersion 14
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    

    }

dependencies { implementation fileTree(dir: 'libs', include: ['*.jar']) implementation 'com.android.support:appcompat-v7:21.0.0' implementation 'com.squareup.picasso:picasso:2.71828' }

  1. build.gradle

    buildscript { repositories { jcenter() mavenCentral() maven { url 'https://maven.google.com/' name 'Google' } google() } dependencies { classpath 'com.android.tools.build:gradle:3.0.1' } } allprojects { repositories { jcenter() google() } }

  2. gradle-wrapper.properties

    distributionUrl=https://services.gradle.org/distributions/gradle-4.1-all.zip

How to view an HTML file in the browser with Visual Studio Code

Ctrl + F1 will open the default browser. alternatively you can hit Ctrl + shift + P to open command window and select "View in Browser". The html code must be saved in a file (unsaved code on the editor - without extension, doesn't work)

What is the best IDE to develop Android apps in?

Eclipse is the most widely used development environment for the Android platform. The reason is that even Google itself providing the plug-in to be added in eclipse and start developing the applications. I have tried installing it from the eclipse market place, it is very easy and simple to create the android application. set up also very simple.

WAMP Server doesn't load localhost

Change the port 80 to port 8080 and restart all services and access like localhost:8080/

It will work fine.

What is the most efficient way to get first and last line of a text file?

docs for io module

with open(fname, 'rb') as fh:
    first = next(fh).decode()

    fh.seek(-1024, 2)
    last = fh.readlines()[-1].decode()

The variable value here is 1024: it represents the average string length. I choose 1024 only for example. If you have an estimate of average line length you could just use that value times 2.

Since you have no idea whatsoever about the possible upper bound for the line length, the obvious solution would be to loop over the file:

for line in fh:
    pass
last = line

You don't need to bother with the binary flag you could just use open(fname).

ETA: Since you have many files to work on, you could create a sample of couple of dozens of files using random.sample and run this code on them to determine length of last line. With an a priori large value of the position shift (let say 1 MB). This will help you to estimate the value for the full run.

Submit a form in a popup, and then close the popup

Try like this as well

covertPostSub("/xyz/test.jsp","?param1=param1&param2=param2","_self","true");
covertPostSub("/xyz/test.jsp","?param1=param1&param2=param2","_blank","true");

var convPop = null;
function covertPostSub(action,paramsTosend,targetIframe,isWindow){
    var Popup = null;
    var form = document.createElement("form");
    form.setAttribute("method", "POST");
    form.setAttribute("id","TheForm");
    form.setAttribute("action", action);
    form.setAttribute("target", targetIframe);
    var params = paramsTosend;
    params = params.substring(1, params.length);
    params = params.split("&");
    for(var key=0; key<params.length; key++) {
        var sa = params[key];
        sa = sa.split("=");
        var xs = (sa[1]);

        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", sa[0]);
            hiddenField.setAttribute("value",xs);

            form.appendChild(hiddenField);
         }
    }
    document.body.appendChild(form);
    form.style.display = "none";
    if(isWindow){
        window.open('', "formpopup","width=900,height=590,toolbar=no,scrollbars=yes,resizable=no,location=0,directories=0,status=1,menubar=0,left=60,top=60");
        form.target = 'formpopup';
        form.submit();
    }else{
        form.submit();
    }

}

ActionLink htmlAttributes

Replace the desired hyphen with an underscore; it will automatically be rendered as a hyphen:

@Html.ActionLink("Edit", "edit", "markets",
    new { id = 1 },
    new {@class="ui-btn-right", data_icon="gear"})

becomes:

<form action="markets/Edit/1" class="ui-btn-right" data-icon="gear" .../>

TSQL How do you output PRINT in a user defined function?

Tip: generate error.

declare @Day int, @Config_Node varchar(50)

    set @Config_Node = 'value to trace'

    set @Day = @Config_Node

You will get this message:

Conversion failed when converting the varchar value 'value to trace' to data type int.

Filter multiple values on a string column in dplyr

This can be achieved using dplyr package, which is available in CRAN. The simple way to achieve this:

  1. Install dplyr package.
  2. Run the below code
library(dplyr) 

df<- select(filter(dat,name=='tom'| name=='Lynn'), c('days','name))

Explanation:

So, once we’ve downloaded dplyr, we create a new data frame by using two different functions from this package:

filter: the first argument is the data frame; the second argument is the condition by which we want it subsetted. The result is the entire data frame with only the rows we wanted. select: the first argument is the data frame; the second argument is the names of the columns we want selected from it. We don’t have to use the names() function, and we don’t even have to use quotation marks. We simply list the column names as objects.

Inserting code in this LaTeX document with indentation

Specialized packages such as minted, which relies on Pygments to do the formatting, offer various advantages over the listings package. To quote from the minted manual,

Pygments provides far superior syntax highlighting compared to conventional packages. For example, listings basically only highlights strings, comments and keywords. Pygments, on the other hand, can be completely customized to highlight any token kind the source language might support. This might include special formatting sequences inside strings, numbers, different kinds of identifiers and exotic constructs such as HTML tags.

how to use the Box-Cox power transformation in R

Applying the BoxCox transformation to data, without the need of any underlying model, can be done currently using the package geoR. Specifically, you can use the function boxcoxfit() for finding the best parameter and then predict the transformed variables using the function BCtransform().

What is the HTML tabindex attribute?

When the user presses the tab button the user will be taken through the form in the order 1, 2, and 3 as indicated in the example below.

For example:

Name: <input name="name" tabindex="1"  />
Age: <input name="age" tabindex="3"  />
Email: <input name="email" tabindex="2"  />

jQuery date formatting

u can use this coding

$('[name="tgllahir"]').val($.datepicker.formatDate('dd-mm-yy', new Date(data.tgllahir)));

HTML5 image icon to input placeholder

<html>
<head>
<style> 
input[type=text] {
    width: 50%;
    box-sizing: border-box;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background-color: white;
    background-image: url('searchicon.png');
    background-position: 10px 10px; 
    background-repeat: no-repeat;
    padding: 12px 20px 12px 40px;
}
</style>
</head>
<body>

<p>Input with icon:</p>

<form>
  <input type="text" name="search" placeholder="Search..">
</form>

</body>
</html>

c# - approach for saving user settings in a WPF application?

Apart from a database, you can also have following options to save user related settings

  1. registry under HKEY_CURRENT_USER

  2. in a file in AppData folder

  3. using Settings file in WPF and by setting its scope as User

How do I tell what type of value is in a Perl variable?

At some point I read a reasonably convincing argument on Perlmonks that testing the type of a scalar with ref or reftype is a bad idea. I don't recall who put the idea forward, or the link. Sorry.

The point was that in Perl there are many mechanisms that make it possible to make a given scalar act like just about anything you want. If you tie a filehandle so that it acts like a hash, the testing with reftype will tell you that you have a filehanle. It won't tell you that you need to use it like a hash.

So, the argument went, it is better to use duck typing to find out what a variable is.

Instead of:

sub foo {
    my $var = shift;
    my $type = reftype $var;

    my $result;
    if( $type eq 'HASH' ) {
        $result = $var->{foo};
    }
    elsif( $type eq 'ARRAY' ) {
        $result = $var->[3];
    }
    else {
        $result = 'foo';
    }

    return $result;
}

You should do something like this:

sub foo {
    my $var = shift;
    my $type = reftype $var;

    my $result;

    eval {
        $result = $var->{foo};
        1; # guarantee a true result if code works.
    }
    or eval { 
        $result = $var->[3];
        1;
    }
    or do {
        $result = 'foo';
    }

    return $result;
}

For the most part I don't actually do this, but in some cases I have. I'm still making my mind up as to when this approach is appropriate. I thought I'd throw the concept out for further discussion. I'd love to see comments.

Update

I realized I should put forward my thoughts on this approach.

This method has the advantage of handling anything you throw at it.

It has the disadvantage of being cumbersome, and somewhat strange. Stumbling upon this in some code would make me issue a big fat 'WTF'.

I like the idea of testing whether a scalar acts like a hash-ref, rather that whether it is a hash ref.

I don't like this implementation.

Suppress Scientific Notation in Numpy When Creating Array From Nested List

You could write a function that converts a scientific notation to regular, something like

def sc2std(x):
    s = str(x)
    if 'e' in s:
        num,ex = s.split('e')
        if '-' in num:
            negprefix = '-'
        else:
            negprefix = ''
        num = num.replace('-','')
        if '.' in num:
            dotlocation = num.index('.')
        else:
            dotlocation = len(num)
        newdotlocation = dotlocation + int(ex)
        num = num.replace('.','')
        if (newdotlocation < 1):
            return negprefix+'0.'+'0'*(-newdotlocation)+num
        if (newdotlocation > len(num)):
            return negprefix+ num + '0'*(newdotlocation - len(num))+'.0'
        return negprefix + num[:newdotlocation] + '.' + num[newdotlocation:]
    else:
        return s

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

For testing purposes:

On the original machine, find the library, copy to the same directory as the executable:

$ ldconfig -p | grep libstdc
        libstdc++.so.6 (libc6,x86-64) => /usr/lib/x86_64-linux-gnu/libstdc++.so.6
        libstdc++.so.6 (libc6) => /usr/lib32/libstdc++.so.6
$ cp /usr/lib/x86_64-linux-gnu/libstdc++.so.6 .

Then copy this same library to the target machine, and run the executable:

LD_LIBRARY_PATH=. ./myexecutable

Note: command above is temporary; it is not a system-wide change.

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

NUMBER (precision, scale) means precision number of total digits, of which scale digits are right of the decimal point.

NUMBER(2,2) in other words means a number with 2 digits, both of which are decimals. You may mean to use NUMBER(4,2) to get 4 digits, of which 2 are decimals. Currently you can just insert values with a zero integer part.

More info at the Oracle docs.

Preventing HTML and Script injections in Javascript

Use this,

function restrict(elem){
  var tf = _(elem);
  var rx = new RegExp;
  if(elem == "email"){
       rx = /[ '"]/gi;
  }else if(elem == "search" || elem == "comment"){
    rx = /[^a-z 0-9.,?]/gi;
  }else{
      rx =  /[^a-z0-9]/gi;
  }
  tf.value = tf.value.replace(rx , "" );
}

On the backend, for java , Try using StringUtils class or a custom script.

public static String HTMLEncode(String aTagFragment) {
        final StringBuffer result = new StringBuffer();
        final StringCharacterIterator iterator = new
                StringCharacterIterator(aTagFragment);
        char character = iterator.current();
        while (character != StringCharacterIterator.DONE )
        {
            if (character == '<')
                result.append("&lt;");
            else if (character == '>')
                result.append("&gt;");
            else if (character == '\"')
                result.append("&quot;");
            else if (character == '\'')
                result.append("&#039;");
            else if (character == '\\')
                result.append("&#092;");
            else if (character == '&')
                result.append("&amp;");
            else {
            //the char is not a special one
            //add it to the result as is
                result.append(character);
            }
            character = iterator.next();
        }
        return result.toString();
    }

How to have an automatic timestamp in SQLite?

You can create TIMESTAMP field in table on the SQLite, see this:

CREATE TABLE my_table (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    name VARCHAR(64),
    sqltime TIMESTAMP DEFAULT CURRENT_TIMESTAMP NOT NULL
);

INSERT INTO my_table(name, sqltime) VALUES('test1', '2010-05-28T15:36:56.200');
INSERT INTO my_table(name, sqltime) VALUES('test2', '2010-08-28T13:40:02.200');
INSERT INTO my_table(name) VALUES('test3');

This is the result:

SELECT * FROM my_table;

enter image description here

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

If you've edited /etc/apache2/httpd.conf with the ServerName localhost you may be editing the wrong file. All answers I found were pointing towards that standard httpd.conf. After some foraging, I found a good answer here.

To locate the right httpd.conf file use

apachectl -t -D DUMP_INCLUDES

I found mine was actually /usr/local/etc/httpd/httpd.conf.

Use your preferred editor to comment out the line (i.e. remove the # before) starting with ServerName, and replace the domain name for the appropriate one – local environments should work with

ServerName localhost

I hope this helps more people who may be stuck.

Qt 5.1.1: Application failed to start because platform plugin "windows" is missing

The application qtbase/bin/windeployqt.exe deploys automatically your application. If you start a prompt with envirenmentvariables set correctly, it deploys to the current directory. You find an example of script:

@echo off
set QTDIR=E:\QT\5110\vc2017

set INCLUDE=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\ATLMFC\include;S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\include;C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\include\um;C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\ucrt;C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\shared;C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\um;C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\winrt;C:\Program Files (x86)\Windows Kits\10\include\10.0.14393.0\cppwinrt

set LIB=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\ATLMFC\lib\x86;S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\lib\x86;C:\Program Files (x86)\Windows Kits\NETFXSDK\4.6.1\lib\um\x86;C:\Program Files (x86)\Windows Kits\10\lib\10.0.14393.0\ucrt\x86;C:\Program Files (x86)\Windows Kits\10\lib\10.0.14393.0\um\x86;

set LIBPATH=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\ATLMFC\lib\x86;S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\lib\x86;S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.15.26726\lib\x86\store\references;C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.17134.0;C:\ProgramFiles (x86)\Windows Kits\10\References\10.0.17134.0;C:\Windows\Microsoft.NET\Framework\v4.0.30319;

Path=%QTDIR%\qtbase\bin;%PATH%
set VCIDEInstallDir=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\VC\
set VCINSTALLDIR=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\
set VCToolsInstallDir=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VC\Tools\MSVC\14.11.25503\
set VisualStudioVersion=15.0
set VS100COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tools\
set VS110COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\Tools\
set VS120COMNTOOLS=S:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\
set VS150COMNTOOLS=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\Tools\
set VS80COMNTOOLS=C:\Program Files (x86)\Microsoft Visual Studio 8\Common7\Tools\
set VS90COMNTOOLS=c:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\Tools\
set VSINSTALLDIR=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\
set VSSDK110Install=C:\Program Files (x86)\Microsoft Visual Studio 11.0\VSSDK\
set VSSDK150INSTALL=S:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\VSSDK
set WindowsLibPath=C:\Program Files (x86)\Windows Kits\10\UnionMetadata;C:\Program Files (x86)\Windows Kits\10\References
set WindowsSdkBinPath=C:\Program Files (x86)\Windows Kits\10\bin\
set WindowsSdkDir=C:\Program Files (x86)\Windows Kits\10\
set WindowsSDKLibVersion=10.0.14393.0\
set WindowsSdkVerBinPath=C:\Program Files (x86)\Windows Kits\10\bin\10.0.14393.0\
set WindowsSDKVersion=10.0.14393.0\
set WindowsSDK_ExecutablePath_x64=C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\x64\
set WindowsSDK_ExecutablePath_x86=C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\

mkdir C:\VCProjects\Application\Build\VS2017_QT5_11_32-Release\setup
cd C:\VCProjects\Application\Build\VS2017_QT5_11_32-Release\setup
copy /Y ..\Release\application.exe .
windeployqt application.exe
pause

Python: Making a beep noise

Using pygame on any platform

The advantage of using pygame is that it can be made to work on any OS platform. Below example code is for GNU/Linux though.

First install the pygame module for python3 as explained in detail here.

$ sudo pip3 install pygame

The pygame module can play .wav and .ogg files from any file location. Here is an example:

#!/usr/bin/env python3
import pygame
pygame.mixer.init()
sound = pygame.mixer.Sound('/usr/share/sounds/freedesktop/stereo/phone-incoming-call.oga')
sound.play()

Change content of div - jQuery

Try this to Change content of div using jQuery.

See more @ Change content of div using jQuery

$(document).ready(function(){
    $("#Textarea").keyup(function(){
        // Getting the current value of textarea
        var currentText = $(this).val();

        // Setting the Div content
        $(".output").text(currentText);
    });
});

Editable 'Select' element

Nothing is impossible. Here's a solution that simply sets the value of a text input whenever the value of the <select> changes (rendering has been tested on Firefox and Google Chrome):

_x000D_
_x000D_
.select-editable {position:relative; background-color:white; border:solid grey 1px;  width:120px; height:18px;}_x000D_
.select-editable select {position:absolute; top:0px; left:0px; font-size:14px; border:none; width:120px; margin:0;}_x000D_
.select-editable input {position:absolute; top:0px; left:0px; width:100px; padding:1px; font-size:12px; border:none;}_x000D_
.select-editable select:focus, .select-editable input:focus {outline:none;}
_x000D_
<div class="select-editable">_x000D_
  <select onchange="this.nextElementSibling.value=this.value">_x000D_
    <option value=""></option>_x000D_
    <option value="115x175 mm">115x175 mm</option>_x000D_
    <option value="120x160 mm">120x160 mm</option>_x000D_
    <option value="120x287 mm">120x287 mm</option>_x000D_
  </select>_x000D_
  <input type="text" name="format" value=""/>_x000D_
</div>
_x000D_
_x000D_
_x000D_ jsfiddle: https://jsfiddle.net/nwH8A/

The next example adds the user input to the empty option slot of the <select> (thanks to @TomerPeled). It also has a little bit more flexible/variable CSS:

_x000D_
_x000D_
.select-editable {position:relative; width:120px;}_x000D_
.select-editable > * {position:absolute; top:0; left:0; box-sizing:border-box; outline:none;}_x000D_
.select-editable select {width:100%;}_x000D_
.select-editable input {width:calc(100% - 20px); margin:1px; border:none; text-overflow:ellipsis;}
_x000D_
<div class="select-editable">_x000D_
  <select onchange="this.nextElementSibling.value=this.value">_x000D_
    <option value=""></option>_x000D_
    <option value="115x175 mm">115x175 mm</option>_x000D_
    <option value="120x160 mm">120x160 mm</option>_x000D_
    <option value="120x287 mm">120x287 mm</option>_x000D_
  </select>_x000D_
  <input type="text" oninput="this.previousElementSibling.options[0].value=this.value; this.previousElementSibling.options[0].innerHTML=this.value" onchange="this.previousElementSibling.selectedIndex=0" value="" />_x000D_
</div>
_x000D_
_x000D_
_x000D_ jsfiddle: https://jsfiddle.net/pu7cndLv/1/


DataList

In HTML5 you can also do this with the <input> list attribute and <datalist> element:

_x000D_
_x000D_
<input list="browsers" name="browser">_x000D_
<datalist id="browsers">_x000D_
  <option value="Internet Explorer">_x000D_
  <option value="Firefox">_x000D_
  <option value="Chrome">_x000D_
  <option value="Opera">_x000D_
  <option value="Safari">_x000D_
</datalist>_x000D_
(click once to focus and edit, click again to see option dropdown)
_x000D_
_x000D_
_x000D_ jsfiddle: https://jsfiddle.net/hrkxebtw/

But this acts more like an auto-complete list; once you start typing, only the options that contain the typed string are left as suggestions. Depending on what you want to use it for, this may or may not be practical.

Oracle SqlDeveloper JDK path

I cannot believe Oracle's documentation is SO LAME! In some documents it is misleading people to point to the JDK by specifying the path to the JDK root, e.g. on a Mac:

/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/

Reviewing /Applications/SQLDeveloper.app/Contents/MacOS/sqldeveloper.sh revealed the method they use to set up the path:

TMP_PATH=/usr/libexec/java_home -F -v 9 if [ -z "$TMP_PATH" ] ; then TMP_PATH=/usr/libexec/java_home -F -v 1.8 if [ -z "$TMP_PATH" ] ; then osascript -e 'tell app "System Events" to display dialog "SQL Developer requires a minimum of Java 8. \nJava 8 can be downloaded from:\n http://www.oracle.com/technetwork/java/javase/downloads/"' exit 1 fi fi

Executing this manually from Terminal:

/usr/libexec/java_home -F -v 1.8

Lists the path as:

/Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home

And this is what you need to specify as the value for

SetJavaHome /Library/Java/JavaVirtualMachines/jdk1.8.0_152.jdk/Contents/Home

Thank you Oracle for wasting half a day on your "product" that does NOT even support your latest Java version, also released by you.

Error including image in Latex

I use MacTex, and my editor is TexShop. It probably has to do with what compiler you are using. When I use pdftex, the command:

\includegraphics[height=60mm, width=100mm]{number2.png}

works fine, but when I use "Tex and Ghostscript", I get the same error as you, about not being able to get the size information. Use pdftex.

Incidentally, you can change this in TexShop from the "Typeset" menu.

Hope this helps.

pandas loc vs. iloc vs. at vs. iat?

Let's start with this small df:

import pandas as pd
import time as tm
import numpy as np
n=10
a=np.arange(0,n**2)
df=pd.DataFrame(a.reshape(n,n))

We'll so have

df
Out[25]: 
        0   1   2   3   4   5   6   7   8   9
    0   0   1   2   3   4   5   6   7   8   9
    1  10  11  12  13  14  15  16  17  18  19
    2  20  21  22  23  24  25  26  27  28  29
    3  30  31  32  33  34  35  36  37  38  39
    4  40  41  42  43  44  45  46  47  48  49
    5  50  51  52  53  54  55  56  57  58  59
    6  60  61  62  63  64  65  66  67  68  69
    7  70  71  72  73  74  75  76  77  78  79
    8  80  81  82  83  84  85  86  87  88  89
    9  90  91  92  93  94  95  96  97  98  99

With this we have:

df.iloc[3,3]
Out[33]: 33

df.iat[3,3]
Out[34]: 33

df.iloc[:3,:3]
Out[35]: 
    0   1   2   3
0   0   1   2   3
1  10  11  12  13
2  20  21  22  23
3  30  31  32  33



df.iat[:3,:3]
Traceback (most recent call last):
   ... omissis ...
ValueError: At based indexing on an integer index can only have integer indexers

Thus we cannot use .iat for subset, where we must use .iloc only.

But let's try both to select from a larger df and let's check the speed ...

# -*- coding: utf-8 -*-
"""
Created on Wed Feb  7 09:58:39 2018

@author: Fabio Pomi
"""

import pandas as pd
import time as tm
import numpy as np
n=1000
a=np.arange(0,n**2)
df=pd.DataFrame(a.reshape(n,n))
t1=tm.time()
for j in df.index:
    for i in df.columns:
        a=df.iloc[j,i]
t2=tm.time()
for j in df.index:
    for i in df.columns:
        a=df.iat[j,i]
t3=tm.time()
loc=t2-t1
at=t3-t2
prc = loc/at *100
print('\nloc:%f at:%f prc:%f' %(loc,at,prc))

loc:10.485600 at:7.395423 prc:141.784987

So with .loc we can manage subsets and with .at only a single scalar, but .at is faster than .loc

:-)

Change / Add syntax highlighting for a language in Sublime 2/3

I finally found a way to customize the given Themes.

Go to C:\Program Files\Sublime Text 3\Packages and copy + rename Color Scheme - Default.sublime-package to Color Scheme - Default.zip. Afterwards unzip it and copy the Theme, you want to change to %APPDATA%\Sublime Text 3\Packages\User. (In my case, All Hallow's Eve.tmTheme).

Then you can open it with any Text Editor and change / add something, for example for changing this in JavaScript:

<dict>
    <key>name</key>
    <string>Lang Variable</string>
    <key>scope</key>
    <string>variable.language</string>
    <key>settings</key>
    <dict>
        <key>foreground</key>
        <string>#FF0000</string>
    </dict>
</dict>

This will mark this in JavaScript Files red. You can select your Theme under Preferences -> Color Scheme -> User -> <Your Name>.

Installing Oracle Instant Client

The directions state:

  1. Download the appropriate Instant Client packages for your platform. All installations REQUIRE the Basic package.
  2. Unzip the packages into a single directory such as "instantclient".
  3. Set the library loading path in your environment to the directory in Step 2 ("instantclient"). On many UNIX platforms, LD_LIBRARY_PATH is the appropriate environment variable. On Windows, PATH should be used.
  4. Start your application and enjoy.

Suggest extracting/unzipping into a new directory. They've suggested instantclient, but you can name the directory anything you like. Name it C:\OracleInstantClient\ if you choose.

Then in Step 3, open a Windows Command Prompt. Type:

PATH C:\OracleInstantClient; %PATH%`

That's all there is to it!

Adding to the classpath on OSX

In OSX, you can set the classpath from scratch like this:

export CLASSPATH=/path/to/some.jar:/path/to/some/other.jar

Or you can add to the existing classpath like this:

export CLASSPATH=$CLASSPATH:/path/to/some.jar:/path/to/some/other.jar

This is answering your exact question, I'm not saying it's the right or wrong thing to do; I'll leave that for others to comment upon.

How do I do multiple CASE WHEN conditions using SQL Server 2008?

Its just that you need multiple When for a single case to behave it like if.. Elseif else..

   Case when 1=1       //if
   Then
    When 1=1              //else if
     Then.... 
    When .....              //else if
    Then 
    Else                      //else
   ....... 
     End

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

FileNotFoundError: [Errno 2] No such file or directory

You are using a relative path, which means that the program looks for the file in the working directory. The error is telling you that there is no file of that name in the working directory.

Try using the exact, or absolute, path.

Appending a list or series to a pandas DataFrame as a row?

Following onto Mike Chirico's answer... if you want to append a list after the dataframe is already populated...

>>> list = [['f','g']]
>>> df = df.append(pd.DataFrame(list, columns=['col1','col2']),ignore_index=True)
>>> df
  col1 col2
0    a    b
1    d    e
2    f    g

What is the difference between persist() and merge() in JPA and Hibernate?

The most important difference is this:

  • In case of persist method, if the entity that is to be managed in the persistence context, already exists in persistence context, the new one is ignored. (NOTHING happened)

  • But in case of merge method, the entity that is already managed in persistence context will be replaced by the new entity (updated) and a copy of this updated entity will return back. (from now on any changes should be made on this returned entity if you want to reflect your changes in persistence context)

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

I know this is an old question, but I wanted to add ServiceCapture to the list, for those who may come across this.

I've been using ServiceCapture for about 4 years and love it. It's not free, but it is a great tool and not very expensive. If you debug a lot of Flash or AJAX apps it is invaluable.

What is the difference between Scrum and Agile Development?

Waterfall methodology is a sequential design process. This means that as each of the eight stages (conception, initiation, analysis, design, construction, testing, implementation, and maintenance) are completed, the developers move on to the next step.

As this process is sequential, once a step has been completed, developers can’t go back to a previous step – not without scratching the whole project and starting from the beginning. There’s no room for change or error, so a project outcome and an extensive plan must be set in the beginning and then followed careful

ACP Agile Certification came about as a “solution” to the disadvantages of the waterfall methodology. Instead of a sequential design process, the Agile methodology follows an incremental approach. Developers start off with a simplistic project design, and then begin to work on small modules. The work on these modules is done in weekly or monthly sprints, and at the end of each sprint, project priorities are evaluated and tests are run. These sprints allow for bugs to be discovered, and customer feedback to be incorporated into the design before the next sprint is run.

The process, with its lack of initial design and steps, is often criticized for its collaborative nature that focuses on principles rather than process.

"No cached version... available for offline mode."

In my case I get the same error title could not resolve all dependencies for configuration

However suberror said, it was due to a linting jar not loaded with its url given saying status 502 received, I ran the deployment command again, this time it succeeded.

HTML 5 Geo Location Prompt in Chrome

For an easy workaround, just copy the HTML file to some cloud share, such as Dropbox, and use the shared link in your browser. Easy.

How to execute a shell script on a remote server using Ansible?

local_action runs the command on the local server, not on the servers you specify in hosts parameter.

Change your "Execute the script" task to

- name: Execute the script
  command: sh /home/test_user/test.sh

and it should do it.

You don't need to repeat sudo in the command line because you have defined it already in the playbook.

According to Ansible Intro to Playbooks user parameter was renamed to remote_user in Ansible 1.4 so you should change it, too

remote_user: test_user

So, the playbook will become:

---
- name: Transfer and execute a script.
  hosts: server
  remote_user: test_user
  sudo: yes
  tasks:
     - name: Transfer the script
       copy: src=test.sh dest=/home/test_user mode=0777

     - name: Execute the script
       command: sh /home/test_user/test.sh

Select by partial string from a pandas DataFrame

Based on github issue #620, it looks like you'll soon be able to do the following:

df[df['A'].str.contains("hello")]

Update: vectorized string methods (i.e., Series.str) are available in pandas 0.8.1 and up.

How to check if an excel cell is empty using Apache POI?

Gagravarr's answer is quite good!


Check if an excel cell is empty

But if you assume that a cell is also empty if it contains an empty String (""), you need some additional code. This can happen, if a cell was edited and then not cleared properly (for how to clear a cell properly, see further below).

I wrote myself a helper to check if an XSSFCell is empty (including an empty String).

 /**
 * Checks if the value of a given {@link XSSFCell} is empty.
 * 
 * @param cell
 *            The {@link XSSFCell}.
 * @return {@code true} if the {@link XSSFCell} is empty. {@code false}
 *         otherwise.
 */
public static boolean isCellEmpty(final XSSFCell cell) {
    if (cell == null) { // use row.getCell(x, Row.CREATE_NULL_AS_BLANK) to avoid null cells
        return true;
    }

    if (cell.getCellType() == Cell.CELL_TYPE_BLANK) {
        return true;
    }

    if (cell.getCellType() == Cell.CELL_TYPE_STRING && cell.getStringCellValue().trim().isEmpty()) {
        return true;
    }

    return false;
}

Pay attention for newer POI Version

They first changed getCellType() to getCellTypeEnum() as of Version 3.15 Beta 3 and then moved back to getCellType() as of Version 4.0.

  • Version >= 3.15 Beta 3:

    • Use CellType.BLANK and CellType.STRING instead of Cell.CELL_TYPE_BLANK and Cell.CELL_TYPE_STRING
  • Version >= 3.15 Beta 3 && Version < 4.0

    • Use Cell.getCellTypeEnum() instead of Cell.getCellType()

But better double check yourself, because they planned to change it back in future releases.


Example

This JUnit test shows the case in which the additional empty check is needed.

Scenario: the content of a cell is changed within a Java program. Later on, in the same Java program, the cell is checked for emptiness. The test will fail if the isCellEmpty(XSSFCell cell) function doesn't check for empty Strings.

@Test
public void testIsCellEmpty_CellHasEmptyString_ReturnTrue() {
    // Arrange
    XSSFCell cell = new XSSFWorkbook().createSheet().createRow(0).createCell(0);

    boolean expectedValue = true;
    boolean actualValue;

    // Act
    cell.setCellValue("foo");
    cell.setCellValue("bar");
    cell.setCellValue(" ");
    actualValue = isCellEmpty(cell);

    // Assert
    Assert.assertEquals(expectedValue, actualValue);
}

In addition: Clear a cell properly

Just in case if someone wants to know, how to clear the content of a cell properly. There are two ways to archive that (I would recommend way 1).

// way 1
public static void clearCell(final XSSFCell cell) {
    cell.setCellType(Cell.CELL_TYPE_BLANK);
}

// way 2
public static void clearCell(final XSSFCell cell) {
    String nullString = null;
    cell.setCellValue(nullString); 
}

Why way 1? Explicit is better than implicit (thanks, Python)

Way 1: sets the cell type explicitly back to blank.
Way 2: sets the cell type implicitly back to blank due to a side effect when setting a cell value to a null String.


Useful sources

Regards winklerrr

Running two projects at once in Visual Studio

Go to Solution properties ? Common Properties ? Startup Project and select Multiple startup projects.

Solution properties dialog

How do I pass a URL with multiple parameters into a URL?

You have to escape the & character. Turn your

&

into

&amp;

and you should be good.

How can I echo HTML in PHP?

Don't echo out HTML.

If you want to use

<?php echo "<h1>  $title; </h1>"; ?>

you should be doing this:

<h1><?= $title;?></h1>

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

Why Maven uses JDK 1.6 but my java -version is 1.7

Get into

/System/Library/Frameworks/JavaVM.framework/Versions

and update the CurrentJDK symbolic link to point to

/Library/Java/JavaVirtualMachines/YOUR_JDK_VERSION/Contents/

E.g.

cd /System/Library/Frameworks/JavaVM.framework/Versions
sudo rm CurrentJDK
sudo ln -s /Library/Java/JavaVirtualMachines/jdk1.8.0.jdk/Contents/ CurrentJDK

Now it shall work immediately.

How to open VMDK File of the Google-Chrome-OS bundle 2012?

you can also use vmware-mount from VMwares VDDK (Virtual Disk Development Kit): http://communities.vmware.com/community/vmtn/developer/forums/vddk

this allows you to mount VMDK files as disk drives in windows or linux

How do I multiply each element in a list by a number?

Multiplying each element in my_list by k:

k = 5
my_list = [1,2,3,4]
result = list(map(lambda x: x * k, my_list))

resulting in: [5, 10, 15, 20]

input[type='text'] CSS selector does not apply to default-type text inputs?

By CSS specifications, browsers may or may not use information about default attributes; mostly the don’t. The relevant clause in the CSS 2.1 spec is 5.8.2 Default attribute values in DTDs. In CSS 3 Selectors, it’s clause 6.3.4, with the same name. It recommends: “Selectors should be designed so that they work whether or not the default values are included in the document tree.”

It is generally best to explicitly specify essential attributes such as type=text instead of defaulting them. The reason is that there is no simple reliable way to refer to the input elements with defaulted type attribute.

HTTP requests and JSON parsing in Python

import urllib
import json

url = 'http://maps.googleapis.com/maps/api/directions/json?origin=Chicago,IL&destination=Los+Angeles,CA&waypoints=Joplin,MO|Oklahoma+City,OK&sensor=false'
result = json.load(urllib.urlopen(url))

How to change the Content of a <textarea> with JavaScript

Like this:

document.getElementById('myTextarea').value = '';

or like this in jQuery:

$('#myTextarea').val('');

Where you have

<textarea id="myTextarea" name="something">This text gets removed</textarea>

For all the downvoters and non-believers:

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true along with start:start, end:end in the second createReadStream arg.

The other part of the solution was to limit the max chunksize being sent in the response. The other answer set end like so:

var end = positions[1] ? parseInt(positions[1], 10) : total - 1;

...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).

I needed this stream to be closed because I was displaying the <video> element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.

My solution was just to set a maxChunk configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.

// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;

// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
  end = start + maxChunk - 1;
  chunksize = (end - start) + 1;
}

This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.

I also wrote a separate StackOverflow question and answer covering this issue.

Equivalent of typedef in C#

The best alternative to typedef that I've found in C# is using. For example, I can control float precision via compiler flags with this code:

#if REAL_T_IS_DOUBLE
using real_t = System.Double;
#else
using real_t = System.Single;
#endif

Unfortunately, it requires that you place this at the top of every file where you use real_t. There is currently no way to declare a global namespace type in C#.

How do I kill an Activity when the Back button is pressed?

Well, if you study the structure of how the application life-cycle works,here , then you'll come to know that onPause() is called when another activity gains focus, and onStop() is called when the activity is no longer visible.

From what I have learned yet, you can call finish() only from the activity which is active and/or has the focus. If you're calling finish() from the onPause() method that means you're calling it when the activity is no longer active. thus an exception is thrown.

When you're calling finish() from onStop() then the activity is being sent to background, thus will no longer be visible, then this exception.

When you press the back button, onStop() is called.

Most probably, Android will automatically do for you what you are currently wanting to do.

How to get the current logged in user Id in ASP.NET Core

If you want this in ASP.NET MVC Controller, use

using Microsoft.AspNet.Identity;

User.Identity.GetUserId();

You need to add using statement because GetUserId() won't be there without it.

The ternary (conditional) operator in C

It's crucial for code obfuscation, like this:

Look->       See?!

No
:(
Oh, well
);

Get all unique values in a JavaScript array (remove duplicates)

That's because 0 is a falsy value in JavaScript.

this[i] will be falsy if the value of the array is 0 or any other falsy value.

How to clone a Date object?

This is the cleanest approach

_x000D_
_x000D_
let dat = new Date() _x000D_
let copyOf = new Date(dat.valueOf())_x000D_
_x000D_
console.log(dat);_x000D_
console.log(copyOf);
_x000D_
_x000D_
_x000D_

Role/Purpose of ContextLoaderListener in Spring?

Your understanding is correct. I wonder why you don't see any advantages in ContextLoaderListener. For example, you need to build a session factory (to manage database). This operation can take some time, so it's better to do it on startup. Of course you can do it with init servlets or something else, but the advantage of Spring's approach is that you make configuration without writing code.

Set encoding and fileencoding to utf-8 in Vim

set encoding=utf-8  " The encoding displayed.
set fileencoding=utf-8  " The encoding written to file.

You may as well set both in your ~/.vimrc if you always want to work with utf-8.

What is the difference between tinyint, smallint, mediumint, bigint and int in MySQL?

The difference is the amount of memory allocated to each integer, and how large a number they each can store.

Git add all files modified, deleted, and untracked?

Try

git add -u

The "u" option stands for update. This will update the repo and actually delete files from the repo that you have deleted in your local copy.

git add -u [filename]

to stage a delete to just one file. Once pushed, the file will no longer be in the repo.

Alternatively,

git add -A .

is equivalent to

git add .

git add -u .

Note the extra '.' on git add -A and git add -u


Warning: Starting with git 2.0 (mid 2013), this will always stage files on the whole working tree.
If you want to stage files under the current path of your working tree, you need to use:

git add -A .

Also see: Difference of git add -A and git add .

OPTION (RECOMPILE) is Always Faster; Why?

Often when there is a drastic difference from run to run of a query I find that it is often one of 5 issues.

  1. STATISTICS - Statistics are out of date. A database stores statistics on the range and distribution of the types of values in various column on tables and indexes. This helps the query engine to develop a "Plan" of attack for how it will do the query, for example the type of method it will use to match keys between tables using a hash or looking through the entire set. You can call Update Statistics on the entire database or just certain tables or indexes. This slows down the query from one run to another because when statistics are out of date, its likely the query plan is not optimal for the newly inserted or changed data for the same query (explained more later below). It may not be proper to Update Statistics immediately on a Production database as there will be some overhead, slow down and lag depending on the amount of data to sample. You can also choose to use a Full Scan or Sampling to update Statistics. If you look at the Query Plan, you can then also view the statistics on the Indexes in use such using the command DBCC SHOW_STATISTICS (tablename, indexname). This will show you the distribution and ranges of the keys that the query plan is using to base its approach on.

  2. PARAMETER SNIFFING - The query plan that is cached is not optimal for the particular parameters you are passing in, even though the query itself has not changed. For example, if you pass in a parameter which only retrieves 10 out of 1,000,000 rows, then the query plan created may use a Hash Join, however if the parameter you pass in will use 750,000 of the 1,000,000 rows, the plan created may be an index scan or table scan. In such a situation you can tell the SQL statement to use the option OPTION (RECOMPILE) or an SP to use WITH RECOMPILE. To tell the Engine this is a "Single Use Plan" and not to use a Cached Plan which likely does not apply. There is no rule on how to make this decision, it depends on knowing the way the query will be used by users.

  3. INDEXES - Its possible that the query haven't changed, but a change elsewhere such as the removal of a very useful index has slowed down the query.

  4. ROWS CHANGED - The rows you are querying drastically changes from call to call. Usually statistics are automatically updated in these cases. However if you are building dynamic SQL or calling SQL within a tight loop, there is a possibility you are using an outdated Query Plan based on the wrong drastic number of rows or statistics. Again in this case OPTION (RECOMPILE) is useful.

  5. THE LOGIC Its the Logic, your query is no longer efficient, it was fine for a small number of rows, but no longer scales. This usually involves more indepth analysis of the Query Plan. For example, you can no longer do things in bulk, but have to Chunk things and do smaller Commits, or your Cross Product was fine for a smaller set but now takes up CPU and Memory as it scales larger, this may also be true for using DISTINCT, you are calling a function for every row, your key matches don't use an index because of CASTING type conversion or NULLS or functions... Too many possibilities here.

In general when you write a query, you should have some mental picture of roughly how certain data is distributed within your table. A column for example, can have an evenly distributed number of different values, or it can be skewed, 80% of the time have a specific set of values, whether the distribution will varying frequently over time or be fairly static. This will give you a better idea of how to build an efficient query. But also when debugging query performance have a basis for building a hypothesis as to why it is slow or inefficient.

replace all occurrences in a string

As explained here, you can use:

function replaceall(str,replace,with_this)
{
    var str_hasil ="";
    var temp;

    for(var i=0;i<str.length;i++) // not need to be equal. it causes the last change: undefined..
    {
        if (str[i] == replace)
        {
            temp = with_this;
        }
        else
        {
                temp = str[i];
        }

        str_hasil += temp;
    }

    return str_hasil;
}

... which you can then call using:

var str = "50.000.000";
alert(replaceall(str,'.',''));

The function will alert "50000000"

Bash foreach loop

xargs --arg-file inputfile cat

This will output the filename followed by the file's contents:

xargs --arg-file inputfile -I % sh -c "echo %; cat %"

How to use Bootstrap 4 in ASP.NET Core

Libman seems to be the tool preferred by Microsoft now. It is integrated in Visual Studio 2017(15.8).

This article describes how to use it and even how to set up a restore performed by the build process.

Bootstrap's documentation tells you what files you need in your project.

The following example should work as a configuration for libman.json.

{
  "version": "1.0",
  "defaultProvider": "cdnjs",
  "libraries": [
  {
    "library": "[email protected]",
    "destination": "wwwroot/lib/bootstrap",
    "files": [
    "js/bootstrap.bundle.js",
    "css/bootstrap.min.css"
    ]
  },
  {
    "library": "[email protected]",
    "destination": "wwwroot/lib/jquery",
    "files": [
      "jquery.min.js"
    ]
  }
]
}

Why is visible="false" not working for a plain html table?

If you want use it, use runat="server" for that table. After that use tablename.visible=False in server side code.

Environment variable substitution in sed

VAR=8675309
echo "abcde:jhdfj$jhbsfiy/.hghi$jh:12345:dgve::" |\
sed 's/:[0-9]*:/:'$VAR':/1' 

where VAR contains what you want to replace the field with

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

What version of tomcat are you using ? What appears to me is that the tomcat version is not supporting the servlet & jsp versions you're using. You can change to something like below or look into your version of tomcat on what it supports and change the versions accordingly.

 <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>