Programs & Examples On #Open session in view

Open Session In View (OSIV) is pattern where persistence context (session) is open and available in the presentation layer and closed at the end of the HTTP request.

How to show PIL Image in ipython notebook

much simpler in jupyter using pillow.

from PIL import Image
image0=Image.open('image.png')
image0

Difference between Dictionary and Hashtable

There is one more important difference between a HashTable and Dictionary. If you use indexers to get a value out of a HashTable, the HashTable will successfully return null for a non-existent item, whereas the Dictionary will throw an error if you try accessing a item using a indexer which does not exist in the Dictionary

What is the default initialization of an array in Java?

Every class in Java have a constructor ( a constructor is a method which is called when a new object is created, which initializes the fields of the class variables ). So when you are creating an instance of the class, constructor method is called while creating the object and all the data values are initialized at that time.

For object of integer array type all values in the array are initialized to 0(zero) in the constructor method. Similarly for object of boolean array, all values are initialized to false.

So Java is initializing the array by running its constructor method while creating the object

How to get Chrome to allow mixed content?

In Windows open the Run window (Win + R):

C:\Program Files (x86)\Google\Chrome\Application\chrome.exe  --allow-running-insecure-content

In OS-X Terminal.app run the following command +space:

open /Applications/Google\ Chrome.app --args --allow-running-insecure-content

Note: You seem to be able to add the argument --allow-running-insecure-content to bypass this for development. But its not a recommended solution.

Integer value comparison

To figure out if an Integer is greater than 0, you can:

  • check if compareTo(O) returns a positive number:

    if (count.compareTo(0) > 0)
         ...
    

    But that looks pretty silly, doesn't it? Better just...

  • use autoboxing1:

    if (count > 0)
        ....
    

    This is equivalent to:

    if (count.intValue() > 0)
        ...
    

    It is important to note that "==" is evaluated like this, with the Integer operand unboxed rather than the int operand boxed. Otherwise, count == 0 would return false when count was initialized as new Integer(0) (because "==" tests for reference equality).

1Technically, the first example uses autoboxing (before Java 1.5 you couldn't pass an int to compareTo) and the second example uses unboxing. The combined feature is often simply called "autoboxing" for short, which is often then extended into calling both types of conversions "autoboxing". I apologize for my lax usage of terminology.

Handling 'Sequence has no elements' Exception

I had the same issue, i realized i had deleted the default image that was in the folder just update the media missing, on the specific file

Use own username/password with git and bitbucket

Well, it's part of BitBucket philosophy and workflow:

  • Repository may have only one user: owner
  • For ordinary accounts (end-user's) collaboration expect "fork-pull request" workflow

i.e you can't (in usual case) commit into foreign repo under own credentials.

You have two possible solutions:

  1. "Classic" BB-way: fork repo (get owned by you repository), make changes, send pull request to origin repo
  2. Create "Team", add user-accounts as members of team, make Team owner of repository - it this case for this "Shared central" repository every team memeber can push under own credentials - inspect thg repository and TortoiseHg Team, owner of this repository, as samples

react-native - Fit Image in containing View, not the whole screen size

I could not get the example working using the resizeMode properties of Image, but because the images will all be square there is a way to do it using the Dimensions of the window along with flexbox.

Set flexDirection: 'row', and flexWrap: 'wrap', then they will all line up as long as they are all the same dimensions.

I set it up here

https://snack.expo.io/HkbZNqjeZ

"use strict";

var React = require("react-native");
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Image,
  TouchableOpacity,
  Dimensions,
  ScrollView
} = React;

var deviceWidth = Dimensions.get("window").width;
var temp = "http://thumbs.dreamstime.com/z/close-up-angry-chihuahua-growling-2-years-old-15126199.jpg";
var SampleApp = React.createClass({
  render: function() {
    var images = [];

    for (var i = 0; i < 10; i++) {
      images.push(
        <TouchableOpacity key={i} activeOpacity={0.75} style={styles.item}>
          <Image style={styles.image} source={{ uri: temp }} />
        </TouchableOpacity>
      );
    }

    return (
      <ScrollView style={{ flex: 1 }}>
        <View style={styles.container}>
          {images}
        </View>
      </ScrollView>
    );
  }
});

Run all SQL files in a directory

You can create a single script that calls all the others.

Put the following into a batch file:

@echo off
echo.>"%~dp0all.sql"
for %%i in ("%~dp0"*.sql) do echo @"%%~fi" >> "%~dp0all.sql"

When you run that batch file it will create a new script named all.sql in the same directory where the batch file is located. It will look for all files with the extension .sql in the same directory where the batch file is located.

You can then run all scripts by using sqlplus user/pwd @all.sql (or extend the batch file to call sqlplus after creating the all.sql script)

Cursor inside cursor

This smells of something that should be done with a JOIN instead. Can you share the larger problem with us?


Hey, I should be able to get this down to a single statement, but I haven't had time to play with it further yet today and may not get to. In the mean-time, know that you should be able to edit the query for your inner cursor to create the row numbers as part of the query using the ROW_NUMBER() function. From there, you can fold the inner cursor into the outer by doing an INNER JOIN on it (you can join on a sub query). Finally, any SELECT statement can be converted to an UPDATE using this method:

UPDATE [YourTable/Alias]
   SET [Column] = q.Value
FROM
(
   ... complicate select query here ...
) q

Where [YourTable/Alias] is a table or alias used in the select query.

Skip over a value in the range function in python

It depends on what you want to do. For example you could stick in some conditionals like this in your comprehensions:

# get the squares of each number from 1 to 9, excluding 2
myList = [i**2 for i in range(10) if i != 2]
print(myList)

# --> [0, 1, 9, 16, 25, 36, 49, 64, 81]

Complex CSS selector for parent of active child

Another thought occurred to me just now that could be a pure CSS solution. Display your active class as an absolutely positioned block and set its style to cover up the parent li.

a.active {
   position:absolute;
   display:block;
   width:100%;
   height:100%;
   top:0em;
   left:0em;
   background-color: whatever;
   border: whatever;
}
/* will also need to make sure the parent li is a positioned element so... */
ul.menu li {
    position:relative;
}    

For those of you who want to use javascript without jquery...

Selecting the parent is trivial. You need a getElementsByClass function of some sort, unless you can get your drupal plugin to assign the active item an ID instead of Class. The function I provided I grabbed from some other genius on SO. It works well, just keep in mind when you're debugging that the function will always return an array of nodes, not just a single node.

active_li = getElementsByClass("active","a");
active_li[0].parentNode.style.whatever="whatever";

function getElementsByClass(node,searchClass,tag) {
    var classElements = new Array();
    var els = node.getElementsByTagName(tag); // use "*" for all elements
    var elsLen = els.length;
    var pattern = new RegExp("\\b"+searchClass+"\\b");
    for (i = 0, j = 0; i < elsLen; i++) {
       if ( pattern.test(els[i].className) ) {
       classElements[j] = els[i];
       j++;
   }
}
return classElements;
}

Bash integer comparison

The zeroth parameter of a shell command is the command itself (or sometimes the shell itself). You should be using $1.

(("$#" < 1)) && ( (("$1" != 1)) ||  (("$1" -ne 0q)) )

Your boolean logic is also a bit confused:

(( "$#" < 1 && # If the number of arguments is less than one…
  "$1" != 1 || "$1" -ne 0)) # …how can the first argument possibly be 1 or 0?

This is probably what you want:

(( "$#" )) && (( $1 == 1 || $1 == 0 )) # If true, there is at least one argument and its value is 0 or 1

What are the best use cases for Akka framework

We use Akka in spoken dialog systems (primetalk). Both internally and externally. In order to simultaneously run a lot of telephony channels on a single cluster node it is obviously necessary to have some multithreading framework. Akka works just perfect. We have previous nightmare with the java-concurrency. And with Akka it is just like a swing — it simply works. Robust and reliable. 24*7, non-stop.

Inside a channel we have real-time stream of events that are processed in parallel. In particular: - lengthy automatic speech recognition — is done with an actor; - audio output producer that mixes a few audio sources (including synthesized speech); - text-to-speech conversion is a separate set of actors shared between channels; - semantic and knowledge processing.

To make interconnections of complex signal processing we use SynapseGrid. It has the benefit of compile-time checking of the DataFlow in the complex actor systems.

IOError: [Errno 32] Broken pipe: Python

The problem is due to SIGPIPE handling. You can solve this problem using the following code:

from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL) 

See here for background on this solution. Better answer here.

Check if inputs form are empty jQuery

$(document).ready(function () {
  $('input[type="text"]').blur(function () {
    if (!$(this).val()) {
      $(this).addClass('error');
    } else {
      $(this).removeClass('error');
    }
  });
});


<style>
 .error {
   border: 1px solid #ff0000;
 }
</style>

jquery count li elements inside ul -> length?

Warning: Answers above only work most of the time!

In jQuery version 3.3.1 (haven't tested other versions)

$("#myList li").length; 

works only if your list items don't wrap. If your items wrap in the list then this code counts the number of lines occupied not the number of <li> elements.

$("#myList").children().length;

gets the actual number of <li> elements in your list not the number of lines that are occupied.

How to log SQL statements in Spring Boot?

Translated accepted answer to YAML works for me

logging:
  level:
    org:
      hibernate:
        SQL:
          TRACE
        type:
          descriptor:
            sql:
              BasicBinder:
                TRACE

How to show imageView full screen on imageView click?

You can use ImageView below two properties to show image based on your requirement :

  1. android:adjustViewBounds : Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable.

  2. android:scaleType :Controls how the image should be resized or moved to match the size of this ImageView

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:src="@drawable/ic_launcher"/>
    

Above two properties can be use either xml or java code.

As you need to decide at run time need to show image into full screen or not so will apply above two properties at java code as below :

public class MainActivity extends Activity {

    ImageView imageView;

    boolean isImageFitToScreen;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView) findViewById(R.id.imageView);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isImageFitToScreen) {
                    isImageFitToScreen=false;
                    imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                    imageView.setAdjustViewBounds(true);
                }else{
                    isImageFitToScreen=true;
                    imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                }
            }
        });

    }
}

Changing Java Date one hour back

You can use from bellow code for date and time :

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
       //get current date time with Calendar()
       Calendar cal = Calendar.getInstance();
       System.out.println("Current Date Time : " + dateFormat.format(cal.getTime()));

       cal.add(Calendar.DATE, 1);
       System.out.println("Add one day to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.MONTH, 1);
       System.out.println("Add one month to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.YEAR, 1);
       System.out.println("Add one year to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.HOUR, 1);
       System.out.println("Add one hour to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.MINUTE, 1);
       System.out.println("Add one minute to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.SECOND, 1);
       System.out.println("Add one second to current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.DATE, -1);
       System.out.println("Subtract one day from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.MONTH, -1);
       System.out.println("Subtract one month from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.YEAR, -1);
       System.out.println("Subtract one year from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.HOUR, -1);
       System.out.println("Subtract one hour from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.MINUTE, -1);
       System.out.println("Subtract one minute from current date : " + dateFormat.format(cal.getTime()));

       cal = Calendar.getInstance();
       cal.add(Calendar.SECOND, -1);
       System.out.println("Subtract one second from current date : " + dateFormat.format(cal.getTime()));

Output :

Current Date Time : 2008/12/28 10:24:53
Add one day to current date : 2008/12/29 10:24:53
Add one month to current date : 2009/01/28 10:24:53
Add one year to current date : 2009/12/28 10:24:53
Add one hour to current date : 2008/12/28 11:24:53
Add one minute to current date : 2008/12/28 10:25:53
Add one second to current date : 2008/12/28 10:24:54
Subtract one day from current date : 2008/12/27 10:24:53
Subtract one month from current date : 2008/11/28 10:24:53
Subtract one year from current date : 2007/12/28 10:24:53
Subtract one hour from current date : 2008/12/28 09:24:53
Subtract one minute from current date : 2008/12/28 10:23:53
Subtract one second from current date : 2008/12/28 10:24:52

This link is good : See here

And see : See too

And : Here

And : Here

And : Here

If you need just time :

DateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

How to subtract 30 days from the current date using SQL Server

SELECT DATEADD(day,-30,date) AS before30d 
FROM...

But it is strongly recommended to keep date in datetime column, not varchar.

How to draw vertical lines on a given plot in matplotlib

matplotlib.pyplot.vlines vs. matplotlib.pyplot.axvline

  • The difference is that vlines accepts 1 or more locations for x, while axvline permits one location.
    • Single location: x=37
    • Multiple locations: x=[37, 38, 39]
  • vlines takes ymin and ymax as a position on the y-axis, while axvline takes ymin and ymax as a percentage of the y-axis range.
    • When passing multiple lines to vlines, pass a list to ymin and ymax.
  • If you're plotting a figure with something like fig, ax = plt.subplots(), then replace plt.vlines or plt.axvline with ax.vlines or ax.axvline, respectively.
import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)

plt.figure(figsize=(10, 7))

# only one line may be specified; full height
plt.axvline(x=36, color='b', label='axvline - full height')

# only one line may be specified; ymin & ymax spedified as a percentage of y-range
plt.axvline(x=36.25, ymin=0.05, ymax=0.95, color='b', label='axvline - % of full height')

# multiple lines all full height
plt.vlines(x=[37, 37.25, 37.5], ymin=0, ymax=len(xs), colors='purple', ls='--', lw=2, label='vline_multiple - full height')

# multiple lines with varying ymin and ymax
plt.vlines(x=[38, 38.25, 38.5], ymin=[0, 25, 75], ymax=[200, 175, 150], colors='teal', ls='--', lw=2, label='vline_multiple - partial height')

# single vline with full ymin and ymax
plt.vlines(x=39, ymin=0, ymax=len(xs), colors='green', ls=':', lw=2, label='vline_single - full height')

# single vline with specific ymin and ymax
plt.vlines(x=39.25, ymin=25, ymax=150, colors='green', ls=':', lw=2, label='vline_single - partial height')

# place legend outside
plt.legend(bbox_to_anchor=(1.0, 1), loc='upper left')

plt.show()

enter image description here

Landscape printing from HTML

Quoted from CSS-Discuss Wiki

The @page rule has been cut down in scope from CSS2 to CSS2.1. The full CSS2 @page rule was reportedly implemented only in Opera (and buggily even then). My own testing shows that IE and Firefox don't support @page at all. According to the now-obsolescent CSS2 spec section 13.2.2 it is possible to override the user's setting of orientation and (for example) force printing in Landscape but the relevant "size" property has been dropped from CSS2.1, consistent with the fact that no current browser supports it. It has been reinstated in the CSS3 Paged Media module but note that this is only a Working Draft (as at July 2009).

Conclusion: forget about @page for the present. If you feel your document needs to be printed in Landscape orientation, ask yourself if you can instead make your design more fluid. If you really can't (perhaps because the document contains data tables with many columns, for example), you will need to advise the user to set the orientation to Landscape and perhaps outline how to do it in the most common browsers. Of course, some browsers have a print fit-to-width (shrink-to-fit) feature (e.g. Opera, Firefox, IE7) but it's inadvisable to rely on users having this facility or having it switched on.

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

Since your server already includes the sites-enabled folder ( notice the include /etc/nginx/sites-enabled/* line ), then you better use that.

  1. Create a file inside /etc/nginx/sites-available and call it whatever you want, I'll call it django since it's a djanog server

    sudo touch /etc/nginx/sites-available/django
    
  2. Then create a symlink that points to it

    sudo ln -s /etc/nginx/sites-available/django /etc/nginx/sites-enabled
    
  3. Then edit that file with whatever file editor you use, vim or nano or whatever and create the server inside it

    server {
        # hostname or ip or multiple separated by spaces
        server_name localhost example.com 192.168.1.1; #change to your setting
        location / {
            root /home/techcee/scrapbook/local/lib/python2.7/site-packages/django/__init__.pyc/;
        }
    }
    
  4. Restart or reload nginx settings

    sudo service nginx reload
    

Note I believe that your configuration like this probably won't work yet because you need to pass it to a fastcgi server or something, but at least this is how you could create a valid server

Address validation using Google Maps API

The answer probably depends how critical it is for you to receive support and possible customization for this service.

Google can certainly do this. Look into their XML and Geocoding API's. You should be able to craft an XML message asking Google to return Map coordinates for a given address. If the address is not found (invalid), you will receive an appropriate response. Here's a useful page: http://code.google.com/apis/maps/documentation/services.html#XML_Requests

Note that Google's aim in providing the Maps API is to plot addresses on actual maps. While you can certainly use the data for other purposes, you are at the mercy of Google should one of their maps not exactly correspond to your legal or commercial address validation needs. If you paid for one of the services you mentioned, you would likely be able to receive support should certain addresses not resolve the way you expect them to.

In other words, you get what you pay for ;) . If you have the time, though, why not try implementing a Google-based solution then going from there? The API looks pretty slick, and it's free, after all.

The network path was not found

Possibly also check the sessionState tag in Web.config

Believe it or not, some projects I've worked on will set a connection string here as well.

Setting this config to:

<sessionState mode="InProc" />

Fixed this issue in my case after checking all other connection strings were correct.

Java ArrayList for integers

you should not use Integer[] array inside the list as arraylist itself is a kind of array. Just leave the [] and it should work

CMAKE_MAKE_PROGRAM not found

I had the exact same problem when I tried to compile OpenCV with Qt Creator (MinGW) to build the .a static library files.

For those that installed Qt 5.2.1 for Windows 32-bit (MinGW 4.8, OpenGL, 634 MB), this problem can be fixed if you add the following to the system's environment variable Path:

C:\Qt\Qt5.2.0\Tools\mingw48_32\bin

Process.start: how to get the output?

You can process your output synchronously or asynchronously.

1. Synchronous example

static void runCommand()
{
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR"; // Note the /c command (*)
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    process.Start();
    //* Read the output (or the error)
    string output = process.StandardOutput.ReadToEnd();
    Console.WriteLine(output);
    string err = process.StandardError.ReadToEnd();
    Console.WriteLine(err);
    process.WaitForExit();
}

Note that it's better to process both output and errors: they must be handled separately.

(*) For some commands (here StartInfo.Arguments) you must add the /c directive, otherwise the process freezes in the WaitForExit().

2. Asynchronous example

static void runCommand() 
{
    //* Create your Process
    Process process = new Process();
    process.StartInfo.FileName = "cmd.exe";
    process.StartInfo.Arguments = "/c DIR";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;
    //* Set your output and error (asynchronous) handlers
    process.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
    process.ErrorDataReceived += new DataReceivedEventHandler(OutputHandler);
    //* Start process and handlers
    process.Start();
    process.BeginOutputReadLine();
    process.BeginErrorReadLine();
    process.WaitForExit();
}

static void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) 
{
    //* Do your stuff with the output (write to console/log/StringBuilder)
    Console.WriteLine(outLine.Data);
}

If you don't need to do complicate operations with the output, you can bypass the OutputHandler method, just adding the handlers directly inline:

//* Set your output and error (asynchronous) handlers
process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data);
process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data);

EF Migrations: Rollback last applied migration?

Update-Database –TargetMigration:"Your migration name"

For this problem I suggest this link:

https://elegantcode.com/2012/04/12/entity-framework-migrations-tips/

javascript regex - look behind alternative?

EDIT: From ECMAScript 2018 onwards, lookbehind assertions (even unbounded) are supported natively.

In previous versions, you can do this:

^(?:(?!filename\.js$).)*\.js$

This does explicitly what the lookbehind expression is doing implicitly: check each character of the string if the lookbehind expression plus the regex after it will not match, and only then allow that character to match.

^                 # Start of string
(?:               # Try to match the following:
 (?!              # First assert that we can't match the following:
  filename\.js    # filename.js 
  $               # and end-of-string
 )                # End of negative lookahead
 .                # Match any character
)*                # Repeat as needed
\.js              # Match .js
$                 # End of string

Another edit:

It pains me to say (especially since this answer has been upvoted so much) that there is a far easier way to accomplish this goal. There is no need to check the lookahead at every character:

^(?!.*filename\.js$).*\.js$

works just as well:

^                 # Start of string
(?!               # Assert that we can't match the following:
 .*               # any string, 
  filename\.js    # followed by filename.js
  $               # and end-of-string
)                 # End of negative lookahead
.*                # Match any string
\.js              # Match .js
$                 # End of string

error LNK2001: unresolved external symbol (C++)

Sounds like you are using Microsoft Visual C++. If that is the case, then the most possibility is that you don't compile your two.cpp with one.cpp (one.cpp is the implementation for one.h).

If you are from command line (cmd.exe), then try this first: cl -o two.exe one.cpp two.cpp

If you are from IDE, right click on the project name from Solution Explore. Then choose Add, Existing Item.... Add one.cpp into your project.

How to create a file in Linux from terminal window?

Depending on what you want the file to contain:

  • touch /path/to/file for an empty file
  • somecommand > /path/to/file for a file containing the output of some command.

      eg: grep --help > randomtext.txt
          echo "This is some text" > randomtext.txt
    
  • nano /path/to/file or vi /path/to/file (or any other editor emacs,gedit etc)
    It either opens the existing one for editing or creates & opens the empty file to enter, if it doesn't exist


Create the file using cat

$ cat > myfile.txt

Now, just type whatever you want in the file:

Hello World!

CTRL-D to save and exit


There are several possible solutions:

Create an empty file

touch file

>file

echo -n > file

printf '' > file

The echo version will work only if your version of echo supports the -n switch to suppress newlines. This is a non-standard addition. The other examples will all work in a POSIX shell.

Create a file containing a newline and nothing else

echo '' > file

printf '\n' > file

This is a valid "text file" because it ends in a newline.

Write text into a file

"$EDITOR" file

echo 'text' > file

cat > file <<END \
text
END

printf 'text\n' > file

These are equivalent. The $EDITOR command assumes that you have an interactive text editor defined in the EDITOR environment variable and that you interactively enter equivalent text. The cat version presumes a literal newline after the \ and after each other line. Other than that these will all work in a POSIX shell.

Of course there are many other methods of writing and creating files, too.

Error Message : Cannot find or open the PDB file

I'm also a newbie to CUDA/Visual studio and encountered the same problem with a couple of the samples. If you run DEBUG-> Start Debugging, then repeatedly step over (F10) you'll see the output window appear and get populated. Normal execution returns nomal completion status 0x0 (as you observed) and the output window is closed.

How to create and handle composite primary key in JPA

The MyKey class (@Embeddable) should not have any relationships like @ManyToOne

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();

how to prevent css inherit

While this isn't currently available, this fascinating article discusses the use of the Shadow DOM, which is a technique used by browsers to limit how far cascading style sheets cascade, so to speak. He doesn't provide any APIs, as it seems that there are no current libraries able to provide access to this part of the DOM, but it's worth a look. There are links to mailing lists at the bottom of the article if this intrigues you.

How to check date of last change in stored procedure or function in SQL server

For SQL 2000 I would use:

SELECT name, crdate, refdate 
FROM sysobjects
WHERE type = 'P' 
ORDER BY refdate desc

Best way to reverse a string

This is the code used for reverse string

public Static void main(){
    string text = "Test Text";
    Console.Writeline(RevestString(text))
}

public Static string RevestString(string text){
    char[] textToChar = text.ToCharArray();
    string result= string.Empty;
    int length = textToChar .Length;
    for (int i = length; i > 0; --i)
    result += textToChar[i - 1];
    return result;
}

How to create a toggle button in Bootstrap

Here this very usefull For Bootstrap Toggle Button . Example in code snippet!! and jsfiddle below.

_x000D_
_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">_x000D_
    <script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>_x000D_
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">_x000D_
    <input id="toggle-trigger" type="checkbox" checked data-toggle="toggle">_x000D_
    <button class="btn btn-success" onclick="toggleOn()">On by API</button>_x000D_
<button class="btn btn-danger" onclick="toggleOff()">Off by API</button>_x000D_
<button class="btn btn-primary" onclick="getValue()">Get Value</button>_x000D_
<script>_x000D_
  //If you want to change it dynamically_x000D_
  function toggleOn() {_x000D_
    $('#toggle-trigger').bootstrapToggle('on')_x000D_
  }_x000D_
  function toggleOff() {_x000D_
    $('#toggle-trigger').bootstrapToggle('off')  _x000D_
  }_x000D_
  //if you want get value_x000D_
  function getValue()_x000D_
  {_x000D_
   var value=$('#toggle-trigger').bootstrapToggle().prop('checked');_x000D_
   console.log(value);_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_ I showed you a few examples above. I hope it helps. Js Fiddle is here Source code is avaible on GitHub.

Update 2020 For Bootstrap 4

I recommended bootstrap4-toggle in 2020.

_x000D_
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
_x000D_
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>_x000D_
_x000D_
<link href="https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/css/bootstrap4-toggle.min.css" rel="stylesheet">_x000D_
<script src="https://cdn.jsdelivr.net/gh/gitbrent/[email protected]/js/bootstrap4-toggle.min.js"></script>_x000D_
_x000D_
<input id="toggle-trigger" type="checkbox" checked data-toggle="toggle" data-onstyle="success">_x000D_
<button class="btn btn-success" onclick="toggleOn()">On by API</button>_x000D_
<button class="btn btn-danger" onclick="toggleOff()">Off by API</button>_x000D_
<button class="btn btn-primary" onclick="getValue()">Get Value</button>_x000D_
_x000D_
<script>_x000D_
  //If you want to change it dynamically_x000D_
  function toggleOn() {_x000D_
    $('#toggle-trigger').bootstrapToggle('on')_x000D_
  }_x000D_
  function toggleOff() {_x000D_
    $('#toggle-trigger').bootstrapToggle('off')  _x000D_
  }_x000D_
  //if you want get value_x000D_
  function getValue()_x000D_
  {_x000D_
   var value=$('#toggle-trigger').bootstrapToggle().prop('checked');_x000D_
   console.log(value);_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

What is the idiomatic Go equivalent of C's ternary operator?

Suppose you have the following ternary expression (in C):

int a = test ? 1 : 2;

The idiomatic approach in Go would be to simply use an if block:

var a int

if test {
  a = 1
} else {
  a = 2
}

However, that might not fit your requirements. In my case, I needed an inline expression for a code generation template.

I used an immediately evaluated anonymous function:

a := func() int { if test { return 1 } else { return 2 } }()

This ensures that both branches are not evaluated as well.

Generate a range of dates using SQL

 SELECT (sysdate-365 + (LEVEL -1)) AS DATES
 FROM DUAL connect by level <=( sysdate-(sysdate-365))

if a 'from' and a 'to' date is replaced in place of sysdate and sysdate-365, the output will be a range of dates between the from and to date.

Pass Javascript variable to PHP via ajax

Since you're not using JSON as the data type no your AJAX call, I would assume that you can't access the value because the PHP you gave will only ever be true or false. isset is a function to check if something exists and has a value, not to get access to the value.

Change your PHP to be:

$uid = (isset($_POST['userID'])) ? $_POST['userID'] : 0;

The above line will check to see if the post variable exists. If it does exist it will set $uid to equal the posted value. If it does not exist then it will set $uid equal to 0.

Later in your code you can check the value of $uid and react accordingly

if($uid==0) {
    echo 'User ID not found';
}

This will make your code more readable and also follow what I consider to be best practices for handling data in PHP.

How do I import .sql files into SQLite 3?

Alternatively, you can do this from a Windows commandline prompt/batch file:

sqlite3.exe DB.db ".read db.sql"

Where DB.db is the database file, and db.sql is the SQL file to run/import.

Is there an "if -then - else " statement in XPath?

Unfortunately the previous answers were no option for me so i researched for a while and found this solution:

http://blog.alessio.marchetti.name/post/2011/02/12/the-Oliver-Becker-s-XPath-method

I use it to output text if a certain Node exists. 4 is the length of the text foo. So i guess a more elegant solution would be the use of a variable.

substring('foo',number(not(normalize-space(/elements/the/element/)))*4)

how to achieve transfer file between client and server using java socket

Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.

http://www.rgagnon.com/javadetails/java-0542.html

Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.

package filesendtest;

import java.io.*;
import java.net.*;

class TCPServer {

    private final static String fileToSend = "C:\\test1.pdf";

    public static void main(String args[]) {

        while (true) {
            ServerSocket welcomeSocket = null;
            Socket connectionSocket = null;
            BufferedOutputStream outToClient = null;

            try {
                welcomeSocket = new ServerSocket(3248);
                connectionSocket = welcomeSocket.accept();
                outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
            } catch (IOException ex) {
                // Do exception handling
            }

            if (outToClient != null) {
                File myFile = new File( fileToSend );
                byte[] mybytearray = new byte[(int) myFile.length()];

                FileInputStream fis = null;

                try {
                    fis = new FileInputStream(myFile);
                } catch (FileNotFoundException ex) {
                    // Do exception handling
                }
                BufferedInputStream bis = new BufferedInputStream(fis);

                try {
                    bis.read(mybytearray, 0, mybytearray.length);
                    outToClient.write(mybytearray, 0, mybytearray.length);
                    outToClient.flush();
                    outToClient.close();
                    connectionSocket.close();

                    // File sent, exit the main method
                    return;
                } catch (IOException ex) {
                    // Do exception handling
                }
            }
        }
    }
}

package filesendtest;

import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;

class TCPClient {

    private final static String serverIP = "127.0.0.1";
    private final static int serverPort = 3248;
    private final static String fileOutput = "C:\\testout.pdf";

    public static void main(String args[]) {
        byte[] aByte = new byte[1];
        int bytesRead;

        Socket clientSocket = null;
        InputStream is = null;

        try {
            clientSocket = new Socket( serverIP , serverPort );
            is = clientSocket.getInputStream();
        } catch (IOException ex) {
            // Do exception handling
        }

        ByteArrayOutputStream baos = new ByteArrayOutputStream();

        if (is != null) {

            FileOutputStream fos = null;
            BufferedOutputStream bos = null;
            try {
                fos = new FileOutputStream( fileOutput );
                bos = new BufferedOutputStream(fos);
                bytesRead = is.read(aByte, 0, aByte.length);

                do {
                        baos.write(aByte);
                        bytesRead = is.read(aByte);
                } while (bytesRead != -1);

                bos.write(baos.toByteArray());
                bos.flush();
                bos.close();
                clientSocket.close();
            } catch (IOException ex) {
                // Do exception handling
            }
        }
    }
}

Related

Byte array of unknown length in java

Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):

public static String md5String(File file) {
    try {
        InputStream fin = new FileInputStream(file);
        java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
        byte[] buffer = new byte[1024];
        int read;
        do {
            read = fin.read(buffer);
            if (read > 0) {
                md5er.update(buffer, 0, read);
            }
        } while (read != -1);
        fin.close();
        byte[] digest = md5er.digest();
        if (digest == null) {
            return null;
        }
        String strDigest = "0x";
        for (int i = 0; i < digest.length; i++) {
            strDigest += Integer.toString((digest[i] & 0xff)
                    + 0x100, 16).substring(1).toUpperCase();
        }
        return strDigest;
    } catch (Exception e) {
        return null;
    }
}

How to merge lists into a list of tuples?

One alternative without using zip:

list_c = [(p1, p2) for idx1, p1 in enumerate(list_a) for idx2, p2 in enumerate(list_b) if idx1==idx2]

In case one wants to get not only tuples 1st with 1st, 2nd with 2nd... but all possible combinations of the 2 lists, that would be done with

list_d = [(p1, p2) for p1 in list_a for p2 in list_b]

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

See the details about entryComponent:

If you are loading any component dynamically then you need to put it in both declarations and entryComponent:

@NgModule({
  imports: [...],
  exports: [...],
  entryComponents: [ConfirmComponent,..],
  declarations: [ConfirmComponent,...],
  providers: [...]
})

IF - ELSE IF - ELSE Structure in Excel

Say P7 is a Cell then you can use the following Syntex to check the value of the cell and assign appropriate value to another cell based on this following nested if:

=IF(P7=0,200,IF(P7=1,100,IF(P7=2,25,IF(P7=3,10,IF((P7=4),5,0)))))

need to test if sql query was successful

global $DB;
$status = $DB->query("UPDATE exp_members SET group_id = '$group_id' WHERE member_id = '$member_id'");

if($status == false)
{ 
    die("Didn't Update"); 
}

If you are using mysql_query in the backend (whatever $DB->query() uses to query the database), it will return a TRUE or FALSE for INSERT, UPDATE, and DELETE (and a few others), commands, based on their status.

Java - removing first character of a string

My version of removing leading chars, one or multiple. For example, String str1 = "01234", when removing leading '0', result will be "1234". For a String str2 = "000123" result will be again "123". And for String str3 = "000" result will be empty string: "". Such functionality is often useful when converting numeric strings into numbers.The advantage of this solution compared with regex (replaceAll(...)) is that this one is much faster. This is important when processing large number of Strings.

 public static String removeLeadingChar(String str, char ch) {
    int idx = 0;
    while ((idx < str.length()) && (str.charAt(idx) == ch))
        idx++;
    return str.substring(idx);
}

invalid byte sequence for encoding "UTF8"

some of lolutions may be very sambles

i there any spaces in the name of comlun will be cause this problem

review every columns name for exaple "colum_name "#>>rong "colum_nam" #>>right

What does the 'Z' mean in Unix timestamp '120314170138Z'?

The Z stands for 'Zulu' - your times are in UTC. From Wikipedia:

The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time. This is especially true in aviation, where Zulu is the universal standard.

T-SQL Cast versus Convert

CAST is standard SQL, but CONVERT is only for the dialect T-SQL. We have a small advantage for convert in the case of datetime.

With CAST, you indicate the expression and the target type; with CONVERT, there’s a third argument representing the style for the conversion, which is supported for some conversions, like between character strings and date and time values. For example, CONVERT(DATE, '1/2/2012', 101) converts the literal character string to DATE using style 101 representing the United States standard.

Entity Framework Query for inner join

You could use a navigation property if its available. It produces an inner join in the SQL.

from s in db.Services
where s.ServiceAssignment.LocationId == 1
select s

Change Bootstrap tooltip color

Bootstrap 3 + SASS for bottom tooltip :

.red-tooltip {
    & + .tooltip.bottom {
          .tooltip-inner{background-color:$red;}
          .tooltip-arrow {border-bottom-color: $red;}
    }
}

Set Colorbar Range in matplotlib

Using vmin and vmax forces the range for the colors. Here's an example:

enter image description here

import matplotlib as m
import matplotlib.pyplot as plt
import numpy as np

cdict = {
  'red'  :  ( (0.0, 0.25, .25), (0.02, .59, .59), (1., 1., 1.)),
  'green':  ( (0.0, 0.0, 0.0), (0.02, .45, .45), (1., .97, .97)),
  'blue' :  ( (0.0, 1.0, 1.0), (0.02, .75, .75), (1., 0.45, 0.45))
}

cm = m.colors.LinearSegmentedColormap('my_colormap', cdict, 1024)

x = np.arange(0, 10, .1)
y = np.arange(0, 10, .1)
X, Y = np.meshgrid(x,y)

data = 2*( np.sin(X) + np.sin(3*Y) )

def do_plot(n, f, title):
    #plt.clf()
    plt.subplot(1, 3, n)
    plt.pcolor(X, Y, f(data), cmap=cm, vmin=-4, vmax=4)
    plt.title(title)
    plt.colorbar()

plt.figure()
do_plot(1, lambda x:x, "all")
do_plot(2, lambda x:np.clip(x, -4, 0), "<0")
do_plot(3, lambda x:np.clip(x, 0, 4), ">0")
plt.show()

Nested JSON: How to add (push) new items to an object?

You can achieve this using Lodash _.assign function.

library[title] = _.assign({}, {'foregrounds': foregrounds }, {'backgrounds': backgrounds });

_x000D_
_x000D_
// This is my JSON object generated from a database_x000D_
var library = {_x000D_
  "Gold Rush": {_x000D_
    "foregrounds": ["Slide 1", "Slide 2", "Slide 3"],_x000D_
    "backgrounds": ["1.jpg", "", "2.jpg"]_x000D_
  },_x000D_
  "California": {_x000D_
    "foregrounds": ["Slide 1", "Slide 2", "Slide 3"],_x000D_
    "backgrounds": ["3.jpg", "4.jpg", "5.jpg"]_x000D_
  }_x000D_
}_x000D_
_x000D_
// These will be dynamically generated vars from editor_x000D_
var title = "Gold Rush";_x000D_
var foregrounds = ["Howdy", "Slide 2"];_x000D_
var backgrounds = ["1.jpg", ""];_x000D_
_x000D_
function save() {_x000D_
_x000D_
  // If title already exists, modify item_x000D_
  if (library[title]) {_x000D_
_x000D_
    // override one Object with the values of another (lodash)_x000D_
    library[title] = _.assign({}, {_x000D_
      'foregrounds': foregrounds_x000D_
    }, {_x000D_
      'backgrounds': backgrounds_x000D_
    });_x000D_
    console.log(library[title]);_x000D_
_x000D_
    // Save to Database. Then on callback..._x000D_
    // console.log('Changes Saved to <b>' + title + '</b>');_x000D_
  }_x000D_
_x000D_
  // If title does not exist, add new item_x000D_
  else {_x000D_
    // Format it for the JSON object_x000D_
    var item = ('"' + title + '" : {"foregrounds" : ' + foregrounds + ',"backgrounds" : ' + backgrounds + '}');_x000D_
_x000D_
    // THE PROBLEM SEEMS TO BE HERE??_x000D_
    // Error: "Result of expression 'library.push' [undefined] is not a function"_x000D_
    library.push(item);_x000D_
_x000D_
    // Save to Database. Then on callback..._x000D_
    console.log('Added: <b>' + title + '</b>');_x000D_
  }_x000D_
}_x000D_
_x000D_
save();
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Mixing C# & VB In The Same Project

Yes its possible.adding c# and vb.net projects into a single solution.

step1: File->Add->Existing Project

Step2: Project->Add reference->dll or exe of project which u added before.

step3: In vb.net form where u want to use c# forms->import namespace of project.

How to use PHP to connect to sql server

Try this to be able to catch the thrown exception:

$server_name = "your server name";
$database_name = "your database name";
try {
   $conn = new PDO("sqlsrv:Server=$server_name;Database=$database_name;ConnectionPooling=0", "user_name", "password");
   $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
    $e->getMessage();
}

Format JavaScript date as yyyy-mm-dd

You can use toLocaleDateString('fr-CA') on Date object

_x000D_
_x000D_
console.log(new Date('Sun May 11,2014').toLocaleDateString('fr-CA'));
_x000D_
_x000D_
_x000D_

Also I found out that those locales give right result from this locales list List of All Locales and Their Short Codes?

'en-CA'
'fr-CA'
'lt-LT'
'sv-FI'
'sv-SE'

_x000D_
_x000D_
var localesList = ["af-ZA",_x000D_
  "am-ET",_x000D_
  "ar-AE",_x000D_
  "ar-BH",_x000D_
  "ar-DZ",_x000D_
  "ar-EG",_x000D_
  "ar-IQ",_x000D_
  "ar-JO",_x000D_
  "ar-KW",_x000D_
  "ar-LB",_x000D_
  "ar-LY",_x000D_
  "ar-MA",_x000D_
  "arn-CL",_x000D_
  "ar-OM",_x000D_
  "ar-QA",_x000D_
  "ar-SA",_x000D_
  "ar-SY",_x000D_
  "ar-TN",_x000D_
  "ar-YE",_x000D_
  "as-IN",_x000D_
  "az-Cyrl-AZ",_x000D_
  "az-Latn-AZ",_x000D_
  "ba-RU",_x000D_
  "be-BY",_x000D_
  "bg-BG",_x000D_
  "bn-BD",_x000D_
  "bn-IN",_x000D_
  "bo-CN",_x000D_
  "br-FR",_x000D_
  "bs-Cyrl-BA",_x000D_
  "bs-Latn-BA",_x000D_
  "ca-ES",_x000D_
  "co-FR",_x000D_
  "cs-CZ",_x000D_
  "cy-GB",_x000D_
  "da-DK",_x000D_
  "de-AT",_x000D_
  "de-CH",_x000D_
  "de-DE",_x000D_
  "de-LI",_x000D_
  "de-LU",_x000D_
  "dsb-DE",_x000D_
  "dv-MV",_x000D_
  "el-GR",_x000D_
  "en-029",_x000D_
  "en-AU",_x000D_
  "en-BZ",_x000D_
  "en-CA",_x000D_
  "en-GB",_x000D_
  "en-IE",_x000D_
  "en-IN",_x000D_
  "en-JM",_x000D_
  "en-MY",_x000D_
  "en-NZ",_x000D_
  "en-PH",_x000D_
  "en-SG",_x000D_
  "en-TT",_x000D_
  "en-US",_x000D_
  "en-ZA",_x000D_
  "en-ZW",_x000D_
  "es-AR",_x000D_
  "es-BO",_x000D_
  "es-CL",_x000D_
  "es-CO",_x000D_
  "es-CR",_x000D_
  "es-DO",_x000D_
  "es-EC",_x000D_
  "es-ES",_x000D_
  "es-GT",_x000D_
  "es-HN",_x000D_
  "es-MX",_x000D_
  "es-NI",_x000D_
  "es-PA",_x000D_
  "es-PE",_x000D_
  "es-PR",_x000D_
  "es-PY",_x000D_
  "es-SV",_x000D_
  "es-US",_x000D_
  "es-UY",_x000D_
  "es-VE",_x000D_
  "et-EE",_x000D_
  "eu-ES",_x000D_
  "fa-IR",_x000D_
  "fi-FI",_x000D_
  "fil-PH",_x000D_
  "fo-FO",_x000D_
  "fr-BE",_x000D_
  "fr-CA",_x000D_
  "fr-CH",_x000D_
  "fr-FR",_x000D_
  "fr-LU",_x000D_
  "fr-MC",_x000D_
  "fy-NL",_x000D_
  "ga-IE",_x000D_
  "gd-GB",_x000D_
  "gl-ES",_x000D_
  "gsw-FR",_x000D_
  "gu-IN",_x000D_
  "ha-Latn-NG",_x000D_
  "he-IL",_x000D_
  "hi-IN",_x000D_
  "hr-BA",_x000D_
  "hr-HR",_x000D_
  "hsb-DE",_x000D_
  "hu-HU",_x000D_
  "hy-AM",_x000D_
  "id-ID",_x000D_
  "ig-NG",_x000D_
  "ii-CN",_x000D_
  "is-IS",_x000D_
  "it-CH",_x000D_
  "it-IT",_x000D_
  "iu-Cans-CA",_x000D_
  "iu-Latn-CA",_x000D_
  "ja-JP",_x000D_
  "ka-GE",_x000D_
  "kk-KZ",_x000D_
  "kl-GL",_x000D_
  "km-KH",_x000D_
  "kn-IN",_x000D_
  "kok-IN",_x000D_
  "ko-KR",_x000D_
  "ky-KG",_x000D_
  "lb-LU",_x000D_
  "lo-LA",_x000D_
  "lt-LT",_x000D_
  "lv-LV",_x000D_
  "mi-NZ",_x000D_
  "mk-MK",_x000D_
  "ml-IN",_x000D_
  "mn-MN",_x000D_
  "mn-Mong-CN",_x000D_
  "moh-CA",_x000D_
  "mr-IN",_x000D_
  "ms-BN",_x000D_
  "ms-MY",_x000D_
  "mt-MT",_x000D_
  "nb-NO",_x000D_
  "ne-NP",_x000D_
  "nl-BE",_x000D_
  "nl-NL",_x000D_
  "nn-NO",_x000D_
  "nso-ZA",_x000D_
  "oc-FR",_x000D_
  "or-IN",_x000D_
  "pa-IN",_x000D_
  "pl-PL",_x000D_
  "prs-AF",_x000D_
  "ps-AF",_x000D_
  "pt-BR",_x000D_
  "pt-PT",_x000D_
  "qut-GT",_x000D_
  "quz-BO",_x000D_
  "quz-EC",_x000D_
  "quz-PE",_x000D_
  "rm-CH",_x000D_
  "ro-RO",_x000D_
  "ru-RU",_x000D_
  "rw-RW",_x000D_
  "sah-RU",_x000D_
  "sa-IN",_x000D_
  "se-FI",_x000D_
  "se-NO",_x000D_
  "se-SE",_x000D_
  "si-LK",_x000D_
  "sk-SK",_x000D_
  "sl-SI",_x000D_
  "sma-NO",_x000D_
  "sma-SE",_x000D_
  "smj-NO",_x000D_
  "smj-SE",_x000D_
  "smn-FI",_x000D_
  "sms-FI",_x000D_
  "sq-AL",_x000D_
  "sr-Cyrl-BA",_x000D_
  "sr-Cyrl-CS",_x000D_
  "sr-Cyrl-ME",_x000D_
  "sr-Cyrl-RS",_x000D_
  "sr-Latn-BA",_x000D_
  "sr-Latn-CS",_x000D_
  "sr-Latn-ME",_x000D_
  "sr-Latn-RS",_x000D_
  "sv-FI",_x000D_
  "sv-SE",_x000D_
  "sw-KE",_x000D_
  "syr-SY",_x000D_
  "ta-IN",_x000D_
  "te-IN",_x000D_
  "tg-Cyrl-TJ",_x000D_
  "th-TH",_x000D_
  "tk-TM",_x000D_
  "tn-ZA",_x000D_
  "tr-TR",_x000D_
  "tt-RU",_x000D_
  "tzm-Latn-DZ",_x000D_
  "ug-CN",_x000D_
  "uk-UA",_x000D_
  "ur-PK",_x000D_
  "uz-Cyrl-UZ",_x000D_
  "uz-Latn-UZ",_x000D_
  "vi-VN",_x000D_
  "wo-SN",_x000D_
  "xh-ZA",_x000D_
  "yo-NG",_x000D_
  "zh-CN",_x000D_
  "zh-HK",_x000D_
  "zh-MO",_x000D_
  "zh-SG",_x000D_
  "zh-TW",_x000D_
  "zu-ZA"_x000D_
];_x000D_
_x000D_
localesList.forEach(lcl => {_x000D_
  if ("2014-05-11" === new Date('Sun May 11,2014').toLocaleDateString(lcl)) {_x000D_
    console.log(lcl, new Date('Sun May 11,2014').toLocaleDateString(lcl));_x000D_
  }_x000D_
});
_x000D_
_x000D_
_x000D_

How do I install boto?

Installing Boto depends on the Operating system. For e.g in Ubuntu you can use the aptitude command:

sudo apt-get install python-boto

Or you can download the boto code from their site and move into the unzipped directory to run

python setup.py install

What is the recommended way to make a numeric TextField in JavaFX?

Mmmm. I ran into that problem weeks ago. As the API doesn't provide a control to achieve that,
you may want to use your own one.
I used something like:

public class IntegerBox extends TextBox {
    public-init var value : Integer = 0;
    protected function apply() {
        try {
            value = Integer.parseInt(text);
        } catch (e : NumberFormatException) {}
        text = "{value}";
    }
    override var focused = false on replace {apply()};
    override var action = function () {apply()}
}

It's used the same way that a normal TextBox,
but has also a value attribute which stores the entered integer.
When the control looses the focus, it validates the value and reverts it (if isn't valid).

C - Convert an uppercase letter to lowercase

Use This code

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
void main(){
char a[10];
clrscr();
gets(a);
int i,length=0;
for(i=0;a[i]!='\0';i++)
length+=1;
for(i=0;i<length;i++){
a[i]=a[i]^32;
}
printf("%s",&a);
getch();
}

ionic build Android | error: No installed build tools found. Please install the Android build tools

This issue also occur if you do an upgrade to you cordova installation.

Check if your log error has something like:

Checking Java JDK and Android SDK versions
ANDROID_SDK_ROOT=undefined (recommended setting) <-------------
ANDROID_HOME=/{path}/android-sdk-linux (DEPRECATED)
Using Android SDK: /usr/lib/android-sdk
Starting a Gradle Daemon (subsequent builds will be faster)

In such case, just change ANDROID_HOME to ANDROID_SDK_ROOT in your ~/.bashrc or similar config file.

Where before was:

export ANDROID_HOME="/{path}/android-sdk-linux"

Now is:

export ANDROID_SDK_ROOT="/{path}/android-sdk-linux"

Don't forget source it: $ . ~/.bashrc after edition.

Is an HTTPS query string secure?

SSL first connects to the host, so the host name and port number are transferred as clear text. When the host responds and the challenge succeeds, the client will encrypt the HTTP request with the actual URL (i.e. anything after the third slash) and and send it to the server.

There are several ways to break this security.

It is possible to configure a proxy to act as a "man in the middle". Basically, the browser sends the request to connect to the real server to the proxy. If the proxy is configured this way, it will connect via SSL to the real server but the browser will still talk to the proxy. So if an attacker can gain access of the proxy, he can see all the data that flows through it in clear text.

Your requests will also be visible in the browser history. Users might be tempted to bookmark the site. Some users have bookmark sync tools installed, so the password could end up on deli.ci.us or some other place.

Lastly, someone might have hacked your computer and installed a keyboard logger or a screen scraper (and a lot of Trojan Horse type viruses do). Since the password is visible directly on the screen (as opposed to "*" in a password dialog), this is another security hole.

Conclusion: When it comes to security, always rely on the beaten path. There is just too much that you don't know, won't think of and which will break your neck.

How to use linux command line ftp with a @ sign in my username?

I simply type ftp hostdomain.com and the very next prompt asked me to enter a name, if it wasn't the same as my current user.

I guess it depends on how your FTP is configured. That is, whether it assumes the same username (if not provided) or asks. the good news is that even without a solution, next time you face this it might Just Work™ for you :D

What is callback in Android?

It was discussed before here.

In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.

C# Lambda expressions: Why should I use them?

Microsoft has given us a cleaner, more convenient way of creating anonymous delegates called Lambda expressions. However, there is not a lot of attention being paid to the expressions portion of this statement. Microsoft released a entire namespace, System.Linq.Expressions, which contains classes to create expression trees based on lambda expressions. Expression trees are made up of objects that represent logic. For example, x = y + z is an expression that might be part of an expression tree in .Net. Consider the following (simple) example:

using System;
using System.Linq;
using System.Linq.Expressions;


namespace ExpressionTreeThingy
{
    class Program
    {
        static void Main(string[] args)
        {
            Expression<Func<int, int>> expr = (x) => x + 1; //this is not a delegate, but an object
            var del = expr.Compile(); //compiles the object to a CLR delegate, at runtime
            Console.WriteLine(del(5)); //we are just invoking a delegate at this point
            Console.ReadKey();
        }
    }
}

This example is trivial. And I am sure you are thinking, "This is useless as I could have directly created the delegate instead of creating an expression and compiling it at runtime". And you would be right. But this provides the foundation for expression trees. There are a number of expressions available in the Expressions namespaces, and you can build your own. I think you can see that this might be useful when you don't know exactly what the algorithm should be at design or compile time. I saw an example somewhere for using this to write a scientific calculator. You could also use it for Bayesian systems, or for genetic programming (AI). A few times in my career I have had to write Excel-like functionality that allowed users to enter simple expressions (addition, subtrations, etc) to operate on available data. In pre-.Net 3.5 I have had to resort to some scripting language external to C#, or had to use the code-emitting functionality in reflection to create .Net code on the fly. Now I would use expression trees.

How to perform Join between multiple tables in LINQ lambda

For joins, I strongly prefer query-syntax for all the details that are happily hidden (not the least of which are the transparent identifiers involved with the intermediate projections along the way that are apparent in the dot-syntax equivalent). However, you asked regarding Lambdas which I think you have everything you need - you just need to put it all together.

var categorizedProducts = product
    .Join(productcategory, p => p.Id, pc => pc.ProdId, (p, pc) => new { p, pc })
    .Join(category, ppc => ppc.pc.CatId, c => c.Id, (ppc, c) => new { ppc, c })
    .Select(m => new { 
        ProdId = m.ppc.p.Id, // or m.ppc.pc.ProdId
        CatId = m.c.CatId
        // other assignments
    });

If you need to, you can save the join into a local variable and reuse it later, however lacking other details to the contrary, I see no reason to introduce the local variable.

Also, you could throw the Select into the last lambda of the second Join (again, provided there are no other operations that depend on the join results) which would give:

var categorizedProducts = product
    .Join(productcategory, p => p.Id, pc => pc.ProdId, (p, pc) => new { p, pc })
    .Join(category, ppc => ppc.pc.CatId, c => c.Id, (ppc, c) => new {
        ProdId = ppc.p.Id, // or ppc.pc.ProdId
        CatId = c.CatId
        // other assignments
    });

...and making a last attempt to sell you on query syntax, this would look like this:

var categorizedProducts =
    from p in product
    join pc in productcategory on p.Id equals pc.ProdId
    join c in category on pc.CatId equals c.Id
    select new {
        ProdId = p.Id, // or pc.ProdId
        CatId = c.CatId
        // other assignments
    };

Your hands may be tied on whether query-syntax is available. I know some shops have such mandates - often based on the notion that query-syntax is somewhat more limited than dot-syntax. There are other reasons, like "why should I learn a second syntax if I can do everything and more in dot-syntax?" As this last part shows - there are details that query-syntax hides that can make it well worth embracing with the improvement to readability it brings: all those intermediate projections and identifiers you have to cook-up are happily not front-and-center-stage in the query-syntax version - they are background fluff. Off my soap-box now - anyhow, thanks for the question. :)

Check if ADODB connection is open

ADO Recordset has .State property, you can check if its value is adStateClosed or adStateOpen

If Not (rs Is Nothing) Then
  If (rs.State And adStateOpen) = adStateOpen Then rs.Close
  Set rs = Nothing
End If

MSDN about State property

Edit; The reason not to check .State against 1 or 0 is because even if it works 99.99% of the time, it is still possible to have other flags set which will cause the If statement fail the adStateOpen check.

Edit2:

For Late binding without the ActiveX Data Objects referenced, you have few options. Use the value of adStateOpen constant from ObjectStateEnum

If Not (rs Is Nothing) Then
  If (rs.State And 1) = 1 Then rs.Close
  Set rs = Nothing
End If

Or you can define the constant yourself to make your code more readable (defining them all for a good example.)

Const adStateClosed As Long = 0 'Indicates that the object is closed.
Const adStateOpen As Long = 1 'Indicates that the object is open.
Const adStateConnecting As Long = 2 'Indicates that the object is connecting.
Const adStateExecuting As Long = 4 'Indicates that the object is executing a command.
Const adStateFetching As Long = 8 'Indicates that the rows of the object are being retrieved.    

[...]

If Not (rs Is Nothing) Then

    ' ex. If (0001 And 0001) = 0001 (only open flag) -> true
    ' ex. If (1001 And 0001) = 0001 (open and retrieve) -> true
    '    This second example means it is open, but its value is not 1
    '    and If rs.State = 1 -> false, even though it is open
    If (rs.State And adStateOpen) = adStateOpen Then 
        rs.Close
    End If

    Set rs = Nothing
End If

Regular expression which matches a pattern, or is an empty string

To match pattern or an empty string, use

^$|pattern

Explanation

  • ^ and $ are the beginning and end of the string anchors respectively.
  • | is used to denote alternates, e.g. this|that.

References


On \b

\b in most flavor is a "word boundary" anchor. It is a zero-width match, i.e. an empty string, but it only matches those strings at very specific places, namely at the boundaries of a word.

That is, \b is located:

  • Between consecutive \w and \W (either order):
    • i.e. between a word character and a non-word character
  • Between ^ and \w
    • i.e. at the beginning of the string if it starts with \w
  • Between \w and $
    • i.e. at the end of the string if it ends with \w

References


On using regex to match e-mail addresses

This is not trivial depending on specification.

Related questions

Pygame Drawing a Rectangle

With the module pygame.draw shapes like rectangles, circles, polygons, liens, ellipses or arcs can be drawn. Some examples:

pygame.draw.rect draws filled rectangular shapes or outlines. The arguments are the target Surface (i.s. the display), the color, the rectangle and the optional outline width. The rectangle argument is a tuple with the 4 components (x, y, width, height), where (x, y) is the upper left point of the rectangle. Alternatively, the argument can be a pygame.Rect object:

pygame.draw.rect(window, color, (x, y, width, height))
rectangle = pygame.Rect(x, y, width, height)
pygame.draw.rect(window, color, rectangle)

pygame.draw.circle draws filled circles or outlines. The arguments are the target Surface (i.s. the display), the color, the center, the radius and the optional outline width. The center argument is a tuple with the 2 components (x, y):

pygame.draw.circle(window, color, (x, y), radius)

pygame.draw.polygon draws filled polygons or contours. The arguments are the target Surface (i.s. the display), the color, a list of points and the optional contour width. Each point is a tuple with the 2 components (x, y):

pygame.draw.polygon(window, color, [(x1, y1), (x2, y2), (x3, y3)])

Minimal example:

import pygame

pygame.init()

window = pygame.display.set_mode((200, 200))
clock = pygame.time.Clock()

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    window.fill((255, 255, 255))

    pygame.draw.rect(window, (0, 0, 255), (20, 20, 160, 160))
    pygame.draw.circle(window, (255, 0, 0), (100, 100), 80)
    pygame.draw.polygon(window, (255, 255, 0), 
        [(100, 20), (100 + 0.8660 * 80, 140), (100 - 0.8660 * 80, 140)])

    pygame.display.flip()

pygame.quit()
exit()

How to add items to a combobox in a form in excel VBA?

The method I prefer assigns an array of data to the combobox. Click on the body of your userform and change the "Click" event to "Initialize". Now the combobox will fill upon the initializing of the userform. I hope this helps.

Sub UserForm_Initialize()
  ComboBox1.List = Array("1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010")
End Sub

How does Python manage int and long?

From python 3.x, the unified integer libries are even more smarter than older versions. On my (i7 Ubuntu) box I got the following,

>>> type(math.factorial(30))
<class 'int'>

For implementation details refer Include/longintrepr.h, Objects/longobject.c and Modules/mathmodule.c files. The last file is a dynamic module (compiled to an so file). The code is well commented to follow.

How can I analyze a heap dump in IntelliJ? (memory leak)

You can install the JVisualVM plugin from here: https://plugins.jetbrains.com/plugin/3749?pr=

This will allow you to analyse the dump within the plugin.

How to use placeholder as default value in select2 framework

you can init placeholder in you select html code in two level such as:

<select class="form-control select2" style="width: 100%;" data-placeholder="Select a State">
   <option></option>
   <option>?????</option>
   <option>????</option>
   <option>??????</option>
   <option>?????</option>
   <option>?????</option>
   <option>?????</option>
   <option>???</option>   
</select>

1.set data-placeholder attribute in your select tag 2.set empty tag in first of your select tag

bootstrap 4 file input doesn't show the file name

When you have multiple files, an idea is to show only the first file and the number of the hidden file names.

$('.custom-file input').change(function() {
    var $el = $(this),
    files = $el[0].files,
    label = files[0].name;
    if (files.length > 1) {
        label = label + " and " + String(files.length - 1) + " more files"
    }
    $el.next('.custom-file-label').html(label);
});

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

Try figsize param in df.plot(figsize=(width,height)):

df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(3,3));

enter image description here

df = pd.DataFrame({"a":[1,2],"b":[1,2]})
df.plot(figsize=(5,3));

enter image description here

The size in figsize=(5,3) is given in inches per (width, height)

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.plot.html

How to create python bytes object from long hex string?

result = bytes.fromhex(some_hex_string)

Make element fixed on scroll

You can do this with css too.

just use position:fixed; for what you want to be fixed when you scroll down.

you can have some examples here:

http://davidwalsh.name/demo/css-fixed-position.php

http://demo.tutorialzine.com/2010/06/microtut-how-css-position-works/demo.html

Get HTML code from website in C#

Best thing to use is HTMLAgilityPack. You can also look into using Fizzler or CSQuery depending on your needs for selecting the elements from the retrieved page. Using LINQ or Regukar Expressions is just to error prone, especially when the HTML can be malformed, missing closing tags, have nested child elements etc.

You need to stream the page into an HtmlDocument object and then select your required element.

// Call the page and get the generated HTML
var doc = new HtmlAgilityPack.HtmlDocument();
HtmlAgilityPack.HtmlNode.ElementsFlags["br"] = HtmlAgilityPack.HtmlElementFlag.Empty;
doc.OptionWriteEmptyNodes = true;

try
{
    var webRequest = HttpWebRequest.Create(pageUrl);
    Stream stream = webRequest.GetResponse().GetResponseStream();
    doc.Load(stream);
    stream.Close();
}
catch (System.UriFormatException uex)
{
    Log.Fatal("There was an error in the format of the url: " + itemUrl, uex);
    throw;
}
catch (System.Net.WebException wex)
{
    Log.Fatal("There was an error connecting to the url: " + itemUrl, wex);
    throw;
}

//get the div by id and then get the inner text 
string testDivSelector = "//div[@id='test']";
var divString = doc.DocumentNode.SelectSingleNode(testDivSelector).InnerHtml.ToString();

[EDIT] Actually, scrap that. The simplest method is to use FizzlerEx, an updated jQuery/CSS3-selectors implementation of the original Fizzler project.

Code sample directly from their site:

using HtmlAgilityPack;
using Fizzler.Systems.HtmlAgilityPack;

//get the page
var web = new HtmlWeb();
var document = web.Load("http://example.com/page.html");
var page = document.DocumentNode;

//loop through all div tags with item css class
foreach(var item in page.QuerySelectorAll("div.item"))
{
    var title = item.QuerySelector("h3:not(.share)").InnerText;
    var date = DateTime.Parse(item.QuerySelector("span:eq(2)").InnerText);
    var description = item.QuerySelector("span:has(b)").InnerHtml;
}

I don't think it can get any simpler than that.

Is an empty href valid?

As others have said, it is valid.

There are some downsides to each approach though:

href="#" adds an extra entry to the browser history (which is annoying when e.g. back-buttoning).

href="" reloads the page

href="javascript:;" does not seem to have any problems (other than looking messy and meaningless) - anyone know of any?

What are .iml files in Android Studio?

Add .idea and *.iml to .gitignore, you don't need those files to successfully import and compile the project.

How to detect escape key press with pure JS or jQuery?

check for keyCode && which & keyup || keydown

$(document).keydown(function(e){
   var code = e.keyCode || e.which;
   alert(code);
});

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

How to remove Left property when position: absolute?

left:auto;

This will default the left back to the browser default.


So if you have your Markup/CSS as:

<div class="myClass"></div>

.myClass
{
  position:absolute;
  left:0;
}

When setting RTL, you could change to:

<div class="myClass rtl"></div>

.myClass
{
  position:absolute;
  left:0;
}
.myClass.rtl
{
  left:auto;
  right:0;
}

Multiple conditions in if statement shell script

if using /bin/sh you can use:

if [ <condition> ] && [ <condition> ]; then
    ...
fi

if using /bin/bash you can use:

if [[ <condition> && <condition> ]]; then
    ...
fi

How can I set the default value for an HTML <select> element?

I used this php function to generate the options, and insert it into my HTML

<?php
  # code to output a set of options for a numeric drop down list
  # parameters: (start, end, step, format, default)
  function numericoptions($start, $end, $step, $formatstring, $default)
  {
    $retstring = "";
    for($i = $start; $i <= $end; $i = $i + $step)
    {
      $retstring = $retstring . '<OPTION ';
      $retstring = $retstring . 'value="' . sprintf($formatstring,$i) . '"';
      if($default == $i)
      {
        $retstring = $retstring . ' selected="selected"';
      }
      $retstring = $retstring . '>' . sprintf($formatstring,$i) . '</OPTION> ';
    }

  return $retstring;
  }

?>

And then in my webpage code I use it as below;

<select id="endmin" name="endmin">
  <?php echo numericoptions(0,55,5,'%02d',$endmin); ?>
</select>

If $endmin is created from a _POST variable every time the page is loaded (and this code is inside a form which posts) then the previously selected value is selected by default.

What is recursion and when should I use it?

Well, that's a pretty decent definition you have. And wikipedia has a good definition too. So I'll add another (probably worse) definition for you.

When people refer to "recursion", they're usually talking about a function they've written which calls itself repeatedly until it is done with its work. Recursion can be helpful when traversing hierarchies in data structures.

How can I plot a confusion matrix?

IF you want more data in you confusion matrix, including "totals column" and "totals line", and percents (%) in each cell, like matlab default (see image below)

enter image description here

including the Heatmap and other options...

You should have fun with the module above, shared in the github ; )

https://github.com/wcipriano/pretty-print-confusion-matrix


This module can do your task easily and produces the output above with a lot of params to customize your CM: enter image description here

Understanding Fragment's setRetainInstance(boolean)

setRetaininstance is only useful when your activity is destroyed and recreated due to a configuration change because the instances are saved during a call to onRetainNonConfigurationInstance. That is, if you rotate the device, the retained fragments will remain there(they're not destroyed and recreated.) but when the runtime kills the activity to reclaim resources, nothing is left. When you press back button and exit the activity, everything is destroyed.

Usually I use this function to saved orientation changing Time.Say I have download a bunch of Bitmaps from server and each one is 1MB, when the user accidentally rotate his device, I certainly don't want to do all the download work again.So I create a Fragment holding my bitmaps and add it to the manager and call setRetainInstance,all the Bitmaps are still there even if the screen orientation changes.

Programmatically center TextView text

These two need to go together for it to work. Been scratching my head for a while.

numberView.textAlignment = View.TEXT_ALIGNMENT_CENTER
 numberView.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT)

PHP MySQL Google Chart JSON - Complete Example

use this, it realy works:

data.addColumn no of your key, you can add more columns or remove

<?php
$con=mysql_connect("localhost","USername","Password") or die("Failed to connect with database!!!!");
mysql_select_db("Database Name", $con); 
// The Chart table contain two fields: Weekly_task and percentage
//this example will display a pie chart.if u need other charts such as Bar chart, u will need to change little bit to make work with bar chart and others charts
$sth = mysql_query("SELECT * FROM chart");

while($r = mysql_fetch_assoc($sth)) {
$arr2=array_keys($r);
$arr1=array_values($r);

}

for($i=0;$i<count($arr1);$i++)
{
    $chart_array[$i]=array((string)$arr2[$i],intval($arr1[$i]));
}
echo "<pre>";
$data=json_encode($chart_array);
?>

<html>
  <head>
    <!--Load the AJAX API-->
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript">

    // Load the Visualization API and the piechart package.
    google.load('visualization', '1', {'packages':['corechart']});

    // Set a callback to run when the Google Visualization API is loaded.
    google.setOnLoadCallback(drawChart);

    function drawChart() {

      // Create our data table out of JSON data loaded from server.
     var data = new google.visualization.DataTable();
        data.addColumn("string", "YEAR");
        data.addColumn("number", "NO of record");

        data.addRows(<?php $data ?>);

        ]); 
      var options = {
           title: 'My Weekly Plan',
          is3D: 'true',
          width: 800,
          height: 600
        };
      // Instantiate and draw our chart, passing in some options.
      //do not forget to check ur div ID
      var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
      chart.draw(data, options);
    }
    </script>
  </head>

  <body>
    <!--Div that will hold the pie chart-->
    <div id="chart_div"></div>
  </body>
</html>

How can I switch word wrap on and off in Visual Studio Code?

  • Windows: Ctrl + Shift + press the key "P". Now on the command line, type Toggle Word Wrap and press Enter.
  • Mac: Command + Shift + press the key "P". Now in the command line, type Toggle Word Wrap and press Enter.

How to implement my very own URI scheme on Android

Complementing the @DanielLew answer, to get the values of the parameteres you have to do this:

URI example: myapp://path/to/what/i/want?keyOne=valueOne&keyTwo=valueTwo

in your activity:

Intent intent = getIntent();
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
  Uri uri = intent.getData();
  String valueOne = uri.getQueryParameter("keyOne");
  String valueTwo = uri.getQueryParameter("keyTwo");
}

Python: IndexError: list index out of range

As the error notes, the problem is in the line:

if guess[i] == winning_numbers[i]

The error is that your list indices are out of range--that is, you are trying to refer to some index that doesn't even exist. Without debugging your code fully, I would check the line where you are adding guesses based on input:

for i in range(tickets):
    bubble = input("What numbers do you want to choose for ticket #"+str(i+1)+"?\n").split(" ")
    guess.append(bubble)
print(bubble)

The size of how many guesses you are giving your user is based on

# Prompts the user to enter the number of tickets they wish to play.
tickets = int(input("How many lottery tickets do you want?\n"))

So if the number of tickets they want is less than 5, then your code here

for i in range(5):

if guess[i] == winning_numbers[i]:
    match = match+1

return match

will throw an error because there simply aren't that many elements in the guess list.

How to update multiple columns in single update statement in DB2

The update statement in all versions of SQL looks like:

update table
    set col1 = expr1,
        col2 = expr2,
        . . .
        coln = exprn
    where some condition

So, the answer is that you separate the assignments using commas and don't repeat the set statement.

How to get JSON from webpage into Python script

Get data from the URL and then call json.loads e.g.

Python3 example:

import urllib.request, json 
with urllib.request.urlopen("http://maps.googleapis.com/maps/api/geocode/json?address=google") as url:
    data = json.loads(url.read().decode())
    print(data)

Python2 example:

import urllib, json
url = "http://maps.googleapis.com/maps/api/geocode/json?address=google"
response = urllib.urlopen(url)
data = json.loads(response.read())
print data

The output would result in something like this:

{
"results" : [
    {
    "address_components" : [
        {
            "long_name" : "Charleston and Huff",
            "short_name" : "Charleston and Huff",
            "types" : [ "establishment", "point_of_interest" ]
        },
        {
            "long_name" : "Mountain View",
            "short_name" : "Mountain View",
            "types" : [ "locality", "political" ]
        },
        {
...

Make XAMPP / Apache serve file outside of htdocs folder

Ok, per pix0r's, Sparks' and Dave's answers it looks like there are three ways to do this:


Virtual Hosts

  1. Open C:\xampp\apache\conf\extra\httpd-vhosts.conf.
  2. Un-comment ~line 19 (NameVirtualHost *:80).
  3. Add your virtual host (~line 36):

    <VirtualHost *:80>
        DocumentRoot C:\Projects\transitCalculator\trunk
        ServerName transitcalculator.localhost
        <Directory C:\Projects\transitCalculator\trunk>
            Order allow,deny
            Allow from all
        </Directory>
    </VirtualHost>
    
  4. Open your hosts file (C:\Windows\System32\drivers\etc\hosts).

  5. Add

    127.0.0.1 transitcalculator.localhost #transitCalculator
    

    to the end of the file (before the Spybot - Search & Destroy stuff if you have that installed).

  6. Save (You might have to save it to the desktop, change the permissions on the old hosts file (right click > properties), and copy the new one into the directory over the old one (or rename the old one) if you are using Vista and have trouble).
  7. Restart Apache.

Now you can access that directory by browsing to http://transitcalculator.localhost/.


Make an Alias

  1. Starting ~line 200 of your http.conf file, copy everything between <Directory "C:/xampp/htdocs"> and </Directory> (~line 232) and paste it immediately below with C:/xampp/htdocs replaced with your desired directory (in this case C:/Projects) to give your server the correct permissions for the new directory.

  2. Find the <IfModule alias_module></IfModule> section (~line 300) and add

    Alias /transitCalculator "C:/Projects/transitCalculator/trunk"
    

    (or whatever is relevant to your desires) below the Alias comment block, inside the module tags.


Change your document root

  1. Edit ~line 176 in C:\xampp\apache\conf\httpd.conf; change DocumentRoot "C:/xampp/htdocs" to #DocumentRoot "C:/Projects" (or whatever you want).

  2. Edit ~line 203 to match your new location (in this case C:/Projects).


Notes:

  • You have to use forward slashes "/" instead of back slashes "\".
  • Don't include the trailing "/" at the end.
  • restart your server.

Getting a count of objects in a queryset in django

Another way of doing this would be using Aggregation. You should be able to achieve a similar result using a single query. Such as this:

Item.objects.values("contest").annotate(Count("id"))

I did not test this specific query, but this should output a count of the items for each value in contests as a dictionary.

When do items in HTML5 local storage expire?

Here highly recommended to use sessionStorage

  • it is same as localStorage but destroy when session destroyed / browser close
  • also localStorage can share between tabs while sessionStorage can use in current tab only, but value does not change on refresh page or change the page
  • sessionStorage is also useful to reduce network traffic against cookie

for set value use

sessionStorage.setItem("key","my value");

for get value use

var value = sessionStorage.getItem("key");

click here for view api

all ways for set are

  sessionStorage.key = "my val";
  sessionStorage["key"] = "my val";
  sessionStorage.setItem("key","my value");

all ways for get are

  var value = sessionStorage.key;
  var value = sessionStorage["key"];
  var value = sessionStorage.getItem("key");

Auto detect mobile browser (via user-agent?)

protected void Page_Load(object sender, EventArgs e)
{
    if (Request.Browser.IsMobileDevice == true)
    {
        Response.Redirect("Mobile//home.aspx");
    }
}

This example works in asp.net

How to spawn a process and capture its STDOUT in .NET?

The answer from Judah did not work for me (or is not complete) as the application was exiting after the first BeginOutputReadLine();

This works for me as a complete snippet, reading the constant output of a ping:

        var process = new Process();
        process.StartInfo.FileName = "ping";
        process.StartInfo.Arguments = "google.com -t";
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.UseShellExecute = false;
        process.OutputDataReceived += (sender, a) => Console.WriteLine(a.Data);
        process.Start();
        process.BeginOutputReadLine();
        process.WaitForExit();

A simple command line to download a remote maven2 artifact to the local repository?

As of version 2.4 of the Maven Dependency Plugin, you can also define a target destination for the artifact by using the -Ddest flag. It should point to a filename (not a directory) for the destination artifact. See the parameter page for additional parameters that can be used

mvn org.apache.maven.plugins:maven-dependency-plugin:2.4:get \
    -DremoteRepositories=http://download.java.net/maven/2 \
    -Dartifact=robo-guice:robo-guice:0.4-SNAPSHOT \
    -Ddest=c:\temp\robo-guice.jar

Google Play error "Error while retrieving information from server [DF-DFERH-01]"

I had the same issue because of an incorrect product sku.

I was using android.test.purchase instead of android.test.purchased.

Laravel: Get base url

Another possibility: {{ URL::route('index') }}

/** and /* in Java Comments

For the Java programming language, there is no difference between the two. Java has two types of comments: traditional comments (/* ... */) and end-of-line comments (// ...). See the Java Language Specification. So, for the Java programming language, both /* ... */ and /** ... */ are instances of traditional comments, and they are both treated exactly the same by the Java compiler, i.e., they are ignored (or more correctly: they are treated as white space).

However, as a Java programmer, you do not only use a Java compiler. You use a an entire tool chain, which includes e.g. the compiler, an IDE, a build system, etc. And some of these tools interpret things differently than the Java compiler. In particular, /** ... */ comments are interpreted by the Javadoc tool, which is included in the Java platform and generates documentation. The Javadoc tool will scan the Java source file and interpret the parts between /** ... */ as documentation.

This is similar to tags like FIXME and TODO: if you include a comment like // TODO: fix this or // FIXME: do that, most IDEs will highlight such comments so that you don't forget about them. But for Java, they are just comments.

Java JDBC - How to connect to Oracle using Service Name instead of SID

You can also specify the TNS name in the JDBC URL as below

jdbc:oracle:thin:@(DESCRIPTION =(ADDRESS_LIST =(ADDRESS =(PROTOCOL=TCP)(HOST=blah.example.com)(PORT=1521)))(CONNECT_DATA=(SID=BLAHSID)(GLOBAL_NAME=BLAHSID.WORLD)(SERVER=DEDICATED)))

How can I have grep not print out 'No such file or directory' errors?

I redirect stderr to stdout and then use grep's invert-match (-v) to exclude the warning/error string that I want to hide:

grep -r <pattern> * 2>&1 | grep -v "No such file or directory"

How to replace list item in best way

Why not use the extension methods?

Consider the following code:

        var intArray = new int[] { 0, 1, 1, 2, 3, 4 };
        // Replaces the first occurance and returns the index
        var index = intArray.Replace(1, 0);
        // {0, 0, 1, 2, 3, 4}; index=1

        var stringList = new List<string> { "a", "a", "c", "d"};
        stringList.ReplaceAll("a", "b");
        // {"b", "b", "c", "d"};

        var intEnum = intArray.Select(x => x);
        intEnum = intEnum.Replace(0, 1);
        // {0, 0, 1, 2, 3, 4} => {1, 1, 1, 2, 3, 4}
  • No code duplication
  • There is no need to type long linq expressions
  • There is no need for additional usings

The source code:

namespace System.Collections.Generic
{
    public static class Extensions
    {
        public static int Replace<T>(this IList<T> source, T oldValue, T newValue)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));

            var index = source.IndexOf(oldValue);
            if (index != -1)
                source[index] = newValue;
            return index;
        }

        public static void ReplaceAll<T>(this IList<T> source, T oldValue, T newValue)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));

            int index = -1;
            do
            {
                index = source.IndexOf(oldValue);
                if (index != -1)
                    source[index] = newValue;
            } while (index != -1);
        }


        public static IEnumerable<T> Replace<T>(this IEnumerable<T> source, T oldValue, T newValue)
        {
            if (source == null)
                throw new ArgumentNullException(nameof(source));

            return source.Select(x => EqualityComparer<T>.Default.Equals(x, oldValue) ? newValue : x);
        }
    }
}

The first two methods have been added to change the objects of reference types in place. Of course, you can use just the third method for all types.

P.S. Thanks to mike's observation, I've added the ReplaceAll method.

Update GCC on OSX

in /usr/bin type

sudo ln -s -f g++-4.2 g++

sudo ln -s -f gcc-4.2 gcc

That should do it.

Should C# or C++ be chosen for learning Games Programming (consoles)?

C++.

It is the gold standard for AAA game programming. If you need to do something interesting, you will need to do C++ or delve into unmanaged C#(not always nice).

C++ is also arguably faster(usual caveats apply).

As a learning experience, C# is not worth it. C++ is unquestionably better, especially in the quasi-embedded world of consoles. To get the object-oriented experience, go towards Java.

is the + operator less performant than StringBuffer.append()

Try this:

var s = ["<a href='", url, "'>click here</a>"].join("");

How to remove text before | character in notepad++

To replace anything that starts with "text" until the last character:

text.+(.*)$

Example

text             hsjh sdjh sd          jhsjhsdjhsdj hsd
                                                      ^
                                                      last character


To replace anything that starts with "text" until "123"

text.+(\ 123)

Example

text fuhfh283nfnd03no3 d90d3nd 3d 123 udauhdah au dauh ej2e
^                                   ^
From here                     To here

Adding Counter in shell script

Here's how you might implement a counter:

counter=0
while true; do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       exit 0
  elif [[ "$counter" -gt 20 ]]; then
       echo "Counter: $counter times reached; Exiting loop!"
       exit 1
  else
       counter=$((counter+1))
       echo "Counter: $counter time(s); Sleeping for another half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

Some Explanations:

  • counter=$((counter+1)) - this is how you can increment a counter. The $ for counter is optional inside the double parentheses in this case.
  • elif [[ "$counter" -gt 20 ]]; then - this checks whether $counter is not greater than 20. If so, it outputs the appropriate message and breaks out of your while loop.

Difference between socket and websocket?

WebSocket is just another application level protocol over TCP protocol, just like HTTP.

Some snippets < Spring in Action 4> quoted below, hope it can help you understand WebSocket better.

In its simplest form, a WebSocket is just a communication channel between two applications (not necessarily a browser is involved)...WebSocket communication can be used between any kinds of applications, but the most common use of WebSocket is to facilitate communication between a server application and a browser-based application.

Hashmap with Streams in Java 8 Streams to collect value of Map

Using keySet-

id1.keySet().stream()
        .filter(x -> x == 1)
        .map(x -> id1.get(x))
        .collect(Collectors.toList())

Best way to randomize an array with .NET

This is a complete working Console solution based on the example provided in here:

class Program
{
    static string[] words1 = new string[] { "brown", "jumped", "the", "fox", "quick" };

    static void Main()
    {
        var result = Shuffle(words1);
        foreach (var i in result)
        {
            Console.Write(i + " ");
        }
        Console.ReadKey();
    }

   static string[] Shuffle(string[] wordArray) {
        Random random = new Random();
        for (int i = wordArray.Length - 1; i > 0; i--)
        {
            int swapIndex = random.Next(i + 1);
            string temp = wordArray[i];
            wordArray[i] = wordArray[swapIndex];
            wordArray[swapIndex] = temp;
        }
        return wordArray;
    }         
}

Dynamically create Bootstrap alerts box through JavaScript

Found this today, made a few tweaks and combined the features of the other answers while updating it to bootstrap 3.x. NB: This answer requires jQuery.

In html:

<div id="form_errors" class="alert alert-danger fade in" style="display:none">

In JS:

<script>
//http://stackoverflow.com/questions/10082330/dynamically-create-bootstrap-alerts-box-through-javascript
function bootstrap_alert(elem, message, timeout) {
  $(elem).show().html('<div class="alert"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button><span>'+message+'</span></div>');

  if (timeout || timeout === 0) {
    setTimeout(function() { 
      $(elem).alert('close');
    }, timeout);    
  }
};
</script>?

Then you can invoke this either as:

bootstrap_alert('#form_errors', 'This message will fade out in 1 second', 1000)
bootstrap_alert('#form_errors', 'User must dismiss this message manually')

How to render an array of objects in React?

import React from 'react';

class RentalHome extends React.Component{
    constructor(){
        super();
        this.state = {
            rentals:[{
                _id: 1,
                title: "Nice Shahghouse Biryani",
                city: "Hyderabad",
                category: "condo",
                image: "http://via.placeholder.com/350x250",
                numOfRooms: 4,
                shared: true,
                description: "Very nice apartment in center of the city.",
                dailyPrice: 43
              },
              {
                _id: 2,
                title: "Modern apartment in center",
                city: "Bangalore",
                category: "apartment",
                image: "http://via.placeholder.com/350x250",
                numOfRooms: 1,
                shared: false,
                description: "Very nice apartment in center of the city.",
                dailyPrice: 11
              },
              {
                _id: 3,
                title: "Old house in nature",
                city: "Patna",
                category: "house",
                image: "http://via.placeholder.com/350x250",
                numOfRooms: 5,
                shared: true,
                description: "Very nice apartment in center of the city.",
                dailyPrice: 23
              }]
        }
    }
    render(){
        const {rentals} = this.state;
        return(
            <div className="card-list">
                <div className="container">
                    <h1 className="page-title">Your Home All Around the World</h1>
                    <div className="row">
                        {
                            rentals.map((rental)=>{
                                return(
                                    <div key={rental._id} className="col-md-3">
                                        <div className="card bwm-card">
                                        <img 
                                        className="card-img-top" 
                                        src={rental.image}
                                        alt={rental.title} />
                                        <div className="card-body">
                                        <h6 className="card-subtitle mb-0 text-muted">
                                            {rental.shared} {rental.category} {rental.city}
                                        </h6>
                                        <h5 className="card-title big-font">
                                            {rental.title}
                                        </h5>
                                        <p className="card-text">
                                            ${rental.dailyPrice} per Night &#183; Free Cancelation
                                        </p>
                                        </div>
                                        </div>
                                    </div>
                                )
                            })
                        }
                        
                    </div>
                </div>
            </div>
        )
    }
}

export default RentalHome;

How to cherry-pick multiple commits

Or the requested one-liner:

git rebase --onto a b f

LINQ to Entities does not recognize the method

If anyone is looking for a VB.Net answer (as I was initially), here it is:

Public Function IsSatisfied() As Expression(Of Func(Of Charity, String, String, Boolean))

Return Function(charity, name, referenceNumber) (String.IsNullOrWhiteSpace(name) Or
                                                         charity.registeredName.ToLower().Contains(name.ToLower()) Or
                                                         charity.alias.ToLower().Contains(name.ToLower()) Or
                                                         charity.charityId.ToLower().Contains(name.ToLower())) And
                                                    (String.IsNullOrEmpty(referenceNumber) Or
                                                     charity.charityReference.ToLower().Contains(referenceNumber.ToLower()))
End Function

Python Regex - How to Get Positions and Values of Matches

Taken from

Regular Expression HOWTO

span() returns both start and end indexes in a single tuple. Since the match method only checks if the RE matches at the start of a string, start() will always be zero. However, the search method of RegexObject instances scans through the string, so the match may not start at zero in that case.

>>> p = re.compile('[a-z]+')
>>> print p.match('::: message')
None
>>> m = p.search('::: message') ; print m
<re.MatchObject instance at 80c9650>
>>> m.group()
'message'
>>> m.span()
(4, 11)

Combine that with:

In Python 2.2, the finditer() method is also available, returning a sequence of MatchObject instances as an iterator.

>>> p = re.compile( ... )
>>> iterator = p.finditer('12 drummers drumming, 11 ... 10 ...')
>>> iterator
<callable-iterator object at 0x401833ac>
>>> for match in iterator:
...     print match.span()
...
(0, 2)
(22, 24)
(29, 31)

you should be able to do something on the order of

for match in re.finditer(r'[a-z]', 'a1b2c3d4'):
   print match.span()

Plotting two variables as lines using ggplot2 on the same graph

The general approach is to convert the data to long format (using melt() from package reshape or reshape2) or gather()/pivot_longer() from the tidyr package:

library("reshape2")
library("ggplot2")

test_data_long <- melt(test_data, id="date")  # convert to long format

ggplot(data=test_data_long,
       aes(x=date, y=value, colour=variable)) +
       geom_line()

ggplot2 output

Also see this question on reshaping data from wide to long.

To check if string contains particular word

Maybe this post is old, but I came across it and used the "wrong" usage. The best way to find a keyword is using .contains, example:

if ( d.contains("hello")) {
            System.out.println("I found the keyword");
}

Import data.sql MySQL Docker Container

I can import with this command

docker-compose exec -T mysql mysql -uroot -proot mydatabase < ~/Desktop/mydatabase_2019-10-05.sql

How to manage startActivityForResult on Android?

In your Main Activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    findViewById(R.id.takeCam).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent=new Intent(getApplicationContext(),TakePhotoActivity.class);
            intent.putExtra("Mode","Take");
            startActivity(intent);
        }
    });
    findViewById(R.id.selectGal).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent=new Intent(getApplicationContext(),TakePhotoActivity.class);
            intent.putExtra("Mode","Gallery");
            startActivity(intent);
        }
    });
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

}

In Second Activity to Display

private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
private static final int PICK_PHOTO_FOR_AVATAR = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_take_photo);

    imageView=findViewById(R.id.imageView);

    if(getIntent().getStringExtra("Mode").equals("Gallery"))
    {
        pickImage();
    }
    else {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
            } else {
                Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);
            }
        }
    }
}
public void pickImage() {
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");
    startActivityForResult(intent, PICK_PHOTO_FOR_AVATAR);
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == MY_CAMERA_PERMISSION_CODE)
    {
        if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
        {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        }
        else
        {
            Toast.makeText(this, "Camera Permission Denied..", Toast.LENGTH_LONG).show();
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(photo);
    }
        if (requestCode == PICK_PHOTO_FOR_AVATAR && resultCode == Activity.RESULT_OK) {
            if (data == null) {
                Log.d("ABC","No Such Image Selected");
                return;
            }
            try {
                Uri selectedData=data.getData();
                Log.d("ABC","Image Pick-Up");
                imageView.setImageURI(selectedData);
                InputStream inputStream = getApplicationContext().getContentResolver().openInputStream(selectedData);
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                Bitmap bmp=MediaStore.Images.Media.getBitmap(getContentResolver(),selectedData);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch(IOException e){

            }
    }
}

How to fix itunes could not connect to the iphone because an invalid response was received from the device?

Try resetting your network settings

Settings -> General -> Reset -> Reset Network Settings

And try deleting the contents of your mac/pc lockdown folder. Here's the link, follow the steps on "Reset the Lockdown folder".

http://support.apple.com/kb/ts2529

This one worked for me.

How to change the integrated terminal in visual studio code or VSCode

From Official Docs

Correctly configuring your shell on Windows is a matter of locating the right executable and updating the setting. Below is a list of common shell executables and their default locations.

There is also the convenience command Select Default Shell that can be accessed through the command palette which can detect and set this for you.

So you can open a command palette using ctrl+shift+p, use the command Select Default Shell, then it displays all the available command line interfaces, select whatever you want, VS code sets that as default integrated terminal for you automatically.

If you want to set it manually find the location of executable of your cli and open user settings of vscode(ctrl+,) then set

"terminal.integrated.shell.windows":"path/to/executable.exe"

Example for gitbash on windows7:

"terminal.integrated.shell.windows":"C:\\Users\\stldev03\\AppData\\Local\\Programs\\Git\\bin\\bash.exe",

Changing the JFrame title

I strongly recommend you learn how to use layout managers to get the layout you want to see. null layouts are fragile, and cause no end of trouble.

Try this source & check the comments.

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class VolumeCalculator extends JFrame implements ActionListener {
    private JTabbedPane jtabbedPane;
    private JPanel options;
    JTextField poolLengthText, poolWidthText, poolDepthText, poolVolumeText, hotTub,
            hotTubLengthText, hotTubWidthText, hotTubDepthText, hotTubVolumeText, temp, results,
            myTitle;
    JTextArea labelTubStatus;

    public VolumeCalculator(){
        setSize(400, 250);
        setVisible(true);
        setSize(400, 250);
        setVisible(true);
        setTitle("Volume Calculator");
        setSize(300, 200);
        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BorderLayout());
        getContentPane().add(topPanel);

        createOptions();

        jtabbedPane = new JTabbedPane();

        jtabbedPane.addTab("Options", options);

        topPanel.add(jtabbedPane, BorderLayout.CENTER);
    }
    /* CREATE OPTIONS */

    public void createOptions(){
        options = new JPanel();
        //options.setLayout(null);
        JLabel labelOptions = new JLabel("Change Company Name:");
        labelOptions.setBounds(120, 10, 150, 20);
        options.add(labelOptions);
        JTextField newTitle = new JTextField("Some Title");
        //newTitle.setBounds(80, 40, 225, 20);    
        options.add(newTitle);
        myTitle = new JTextField(20);
        // myTitle WAS NEVER ADDED to the GUI!
        options.add(myTitle);
        //myTitle.setBounds(80, 40, 225, 20);
        //myTitle.add(labelOptions);
        JButton newName = new JButton("Set New Name");
        //newName.setBounds(60, 80, 150, 20);
        newName.addActionListener(this);
        options.add(newName);
        JButton Exit = new JButton("Exit");
        //Exit.setBounds(250, 80, 80, 20);
        Exit.addActionListener(this);
        options.add(Exit);
    }

    public void actionPerformed(ActionEvent event){
        JButton button = (JButton) event.getSource();
        String buttonLabel = button.getText();
        if ("Exit".equalsIgnoreCase(buttonLabel)){
            Exit_pressed();
            return;
        }
        if ("Set New Name".equalsIgnoreCase(buttonLabel)){
            New_Name();
            return;
        }
    }

    private void Exit_pressed(){
        System.exit(0);
    }

    private void New_Name(){
        System.out.println("'" + myTitle.getText() + "'");
        this.setTitle(myTitle.getText());
    }

    private void Options(){
    }

    public static void main(String[] args){
        JFrame frame = new VolumeCalculator();
        frame.pack();
        frame.setSize(380, 350);
        frame.setVisible(true);
    }
}

PostgreSQL, checking date relative to "today"

I think this will do it:

SELECT * FROM MyTable WHERE mydate > now()::date - 365;

How to change the spinner background in Android?

<FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    <Spinner
        android:layout_marginTop="8dp"
        android:background="@drawable/edit_border"
        android:visibility="visible"
        android:id="@+id/teach_repeat"
        android:entries="@array/on_off"
        android:textSize="12sp"
        android:textColor="#ffffff"
        android:layout_width="match_parent"
        android:layout_height="40dp" />
        <ImageView
            android:layout_marginTop="8dp"
            android:layout_gravity="end"
            android:src="@drawable/ic_arrow_drop_down_white_18dp"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </FrameLayout>

Regular expression for URL validation (in JavaScript)

You can simple use type="url" in your input and the check it with checkValidity() in js

E.g:

your.html

<input id="foo" type="url">

your.js

$("#foo").on("keyup", function() {
    if (this.checkValidity()) {
        // The url is valid
    } else {
        // The url is invalid
    }
});

Check if an image is loaded (no errors) with jQuery

I tried many different ways and this way is the only one worked for me

//check all images on the page
$('img').each(function(){
    var img = new Image();
    img.onload = function() {
        console.log($(this).attr('src') + ' - done!');
    }
    img.src = $(this).attr('src');
});

You could also add a callback function triggered once all images are loaded in the DOM and ready. This applies for dynamically added images too. http://jsfiddle.net/kalmarsh80/nrAPk/

Base64 String throwing invalid character error

One gotcha to do with converting Base64 from a string is that some conversion functions use the preceding "data:image/jpg;base64," and others only accept the actual data.

WebSocket with SSL

You can't use WebSockets over HTTPS, but you can use WebSockets over TLS (HTTPS is HTTP over TLS). Just use "wss://" in the URI.

I believe recent version of Firefox won't let you use non-TLS WebSockets from an HTTPS page, but the reverse shouldn't be a problem.

Saving and Reading Bitmaps/Images from Internal memory in Android

Use the below code to save the image to internal directory.

private String saveToInternalStorage(Bitmap bitmapImage){
        ContextWrapper cw = new ContextWrapper(getApplicationContext());
         // path to /data/data/yourapp/app_data/imageDir
        File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
        // Create imageDir
        File mypath=new File(directory,"profile.jpg");

        FileOutputStream fos = null;
        try {           
            fos = new FileOutputStream(mypath);
       // Use the compress method on the BitMap object to write image to the OutputStream
            bitmapImage.compress(Bitmap.CompressFormat.PNG, 100, fos);
        } catch (Exception e) {
              e.printStackTrace();
        } finally {
            try {
              fos.close();
            } catch (IOException e) {
              e.printStackTrace();
            }
        } 
        return directory.getAbsolutePath();
    }

Explanation :

1.The Directory will be created with the given name. Javadocs is for to tell where exactly it will create the directory.

2.You will have to give the image name by which you want to save it.

To Read the file from internal memory. Use below code

private void loadImageFromStorage(String path)
{

    try {
        File f=new File(path, "profile.jpg");
        Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
            ImageView img=(ImageView)findViewById(R.id.imgPicker);
        img.setImageBitmap(b);
    } 
    catch (FileNotFoundException e) 
    {
        e.printStackTrace();
    }

}

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

Avoid using companion objects. Behind the hood, getter and setter instance methods are created for the fields to be accessible. Calling instance methods is technically more expensive than calling static methods.

public class DbConstants {
    companion object {
        val TABLE_USER_ATTRIBUTE_EMPID = "_id"
        val TABLE_USER_ATTRIBUTE_DATA = "data"
    }

Instead define the constants in object.

Recommended practice :

object DbConstants {
        const val TABLE_USER_ATTRIBUTE_EMPID = "_id"
        const val TABLE_USER_ATTRIBUTE_DATA = "data"
}

and access them globally like this: DbConstants.TABLE_USER_ATTRIBUTE_EMPID

Write a function that returns the longest palindrome in a given string

As far as I understood the problem, we can find palindromes around a center index and span our search both ways, to the right and left of the center. Given that and knowing there's no palindrome on the corners of the input, we can set the boundaries to 1 and length-1. While paying attention to the minimum and maximum boundaries of the String, we verify if the characters at the positions of the symmetrical indexes (right and left) are the same for each central position till we reach our max upper bound center.

The outer loop is O(n) (max n-2 iterations), and the inner while loop is O(n) (max around (n / 2) - 1 iterations)

Here's my Java implementation using the example provided by other users.

class LongestPalindrome {

    /**
     * @param input is a String input
     * @return The longest palindrome found in the given input.
     */
    public static String getLongestPalindrome(final String input) {
        int rightIndex = 0, leftIndex = 0;
        String currentPalindrome = "", longestPalindrome = "";
        for (int centerIndex = 1; centerIndex < input.length() - 1; centerIndex++) {
            leftIndex = centerIndex - 1;  rightIndex = centerIndex + 1;
            while (leftIndex >= 0 && rightIndex < input.length()) {
                if (input.charAt(leftIndex) != input.charAt(rightIndex)) {
                    break;
                }
                currentPalindrome = input.substring(leftIndex, rightIndex + 1);
                longestPalindrome = currentPalindrome.length() > longestPalindrome.length() ? currentPalindrome : longestPalindrome;
                leftIndex--;  rightIndex++;
            }
        }
        return longestPalindrome;
    }

    public static void main(String ... args) {
        String str = "HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE";
        String longestPali = getLongestPalindrome(str);
        System.out.println("String: " + str);
        System.out.println("Longest Palindrome: " + longestPali);
    }
}

The output of this is the following:

marcello:datastructures marcello$ javac LongestPalindrome
marcello:datastructures marcello$ java LongestPalindrome
String: HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE
Longest Palindrome: 12345678987654321

How to close IPython Notebook properly?

First step is to save all open notebooks. And then think about shutting down your running Jupyter Notebook. You can use this simple command:

$ jupyter notebook stop 
Shutting down server on port 8888 ...

Which also takes the port number as argument and you can shut down the jupyter notebook gracefully.

For eg:

jupyter notebook stop 8889 
Shutting down server on port 8889 ...

Additionally to know your current jupyter instance running, check below command:

shell> jupyter notebook list 
Currently running servers:
http://localhost:8888/?token=ef12021898c435f865ec706de98632 :: /Users/username/jupyter-notebooks [/code]

How to select only date from a DATETIME field in MySQL?

Use DATE_FORMAT

select DATE_FORMAT(date,'%d') from tablename =>Date only

example:

select DATE_FORMAT(`date_column`,'%d') from `database_name`.`table_name`;

runOnUiThread in fragment

In Xamarin.Android

For Fragment:

this.Activity.RunOnUiThread(() => { yourtextbox.Text="Hello"; });

For Activity:

RunOnUiThread(() => { yourtextbox.Text="Hello"; });

Happy coding :-)

Get records with max value for each group of grouped SQL results

This method has the benefit of allowing you to rank by a different column, and not trashing the other data. It's quite useful in a situation where you are trying to list orders with a column for items, listing the heaviest first.

Source: http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat

SELECT person, group,
    GROUP_CONCAT(
        DISTINCT age
        ORDER BY age DESC SEPARATOR ', follow up: '
    )
FROM sql_table
GROUP BY group;

What is the MySQL VARCHAR max size?

You can use TEXT type, which is not limited to 64KB.

iPad Multitasking support requires these orientations

as Michael said,

Check the "Requires full screen" of the target of xcodeproj, if you don't need to support multitasking.

or Check the following device orientations

  • Portrait
  • Upside Down
  • Landscape Left
  • Landscape Right

In this case, we need to support launch storyboard.

SQL Server tables: what is the difference between @, # and ##?

if you need a unique global temp table, create your own with a Uniqueidentifier Prefix/Suffix and drop post execution if an if object_id(.... The only drawback is using Dynamic sql and need to drop explicitly.

How to pass data between fragments

If you use Roboguice you can use the EventManager in Roboguice to pass data around without using the Activity as an interface. This is quite clean IMO.

If you're not using Roboguice you can use Otto too as a event bus: http://square.github.com/otto/

Update 20150909: You can also use Green Robot Event Bus or even RxJava now too. Depends on your use case.

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

REST HTTP status codes for failed validation or invalid duplicate

I recommend status code 422, "Unprocessable Entity".

11.2. 422 Unprocessable Entity

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

Configuring diff tool with .gitconfig

Here's the part of my ~/.gitconfig where I configure diff and merge tools. I like diffmerge by SourceGear. (I like it very very much, as a matter of fact).

[merge]
        tool = diffmerge
[mergetool "diffmerge"]
        cmd = "diffmerge --merge --result=\"$MERGED\" \"$LOCAL\" \"$(if test -f \"$BASE\"; then echo \"$BASE\"; else echo \"$LOCAL\"; fi)\" \"$REMOTE\""
        trustExitCode = false
[diff]
        tool = diffmerge
[difftool "diffmerge"]
        cmd = diffmerge \"$LOCAL\" \"$REMOTE\"

So, you see, you're defining a tool named "diffmerge" in the [difftool "diffmerge"] line. Then I'm setting the tool "diffmerge" as the default in the [diff] tool = section.

I obviously have the "diffmerge" command in my path, here. Otherwise I'd need to give a full path to the executable.

The endpoint reference (EPR) for the Operation not found is

As described by Eran Chinthaka at http://wso2.com/library/176/

If Axis2 engine cannot find a service and an operation for a message, it immediately fails, sending a fault to the sender. If service not found - "Service Not found EPR is " If service found but not an operation- "Operation Not found EPR is and WSA Action = "

In your case the service is found but the operation not. The Axis2 engine uses SOAPAction in order to figure out the requested operation and, in your example, the SOAPAction is missing, therefore I would try to define the SOAPAction header

Single TextView with multiple colored text

Awesome answers! I was able to use Spannable to build rainbow colored text (so this could be repeated for any array of colors). Here's my method, if it helps anyone:

private Spannable buildRainbowText(String pack_name) {
        int[] colors = new int[]{Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE, Color.RED, 0xFFFF9933, Color.YELLOW, Color.GREEN, Color.BLUE};
        Spannable word = new SpannableString(pack_name);
        for(int i = 0; i < word.length(); i++) {
            word.setSpan(new ForegroundColorSpan(colors[i]), i, i+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        return word;
    }

And then I just setText(buildRainboxText(pack_name)); Note that all of the words I pass in are under 15 characters and this just repeats 5 colors 3 times - you'd want to adjust the colors/length of the array for your usage!

Add vertical whitespace using Twitter Bootstrap?

I know this is old and there are several good solutions already posted, but a simple solution that worked for me is the following CSS

<style>
  .divider{
    margin: 0cm 0cm .5cm 0cm;
  }
</style>

and then create a div in your html

<div class="divider"></div>

Can't import database through phpmyadmin file size too large

You have three options:

  • Use another way to get the file on the server, and use a mysql client on the server
  • Use another client to connect to the server and load the data
  • Change your PHP settings to allow such huge files. Don't forget to increment the execution time as well.

Function to return only alpha-numeric characters from string?

Rather than preg_replace, you could always use PHP's filter functions using the filter_var() function with FILTER_SANITIZE_STRING.

Join two data frames, select all columns from one and some columns from the other

Not sure if the most efficient way, but this worked for me:

from pyspark.sql.functions import col

df1.alias('a').join(df2.alias('b'),col('b.id') == col('a.id')).select([col('a.'+xx) for xx in a.columns] + [col('b.other1'),col('b.other2')])

The trick is in:

[col('a.'+xx) for xx in a.columns] : all columns in a

[col('b.other1'),col('b.other2')] : some columns of b

Anaconda export Environment file

  • Linux

    conda env export --no-builds | grep -v "prefix" > environment.yml

  • Windows

    conda env export --no-builds | findstr -v "prefix" > environment.yml


Rationale: By default, conda env export includes the build information:

$ conda env export
...
dependencies:
  - backcall=0.1.0=py37_0
  - blas=1.0=mkl
  - boto=2.49.0=py_0
...

You can instead export your environment without build info:

$ conda env export --no-builds
...
dependencies:
  - backcall=0.1.0
  - blas=1.0
  - boto=2.49.0
...

Which unties the environment from the Python version and OS.

Set folder browser dialog start location

fldrDialog.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory)

"If the SelectedPath property is set before showing the dialog box, the folder with this path will be the selected folder, as long as SelectedPath is set to an absolute path that is a subfolder of RootFolder (or more accurately, points to a subfolder of the shell namespace represented by RootFolder)."

MSDN - SelectedPath

"The GetFolderPath method returns the locations associated with this enumeration. The locations of these folders can have different values on different operating systems, the user can change some of the locations, and the locations are localized."

Re: Desktop vs DesktopDirectory

Desktop

"The logical Desktop rather than the physical file system location."

DesktopDirectory:

"The directory used to physically store file objects on the desktop. Do not confuse this directory with the desktop folder itself, which is a virtual folder."

MSDN - Special Folder Enum

MSDN - GetFolderPath

Java character array initializer

Here is the code

String str = "Hi There";
char[] arr = str.toCharArray();

for(int i=0;i<arr.length;i++)
    System.out.print(" "+arr[i]);

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

I had the same problem on OSX OpenSSL 1.0.1i from Macports, and also had to specify CApath as a workaround (and as mentioned in the Ubuntu bug report, even an invalid CApath will make openssl look in the default directory). Interestingly, connecting to the same server using PHP's openssl functions (as used in PHPMailer 5) worked fine.

ArrayList: how does the size increase?

Sun's JDK6:

I believe that it grows to 15 elements. Not coding it out, but looking at the grow() code in the jdk.

int newCapacity then = 10 + (10 >> 1) = 15.

/**
 * Increases the capacity to ensure that it can hold at least the
 * number of elements specified by the minimum capacity argument.
 *
 * @param minCapacity the desired minimum capacity
 */
private void grow(int minCapacity) {
    // overflow-conscious code
    int oldCapacity = elementData.length;
    int newCapacity = oldCapacity + (oldCapacity >> 1);
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    // minCapacity is usually close to size, so this is a win:
    elementData = Arrays.copyOf(elementData, newCapacity);
}

From the Javadoc, it says this is from Java 2 and on, so its a safe bet in the Sun JDK.

EDIT : for those who didn't get what's the connection between multiplying factor 1.5 and int newCapacity = oldCapacity + (oldCapacity >> 1);

>> is right shift operator which reduces a number to its half. Thus,
int newCapacity = oldCapacity + (oldCapacity >> 1);
=> int newCapacity = oldCapacity + 0.5*oldCapacity;
=> int newCapacity = 1.5*oldCapacity ;

ORA-01034: ORACLE not available ORA-27101: shared memory realm does not exist

Your listener.ora is misconfigured. There is no orcl service.

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

DataTable's Select method only supports simple filtering expressions like {field} = {value}. It does not support complex expressions, let alone SQL/Linq statements.

You can, however, use Linq extension methods to extract a collection of DataRows then create a new DataTable.

dt = dt.AsEnumerable()
       .GroupBy(r => new {Col1 = r["Col1"], Col2 = r["Col2"]})
       .Select(g => g.OrderBy(r => r["PK"]).First())
       .CopyToDataTable();

Typing the Enter/Return key using Python and Selenium

There are the following ways of pressing keys - C#:

Driver.FindElement(By.Id("Value")).SendKeys(Keys.Return);

OR

OpenQA.Selenium.Interactions.Actions action = new OpenQA.Selenium.Interactions.Actions(Driver);
action.SendKeys(OpenQA.Selenium.Keys.Escape);

OR

IWebElement body = GlobalDriver.FindElement(By.TagName("body"));
body.SendKeys(Keys.Escape);

Reimport a module in python while interactive

This should work:

reload(my.module)

From the Python docs

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.

If running Python 3.4 and up, do import importlib, then do importlib.reload(nameOfModule).

Don't forget the caveats of using this method:

  • When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem, but if the new version of a module does not define a name that was defined by the old version, the old definition is not removed.

  • If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.

  • If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

Writing a pandas DataFrame to CSV file

it could be not the answer for this case, but as I had the same error-message with .to_csvI tried .toCSV('name.csv') and the error-message was different ("SparseDataFrame' object has no attribute 'toCSV'). So the problem was solved by turning dataframe to dense dataframe

df.to_dense().to_csv("submission.csv", index = False, sep=',', encoding='utf-8')

How to read a large file line by line?

Some context up front as to where I am coming from. Code snippets are at the end.

When I can, I prefer to use an open source tool like H2O to do super high performance parallel CSV file reads, but this tool is limited in feature set. I end up writing a lot of code to create data science pipelines before feeding to H2O cluster for the supervised learning proper.

I have been reading files like 8GB HIGGS dataset from UCI repo and even 40GB CSV files for data science purposes significantly faster by adding lots of parallelism with the multiprocessing library's pool object and map function. For example clustering with nearest neighbor searches and also DBSCAN and Markov clustering algorithms requires some parallel programming finesse to bypass some seriously challenging memory and wall clock time problems.

I usually like to break the file row-wise into parts using gnu tools first and then glob-filemask them all to find and read them in parallel in the python program. I use something like 1000+ partial files commonly. Doing these tricks helps immensely with processing speed and memory limits.

The pandas dataframe.read_csv is single threaded so you can do these tricks to make pandas quite faster by running a map() for parallel execution. You can use htop to see that with plain old sequential pandas dataframe.read_csv, 100% cpu on just one core is the actual bottleneck in pd.read_csv, not the disk at all.

I should add I'm using an SSD on fast video card bus, not a spinning HD on SATA6 bus, plus 16 CPU cores.

Also, another technique that I discovered works great in some applications is parallel CSV file reads all within one giant file, starting each worker at different offset into the file, rather than pre-splitting one big file into many part files. Use python's file seek() and tell() in each parallel worker to read the big text file in strips, at different byte offset start-byte and end-byte locations in the big file, all at the same time concurrently. You can do a regex findall on the bytes, and return the count of linefeeds. This is a partial sum. Finally sum up the partial sums to get the global sum when the map function returns after the workers finished.

Following is some example benchmarks using the parallel byte offset trick:

I use 2 files: HIGGS.csv is 8 GB. It is from the UCI machine learning repository. all_bin .csv is 40.4 GB and is from my current project. I use 2 programs: GNU wc program which comes with Linux, and the pure python fastread.py program which I developed.

HP-Z820:/mnt/fastssd/fast_file_reader$ ls -l /mnt/fastssd/nzv/HIGGS.csv
-rw-rw-r-- 1 8035497980 Jan 24 16:00 /mnt/fastssd/nzv/HIGGS.csv

HP-Z820:/mnt/fastssd$ ls -l all_bin.csv
-rw-rw-r-- 1 40412077758 Feb  2 09:00 all_bin.csv

ga@ga-HP-Z820:/mnt/fastssd$ time python fastread.py --fileName="all_bin.csv" --numProcesses=32 --balanceFactor=2
2367496

real    0m8.920s
user    1m30.056s
sys 2m38.744s

In [1]: 40412077758. / 8.92
Out[1]: 4530501990.807175

That’s some 4.5 GB/s, or 45 Gb/s, file slurping speed. That ain’t no spinning hard disk, my friend. That’s actually a Samsung Pro 950 SSD.

Below is the speed benchmark for the same file being line-counted by gnu wc, a pure C compiled program.

What is cool is you can see my pure python program essentially matched the speed of the gnu wc compiled C program in this case. Python is interpreted but C is compiled, so this is a pretty interesting feat of speed, I think you would agree. Of course, wc really needs to be changed to a parallel program, and then it would really beat the socks off my python program. But as it stands today, gnu wc is just a sequential program. You do what you can, and python can do parallel today. Cython compiling might be able to help me (for some other time). Also memory mapped files was not explored yet.

HP-Z820:/mnt/fastssd$ time wc -l all_bin.csv
2367496 all_bin.csv

real    0m8.807s
user    0m1.168s
sys 0m7.636s


HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=16 --balanceFactor=2
11000000

real    0m2.257s
user    0m12.088s
sys 0m20.512s

HP-Z820:/mnt/fastssd/fast_file_reader$ time wc -l HIGGS.csv
11000000 HIGGS.csv

real    0m1.820s
user    0m0.364s
sys 0m1.456s

Conclusion: The speed is good for a pure python program compared to a C program. However, it’s not good enough to use the pure python program over the C program, at least for linecounting purpose. Generally the technique can be used for other file processing, so this python code is still good.

Question: Does compiling the regex just one time and passing it to all workers will improve speed? Answer: Regex pre-compiling does NOT help in this application. I suppose the reason is that the overhead of process serialization and creation for all the workers is dominating.

One more thing. Does parallel CSV file reading even help? Is the disk the bottleneck, or is it the CPU? Many so-called top-rated answers on stackoverflow contain the common dev wisdom that you only need one thread to read a file, best you can do, they say. Are they sure, though?

Let’s find out:

HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=16 --balanceFactor=2
11000000

real    0m2.256s
user    0m10.696s
sys 0m19.952s

HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=1 --balanceFactor=1
11000000

real    0m17.380s
user    0m11.124s
sys 0m6.272s

Oh yes, yes it does. Parallel file reading works quite well. Well there you go!

Ps. In case some of you wanted to know, what if the balanceFactor was 2 when using a single worker process? Well, it’s horrible:

HP-Z820:/mnt/fastssd/fast_file_reader$ time python fastread.py --fileName="HIGGS.csv" --numProcesses=1 --balanceFactor=2
11000000

real    1m37.077s
user    0m12.432s
sys 1m24.700s

Key parts of the fastread.py python program:

fileBytes = stat(fileName).st_size  # Read quickly from OS how many bytes are in a text file
startByte, endByte = PartitionDataToWorkers(workers=numProcesses, items=fileBytes, balanceFactor=balanceFactor)
p = Pool(numProcesses)
partialSum = p.starmap(ReadFileSegment, zip(startByte, endByte, repeat(fileName))) # startByte is already a list. fileName is made into a same-length list of duplicates values.
globalSum = sum(partialSum)
print(globalSum)


def ReadFileSegment(startByte, endByte, fileName, searchChar='\n'):  # counts number of searchChar appearing in the byte range
    with open(fileName, 'r') as f:
        f.seek(startByte-1)  # seek is initially at byte 0 and then moves forward the specified amount, so seek(5) points at the 6th byte.
        bytes = f.read(endByte - startByte + 1)
        cnt = len(re.findall(searchChar, bytes)) # findall with implicit compiling runs just as fast here as re.compile once + re.finditer many times.
    return cnt

The def for PartitionDataToWorkers is just ordinary sequential code. I left it out in case someone else wants to get some practice on what parallel programming is like. I gave away for free the harder parts: the tested and working parallel code, for your learning benefit.

Thanks to: The open-source H2O project, by Arno and Cliff and the H2O staff for their great software and instructional videos, which have provided me the inspiration for this pure python high performance parallel byte offset reader as shown above. H2O does parallel file reading using java, is callable by python and R programs, and is crazy fast, faster than anything on the planet at reading big CSV files.

how to rotate a bitmap 90 degrees

I would simplify comm1x's Kotlin extension function even more:

fun Bitmap.rotate(degrees: Float) =
    Bitmap.createBitmap(this, 0, 0, width, height, Matrix().apply { postRotate(degrees) }, true)

package android.support.v4.app does not exist ; in Android studio 0.8

For me the problem was caused by a gradle.properties file in the list of Gradle scripts. It showed as gradle.properties (global) and refered to a file in C:\users\.gradle\gradle.properties. I right-clicked on it and selected delete from the menu to delete it. It deleted the file from the hard disk and my project now builds and runs. I guess that the global file was overwriting something that was used to locate the package android.support

Passing an array by reference

It's just the required syntax:

void Func(int (&myArray)[100])

^ Pass array of 100 int by reference the parameters name is myArray;

void Func(int* myArray)

^ Pass an array. Array decays to a pointer. Thus you lose size information.

void Func(int (*myFunc)(double))

^ Pass a function pointer. The function returns an int and takes a double. The parameter name is myFunc.

How to measure elapsed time

There are many ways to achieve this, but the most important consideration to measure elapsed time is to use System.nanoTime() and TimeUnit.NANOSECONDS as the time unit. Why should I do this? Well, it is because System.nanoTime() method returns a high-resolution time source, in nanoseconds since some reference point (i.e. Java Virtual Machine's start up).

This method can only be used to measure elapsed time and is not related to any other notion of system or wall-clock time.

For the same reason, it is recommended to avoid the use of the System.currentTimeMillis() method for measuring elapsed time. This method returns the wall-clock time, which may change based on many factors. This will be negative for your measurements.

Note that while the unit of time of the return value is a millisecond, the granularity of the value depends on the underlying operating system and may be larger. For example, many operating systems measure time in units of tens of milliseconds.

So here you have one solution based on the System.nanoTime() method, another one using Guava, and the final one Apache Commons Lang

public class TimeBenchUtil
{
    public static void main(String[] args) throws InterruptedException
    {
        stopWatch();
        stopWatchGuava();
        stopWatchApacheCommons();
    }

    public static void stopWatch() throws InterruptedException
    {
        long endTime, timeElapsed, startTime = System.nanoTime();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds
        TimeUnit.SECONDS.sleep(5);

        /* ... the code being measured ends ... */

        endTime = System.nanoTime();

        // get difference of two nanoTime values
        timeElapsed = endTime - startTime;

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);
    }

    public static void stopWatchGuava() throws InterruptedException
    {
        // Creates and starts a new stopwatch
        Stopwatch stopwatch = Stopwatch.createStarted();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds
        TimeUnit.SECONDS.sleep(5);
        /* ... the code being measured ends ... */

        stopwatch.stop(); // optional

        // get elapsed time, expressed in milliseconds
        long timeElapsed = stopwatch.elapsed(TimeUnit.NANOSECONDS);

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);
    }

    public static void stopWatchApacheCommons() throws InterruptedException
    {
        StopWatch stopwatch = new StopWatch();
        stopwatch.start();

        /* ... the code being measured starts ... */

        // sleep for 5 seconds
        TimeUnit.SECONDS.sleep(5);

        /* ... the code being measured ends ... */

        stopwatch.stop();    // Optional

        long timeElapsed = stopwatch.getNanoTime();

        System.out.println("Execution time in nanoseconds   : " + timeElapsed);
    }
}

PHP: get the value of TEXTBOX then pass it to a VARIABLE

In testing2.php use the following code to get the name:

if ( ! empty($_POST['name'])){
    $name = $_POST['name']);
}

When you create the next page, use the value of $name to prefill the form field:

Name: <input type="text" name="name" id="name" value="<?php echo $name; ?>"><br/>

However, before doing that, be sure to use regular expressions to verify that the $name only contains valid characters, such as:

$pattern =  '/^[0-9A-Za-zÁ-Úá-úàÀÜü]+$/';//integers & letters
if (preg_match($pattern, $name) == 1){
    //continue
} else {
    //reload form with error message
}

How to make an HTML back link?

The best way using a button is

<input type= 'button' onclick='javascript:history.back();return false;' value='Back'>

How to get error message when ifstream open fails

Every system call that fails update the errno value.

Thus, you can have more information about what happens when a ifstream open fails by using something like :

cerr << "Error: " << strerror(errno);

However, since every system call updates the global errno value, you may have issues in a multithreaded application, if another system call triggers an error between the execution of the f.open and use of errno.

On system with POSIX standard:

errno is thread-local; setting it in one thread does not affect its value in any other thread.


Edit (thanks to Arne Mertz and other people in the comments):

e.what() seemed at first to be a more C++-idiomatically correct way of implementing this, however the string returned by this function is implementation-dependant and (at least in G++'s libstdc++) this string has no useful information about the reason behind the error...

How to write a confusion matrix in Python?

This function creates confusion matrices for any number of classes.

def create_conf_matrix(expected, predicted, n_classes):
    m = [[0] * n_classes for i in range(n_classes)]
    for pred, exp in zip(predicted, expected):
        m[pred][exp] += 1
    return m

def calc_accuracy(conf_matrix):
    t = sum(sum(l) for l in conf_matrix)
    return sum(conf_matrix[i][i] for i in range(len(conf_matrix))) / t

In contrast to your function above, you have to extract the predicted classes before calling the function, based on your classification results, i.e. sth. like

[1 if p < .5 else 2 for p in classifications]

Uninstall Django completely

On Windows, I had this issue with static files cropping up under pydev/eclipse with python 2.7, due to an instance of django (1.8.7) that had been installed under cygwin. This caused a conflict between windows style paths and cygwin style paths. So, unfindable static files despite all the above fixes. I removed the extra distribution (so that all packages were installed by pip under windows) and this fixed the issue.

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

The first solution I can think of, is to use ViewBag to store the values that must be rendered.

Onestly I never tried if this work from a partial view, but it should imo.

Rename multiple columns by names

Here is the most efficient way I have found to rename multiple columns using a combination of purrr::set_names() and a few stringr operations.

library(tidyverse)

# Make a tibble with bad names
data <- tibble(
    `Bad NameS 1` = letters[1:10],
    `bAd NameS 2` = rnorm(10)
)

data 
# A tibble: 10 x 2
   `Bad NameS 1` `bAd NameS 2`
   <chr>                 <dbl>
 1 a                    -0.840
 2 b                    -1.56 
 3 c                    -0.625
 4 d                     0.506
 5 e                    -1.52 
 6 f                    -0.212
 7 g                    -1.50 
 8 h                    -1.53 
 9 i                     0.420
 10 j                     0.957

# Use purrr::set_names() with annonymous function of stringr operations
data %>%
    set_names(~ str_to_lower(.) %>%
                  str_replace_all(" ", "_") %>%
                  str_replace_all("bad", "good"))

# A tibble: 10 x 2
   good_names_1 good_names_2
   <chr>               <dbl>
 1 a                  -0.840
 2 b                  -1.56 
 3 c                  -0.625
 4 d                   0.506
 5 e                  -1.52 
 6 f                  -0.212
 7 g                  -1.50 
 8 h                  -1.53 
 9 i                   0.420
10 j                   0.957

Ways to iterate over a list in Java

Example of each kind listed in the question:

ListIterationExample.java

import java.util.*;

public class ListIterationExample {

     public static void main(String []args){
        List<Integer> numbers = new ArrayList<Integer>();

        // populates list with initial values
        for (Integer i : Arrays.asList(0,1,2,3,4,5,6,7))
            numbers.add(i);
        printList(numbers);         // 0,1,2,3,4,5,6,7

        // replaces each element with twice its value
        for (int index=0; index < numbers.size(); index++) {
            numbers.set(index, numbers.get(index)*2); 
        }
        printList(numbers);         // 0,2,4,6,8,10,12,14

        // does nothing because list is not being changed
        for (Integer number : numbers) {
            number++; // number = new Integer(number+1);
        }
        printList(numbers);         // 0,2,4,6,8,10,12,14  

        // same as above -- just different syntax
        for (Iterator<Integer> iter = numbers.iterator(); iter.hasNext(); ) {
            Integer number = iter.next();
            number++;
        }
        printList(numbers);         // 0,2,4,6,8,10,12,14

        // ListIterator<?> provides an "add" method to insert elements
        // between the current element and the cursor
        for (ListIterator<Integer> iter = numbers.listIterator(); iter.hasNext(); ) {
            Integer number = iter.next();
            iter.add(number+1);     // insert a number right before this
        }
        printList(numbers);         // 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15

        // Iterator<?> provides a "remove" method to delete elements
        // between the current element and the cursor
        for (Iterator<Integer> iter = numbers.iterator(); iter.hasNext(); ) {
            Integer number = iter.next();
            if (number % 2 == 0)    // if number is even 
                iter.remove();      // remove it from the collection
        }
        printList(numbers);         // 1,3,5,7,9,11,13,15

        // ListIterator<?> provides a "set" method to replace elements
        for (ListIterator<Integer> iter = numbers.listIterator(); iter.hasNext(); ) {
            Integer number = iter.next();
            iter.set(number/2);     // divide each element by 2
        }
        printList(numbers);         // 0,1,2,3,4,5,6,7
     }

     public static void printList(List<Integer> numbers) {
        StringBuilder sb = new StringBuilder();
        for (Integer number : numbers) {
            sb.append(number);
            sb.append(",");
        }
        sb.deleteCharAt(sb.length()-1); // remove trailing comma
        System.out.println(sb.toString());
     }
}

How to debug SSL handshake using cURL?

I have used this command to troubleshoot client certificate negotiation:

openssl s_client -connect www.test.com:443 -prexit

The output will probably contain "Acceptable client certificate CA names" and a list of CA certificates from the server, or possibly "No client certificate CA names sent", if the server doesn't always require client certificates.

Send FormData with other field in AngularJS

Here is the complete solution

html code,

create the text anf file upload fields as shown below

    <div class="form-group">
        <div>
            <label for="usr">User Name:</label>
            <input type="text" id="usr" ng-model="model.username">
        </div>
        <div>
            <label for="pwd">Password:</label>
            <input type="password" id="pwd" ng-model="model.password">
        </div><hr>
        <div>
            <div class="col-lg-6">
                <input type="file" file-model="model.somefile"/>
            </div>


        </div>
        <div>
            <label for="dob">Dob:</label>
            <input type="date" id="dob" ng-model="model.dob">
        </div>
        <div>
            <label for="email">Email:</label>
            <input type="email"id="email" ng-model="model.email">
        </div>


        <button type="submit" ng-click="saveData(model)" >Submit</button>

directive code

create a filemodel directive to parse file

.directive('fileModel', ['$parse', function ($parse) {
return {
    restrict: 'A',
    link: function(scope, element, attrs) {
        var model = $parse(attrs.fileModel);
        var modelSetter = model.assign;

        element.bind('change', function(){
            scope.$apply(function(){
                modelSetter(scope, element[0].files[0]);
            });
        });
    }
};}]);

Service code

append the file and fields to form data and do $http.post as shown below remember to keep 'Content-Type': undefined

 .service('fileUploadService', ['$http', function ($http) {
    this.uploadFileToUrl = function(file, username, password, dob, email, uploadUrl){
        var myFormData = new FormData();

        myFormData.append('file', file);
        myFormData.append('username', username);
        myFormData.append('password', password);
        myFormData.append('dob', dob);
        myFormData.append('email', email);


        $http.post(uploadUrl, myFormData, {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
            .success(function(){

            })
            .error(function(){
            });
    }
}]);

In controller

Now in controller call the service by sending required data to be appended in parameters,

$scope.saveData  = function(model){
    var file = model.myFile;
    var uploadUrl = "/api/createUsers";
    fileUpload.uploadFileToUrl(file, model.username, model.password, model.dob, model.email, uploadUrl);
};

visual c++: #include files from other projects in the same solution

#include has nothing to do with projects - it just tells the preprocessor "put the contents of the header file here". If you give it a path that points to the correct location (can be a relative path, like ../your_file.h) it will be included correctly.

You will, however, have to learn about libraries (static/dynamic libraries) in order to make such projects link properly - but that's another question.

What is the use of "object sender" and "EventArgs e" parameters?

EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.

Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event.

Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx

Example:

protected void btn_Click (object sender, EventArgs e){
   Button btn = sender as Button;
   btn.Text = "clicked!";
}

Edit: When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked

Twitter Bootstrap Multilevel Dropdown Menu

Since Bootstrap 3 removed the submenu part and we need to adapt ourselves the style, I think it's better to go with SmartMenu Bootstrap: https://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar.html#

That would save us time on mobile responsive and style.

This plugin also very promising.

How to make <div> fill <td> height

Really have to do this with JS. Here's a solution. I didn't use your class names, but I called the div within the td class name of "full-height" :-) Used jQuery, obviously. Note this was called from jQuery(document).ready(function(){ setFullHeights();}); Also note if you have images, you are going to have to iterate through them first with something like:

function loadedFullHeights(){
var imgCount = jQuery(".full-height").find("img").length;
if(imgCount===0){
    return setFullHeights();
}
var loaded = 0;
jQuery(".full-height").find("img").load(function(){
    loaded++;
    if(loaded ===imgCount){
        setFullHeights()
    }
});

}

And you would want to call the loadedFullHeights() from docReady instead. This is actually what I ended up using just in case. Got to think ahead you know!

function setFullHeights(){
var par;
var height;
var $ = jQuery;
var heights=[];
var i = 0;
$(".full-height").each(function(){
    par =$(this).parent();
    height = $(par).height();
    var tPad = Number($(par).css('padding-top').replace('px',''));
    var bPad = Number($(par).css('padding-bottom').replace('px',''));
    height -= tPad+bPad;
    heights[i]=height;
    i++;
});
for(ii in heights){
    $(".full-height").eq(ii).css('height', heights[ii]+'px');
}

}

set height of imageview as matchparent programmatically

For Kotlin Users

val params = mImageView?.layoutParams as FrameLayout.LayoutParams
params.width = FrameLayout.LayoutParams.MATCH_PARENT
params.height = FrameLayout.LayoutParams.MATCH_PARENT
mImageView?.layoutParams = params

Here I used FrameLayout.LayoutParams since my views( ImageView) parent is FrameLayout

ab load testing

The apache benchmark tool is very basic, and while it will give you a solid idea of some performance, it is a bad idea to only depend on it if you plan to have your site exposed to serious stress in production.

Having said that, here's the most common and simplest parameters:

-c: ("Concurrency"). Indicates how many clients (people/users) will be hitting the site at the same time. While ab runs, there will be -c clients hitting the site. This is what actually decides the amount of stress your site will suffer during the benchmark.

-n: Indicates how many requests are going to be made. This just decides the length of the benchmark. A high -n value with a -c value that your server can support is a good idea to ensure that things don't break under sustained stress: it's not the same to support stress for 5 seconds than for 5 hours.

-k: This does the "KeepAlive" funcionality browsers do by nature. You don't need to pass a value for -k as it it "boolean" (meaning: it indicates that you desire for your test to use the Keep Alive header from HTTP and sustain the connection). Since browsers do this and you're likely to want to simulate the stress and flow that your site will have from browsers, it is recommended you do a benchmark with this.

The final argument is simply the host. By default it will hit http:// protocol if you don't specify it.

ab -k -c 350 -n 20000 example.com/

By issuing the command above, you will be hitting http://example.com/ with 350 simultaneous connections until 20 thousand requests are met. It will be done using the keep alive header.

After the process finishes the 20 thousand requests, you will receive feedback on stats. This will tell you how well the site performed under the stress you put it when using the parameters above.

For finding out how many people the site can handle at the same time, just see if the response times (means, min and max response times, failed requests, etc) are numbers your site can accept (different sites might desire different speeds). You can run the tool with different -c values until you hit the spot where you say "If I increase it, it starts to get failed requests and it breaks".

Depending on your website, you will expect an average number of requests per minute. This varies so much, you won't be able to simulate this with ab. However, think about it this way: If your average user will be hitting 5 requests per minute and the average response time that you find valid is 2 seconds, that means that 10 seconds out of a minute 1 user will be on requests, meaning only 1/6 of the time it will be hitting the site. This also means that if you have 6 users hitting the site with ab simultaneously, you are likely to have 36 users in simulation, even though your concurrency level (-c) is only 6.

This depends on the behavior you expect from your users using the site, but you can get it from "I expect my user to hit X requests per minute and I consider an average response time valid if it is 2 seconds". Then just modify your -c level until you are hitting 2 seconds of average response time (but make sure the max response time and stddev is still valid) and see how big you can make -c.

I hope I explained this clear :) Good luck

Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

One minor thing, which wasted my time.

Put the conditions(if comparing using " = ", " != ") in parenthesis, failing to do so also raises this exception. This will work

df[(some condition) conditional operator (some conditions)]

This will not

df[some condition conditional-operator some condition]

Checking if output of a command contains a certain string in a shell script

Another option is to check for regular expression match on the command output.

For example:

[[ "$(./somecommand)" =~ "sub string" ]] && echo "Output includes 'sub string'"

Convert string to nullable type (int, double, etc...)

There is a generic solution (for any type). Usability is good, but implementation should be improved: http://cleansharp.de/wordpress/2011/05/generischer-typeconverter/

This allows you to write very clean code like this:

string value = null;
int? x = value.ConvertOrDefault<int?>();

and also:

object obj = 1;  

string value = null;
int x = 5;
if (value.TryConvert(out x))
    Console.WriteLine("TryConvert example: " + x); 

bool boolean = "false".ConvertOrDefault<bool>();
bool? nullableBoolean = "".ConvertOrDefault<bool?>();
int integer = obj.ConvertOrDefault<int>();
int negativeInteger = "-12123".ConvertOrDefault<int>();
int? nullableInteger = value.ConvertOrDefault<int?>();
MyEnum enumValue = "SecondValue".ConvertOrDefault<MyEnum>();

MyObjectBase myObject = new MyObjectClassA();
MyObjectClassA myObjectClassA = myObject.ConvertOrDefault<MyObjectClassA>();

convert string date to java.sql.Date

This works for me without throwing an exception:

package com.sandbox;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Sandbox {

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date parsed = format.parse("20110210");
        java.sql.Date sql = new java.sql.Date(parsed.getTime());
    }


}

R not finding package even after package installation

So the package will be downloaded in a temp folder C:\Users\U122337.BOSTONADVISORS\AppData\Local\Temp\Rtmp404t8Y\downloaded_packages from where it will be installed into your library folder, e.g. C:\R\library\zoo

What you have to do once install command is done: Open Packages menu -> Load package...

You will see your package on the list. You can automate this: How to load packages in R automatically?

Where is adb.exe in windows 10 located?

Open a cmd window and type where adb.exe

For me

D:\android-sdk_r24.4.1-windows\android-sdk-windows\platform-tools\adb.exe

Is there a NumPy function to return the first index of something in an array?

There are lots of operations in NumPy that could perhaps be put together to accomplish this. This will return indices of elements equal to item:

numpy.nonzero(array - item)

You could then take the first elements of the lists to get a single element.