Programs & Examples On #Deliverance

How can I fill a div with an image while keeping it proportional?

The CSS object-fit: cover and object-position: left center property values now address this issue.

Finalize vs Dispose

Class instances often encapsulate control over resources that are not managed by the runtime, such as window handles (HWND), database connections, and so on. Therefore, you should provide both an explicit and an implicit way to free those resources. Provide implicit control by implementing the protected Finalize Method on an object (destructor syntax in C# and the Managed Extensions for C++). The garbage collector calls this method at some point after there are no longer any valid references to the object. In some cases, you might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. If an external resource is scarce or expensive, better performance can be achieved if the programmer explicitly releases resources when they are no longer being used. To provide explicit control, implement the Dispose method provided by the IDisposable Interface. The consumer of the object should call this method when it is done using the object. Dispose can be called even if other references to the object are alive.

Note that even when you provide explicit control by way of Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose.

Error ITMS-90717: "Invalid App Store Icon"

Invalid App Store Icon. The App Store Icon in the asset catalog in 'YourApp.app' can't be transparent nor contain an alpha channel.

Solved in Catalina

  1. copy to desktop
  2. open image in PREVIEW APP.
  3. File -> Duplicate Close the first opened preview
  4. after try to close the second duplicated image, then it will prompt to save there you will available to untick AlPHA

look into my screenshot

nvalid App Store Icon Solved in Catalina

How to know user has clicked "X" or the "Close" button?

I also had to register the closing function inside the form's "InitializeComponent()" method:

private void InitializeComponent() {
// ...
this.FormClosing += FrmMain_FormClosing;
// ...
}

My "FormClosing" function looks similar to the given answer (https://stackoverflow.com/a/2683846/3323790):

private void FrmMain_FormClosing(object sender, FormClosingEventArgs e) {
    if (e.CloseReason == CloseReason.UserClosing){
        MessageBox.Show("Closed by User", "UserClosing");
    }

    if (e.CloseReason == CloseReason.WindowsShutDown){
        MessageBox.Show("Closed by Windows shutdown", "WindowsShutDown");
    }
}

One more thing to mention: There is also a "FormClosed" function which occurs after "FormClosing". To use this function, register it as shown below:

this.FormClosed += MainPage_FormClosed;

private void MainPage_FormClosing(object sender, FormClosingEventArgs e)
{
// your code after the form is closed
}

How would I extract a single file (or changes to a file) from a git stash?

If you use git stash apply rather than git stash pop, it will apply the stash to your working tree but still keep the stash.

With this done, you can add/commit the file that you want and then reset the remaining changes.

How to insert a data table into SQL Server database table?

I am giving a very simple code, which i used in my solution (I have the same problem statement as yours)

    SqlConnection con = connection string ;
//new SqlConnection("Data Source=.;uid=sa;pwd=sa123;database=Example1");
con.Open();
string sql = "Create Table abcd (";
foreach (DataColumn column in dt.Columns)
{
    sql += "[" + column.ColumnName + "] " + "nvarchar(50)" + ",";
}
sql = sql.TrimEnd(new char[] { ',' }) + ")";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
using (var adapter = new SqlDataAdapter("SELECT * FROM abcd", con)) 
using(var builder = new SqlCommandBuilder(adapter))
{
adapter.InsertCommand = builder.GetInsertCommand();
adapter.Update(dt);
// adapter.Update(ds.Tables[0]); (Incase u have a data-set)
}
con.Close();

I have given a predefined table-name as "abcd" (you must take care that a table by this name doesn't exist in your database). Please vote my answer if it works for you!!!! :)

jquery: $(window).scrollTop() but no $(window).scrollBottom()

This is a quick hack: just assign the scroll value to a very large number. This will ensure that the page is scrolled to the bottom. Using plain javascript:

document.body.scrollTop = 100000;

height: calc(100%) not working correctly in CSS

First off - check with Firebug(or what ever your preference is) whether the css property is being interpreted by the browser. Sometimes the tool used will give you the problem right there, so no more hunting.

Second off - check compatibility: http://caniuse.com/#feat=calc

And third - I ran into some problems a few hours ago and just resolved it. It's the smallest thing but it kept me busy for 30 minutes.

Here's how my CSS looked

#someElement {
    height:calc(100%-100px);
    height:-moz-calc(100%-100px);
    height:-webkit-calc(100%-100px);
}

Looks right doesn't it? WRONG Here's how it should look:

#someElement {
    height:calc(100% - 100px);
    height:-moz-calc(100% - 100px);
    height:-webkit-calc(100% - 100px);
}

Looks the same right?

Notice the spaces!!! Checked android browser, Firefox for android, Chrome for android, Chrome and Firefox for Windows and Internet Explorer 11. All of them ignored the CSS if there were no spaces.

Hope this helps someone.

Install gitk on Mac

If you happen to already have Fink installed, this worked for me on Yosemite / OS X 10.10.5:

fink install git

Note that as a side effect, other git commands are also using the newer git version (2.5.1) installed by Fink, rather than the version from Apple (2.3.2), which is still there but preempted by my $PATH.

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

I resolved this problem, searching the dll's file in C:\Windows\assembly\GAC_MSIL\ and copied to bin directory of the proyect deployed. That work for me.

How/when to use ng-click to call a route?

Routes monitor the $location service and respond to changes in URL (typically through the hash). To "activate" a route, you simply change the URL. The easiest way to do that is with anchor tags.

<a href="#/home">Go Home</a>
<a href="#/about">Go to About</a>

Nothing more complicated is needed. If, however, you must do this from code, the proper way is by using the $location service:

$scope.go = function ( path ) {
  $location.path( path );
};

Which, for example, a button could trigger:

<button ng-click="go('/home')"></button>

Pass user defined environment variable to tomcat

My recipe to fix it:

  1. DID NOT WORK >> Set as system environment variable: I had set the environment variable in my mac bash_profile, however, Tomcat did not see that variable.

  2. DID NOT WORK >> setenv.sh: Apache's recommendation was to have user-defined environment variables in setenv.sh file and I did that.

  3. THIS WORKED!! >> After a little research into Tomcat startup scripts, I found that environment variables set using setenv.sh are lost during the startup. So I had to edit my catalina.sh against the recommendation of Apache and that did the trick.

Add your -DUSER_DEFINED variable in the run command in catalina.sh.

eval exec "\"$_RUNJAVA\"" "\"$LOGGING_CONFIG\"" $LOGGING_MANAGER $JAVA_OPTS $CATALINA_OPTS \
  -classpath "\"$CLASSPATH\"" \
  -Djava.security.manager \
  -Djava.security.policy=="\"$CATALINA_BASE/conf/catalina.policy\"" \
  -Dcatalina.base="\"$CATALINA_BASE\"" \
  -Dcatalina.home="\"$CATALINA_HOME\"" \
  -Djava.io.tmpdir="\"$CATALINA_TMPDIR\"" \
  -DUSER_DEFINED="$USER_DEFINED" \
  org.apache.catalina.startup.Bootstrap "$@" start

P.S: This problem could have been local to my computer. Others would have different problems. Adding my answer to this post just in case anyone is still facing issues with Tomcat not seeing the environment vars after trying out all recommended approaches.

How to post query parameters with Axios?

As of 2021 insted of null i had to add {} in order to make it work!

axios.post(
        url,
        {},
        {
          params: {
            key,
            checksum
          }
        }
      )
      .then(response => {
        return success(response);
      })
      .catch(error => {
        return fail(error);
      });

How to import an existing directory into Eclipse?

The thing that works best for me when that happens is :

  1. Create a new eclipse project(JAVA)

  2. Take your source file (contents of the src folder!!!) and drag from finder and drop into the src folder in eclipse IDE

  3. Make sure you add your external jars and stuff and tada you're done!!

How do I convert from a string to an integer in Visual Basic?

You can use the following to convert string to int:

  • CInt(String) for ints
  • CDec(String) for decimals

For details refer to Type Conversion Functions (Visual Basic).

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

CGContextDrawImage draws image upside down when passed UIImage.CGImage

Swift 5 answer based on @ZpaceZombor's excellent answer

If you have a UIImage, just use

var image: UIImage = .... 
image.draw(in: CGRect)

If you have a CGImage use my category below

Note: Unlike some other answers, this one takes into account that the rect you want to draw in might have y != 0. Those answers that don't take that into account are incorrect and won't work in the general case.

extension CGContext {
    final func drawImage(image: CGImage, inRect rect: CGRect) {

        //flip coords
        let ty: CGFloat = (rect.origin.y + rect.size.height)
        translateBy(x: 0, y: ty)
        scaleBy(x: 1.0, y: -1.0)

        //draw image
        let rect__y_zero = CGRect(x: rect.origin.x, y: 0, width: rect.width, height: rect.height)
        draw(image, in: rect__y_zero)

        //flip back
        scaleBy(x: 1.0, y: -1.0)
        translateBy(x: 0, y: -ty)

    }
} 

Use like this:

let imageFrame: CGRect = ...
let context: CGContext = ....
let img: CGImage = ..... 
context.drawImage(image: img, inRect: imageFrame)

How to use BeginInvoke C#

I guess your code relates to Windows Forms.
You call BeginInvoke if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases.
Roughly speaking this is accomplished be passing the delegate to some procedure which is being periodically executed. (message loop processing and the stuff like that)

If BeginInvoke is called for Delegate type the delegate is just invoked asynchronously.
(Invoke for the sync version.)

If you want more universal code which works perfectly for WPF and WinForms you can consider Task Parallel Library and running the Task with the according context. (TaskScheduler.FromCurrentSynchronizationContext())

And to add a little to already said by others: Lambdas can be treated either as anonymous methods or expressions.
And that is why you cannot just use var with lambdas: compiler needs a hint.

UPDATE:

this requires .Net v4.0 and higher

// This line must be called in UI thread to get correct scheduler
var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();

// this can be called anywhere
var task = new System.Threading.Tasks.Task( () => someformobj.listBox1.SelectedIndex = 0);

// also can be called anywhere. Task  will be scheduled for execution.
// And *IF I'm not mistaken* can be (or even will be executed synchronously)
// if this call is made from GUI thread. (to be checked) 
task.Start(scheduler);

If you started the task from other thread and need to wait for its completition task.Wait() will block calling thread till the end of the task.

Read more about tasks here.

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

If you want to have the filename with extension I use this function to get it. It also works with google drive file picks

public static String getFileName(Uri uri) {
    String result;

    //if uri is content
    if (uri.getScheme() != null && uri.getScheme().equals("content")) {
        Cursor cursor = global.getInstance().context.getContentResolver().query(uri, null, null, null, null);
        try {
            if (cursor != null && cursor.moveToFirst()) {
                //local filesystem
                int index = cursor.getColumnIndex("_data");
                if(index == -1)
                    //google drive
                    index = cursor.getColumnIndex("_display_name");
                result = cursor.getString(index);
                if(result != null)
                    uri = Uri.parse(result);
                else
                    return null;
            }
        } finally {
            cursor.close();
        }
    }

    result = uri.getPath();

    //get filename + ext of path
    int cut = result.lastIndexOf('/');
    if (cut != -1)
        result = result.substring(cut + 1);
    return result;
}

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

For me, I was receiving this error when connecting to the new IP Address I had configured FileZilla to bind to and saved the configuration. After trying all of the other answers unsuccessfully, I decided to connect to the old IP Address to see what came up; lo and behold it responded.

I restarted the FileZilla Windows Service and it immediately came back listening on the correct IP. Pretty elementary, but it cost me some time today as a noob to FZ.

Hopefully this helps someone out in the same predicament.

How to implement the Android ActionBar back button?

To enable the ActionBar back button you obviously need an ActionBar in your Activity. This is set by the theme you are using. You can set the theme for your Activity in the AndroidManfiest.xml. If you are using e.g the @android:style/Theme.NoTitleBar theme, you don't have an ActionBar. In this case the call to getActionBar() will return null. So make sure you have an ActionBar first.

The next step is to set the android:parentActivityName to the activity you want to navigate if you press the back button. This should be done in the AndroidManifest.xml too.

Now you can enable the back button in the onCreate method of your "child" activity.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    getActionBar().setDisplayHomeAsUpEnabled(true);
}

Now you should implement the logic for the back button. You simply override the onOptionsItemSelected method in your "child" activity and check for the id of the back button which is android.R.id.home.

Now you can fire the method NavUtils.navigateUpFromSameTask(this); BUT if you don't have specified the android:parentActivityName in you AndroidManifest.xml this will crash your app.

Sometimes this is what you want because it is reminding you that you forgot "something". So if you want to prevent this, you can check if your activity has a parent using the getParentActivityIntent() method. If this returns null, you don't have specified the parent.

In this case you can fire the onBackPressed() method that does basically the same as if the user would press the back button on the device. A good implementation that never crashes your app would be:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
            if (getParentActivityIntent() == null) {
                Log.i(TAG, "You have forgotten to specify the parentActivityName in the AndroidManifest!");
                onBackPressed();
            } else {
                NavUtils.navigateUpFromSameTask(this);
            }
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Please notice that the animation that the user sees is different between NavUtils.navigateUpFromSameTask(this); and onBackPressed().

It is up to you which road you take, but I found the solution helpful, especially if you use a base class for all of your activities.

base64 encoded images in email signatures

Recently I had the same problem to include QR image/png in email. The QR image is a byte array which is generated using ZXing. We do not want to save it to a file because saving/reading from a file is too expensive (slow). So both of the answers above do not work for me. Here's what I did to solve this problem:

import javax.mail.util.ByteArrayDataSource;
import org.apache.commons.mail.ImageHtmlEmail;
...
ImageHtmlEmail email = new ImageHtmlEmail();
byte[] qrImageBytes = createQRCode(); // get your image byte array
ByteArrayDataSource qrImageDataSource = new ByteArrayDataSource(qrImageBytes, "image/png");
String contentId = email.embed(qrImageDataSource, "QR Image");

Let's say the contentId is "111122223333", then your HTML part should have this:

<img src="cid: 111122223333">

There's no need to convert the byte array to Base64 because Commons Mail does the conversion for you automatically. Hope this helps.

The system cannot find the file specified in java

When you run a jar, your Main class itself becomes args[0] and your filename comes immediately after.

I had the same issue: I could locate my file when provided the absolute path from eclipse (because I was referring to the file as args[0]). Yet when I run the same from jar, it was trying to locate my main class - which is when I got the idea that I should be reading my file from args[1].

Detect page change on DataTable

An alternative approach would be to register an event handler on the pagination link like so:

$("#dataTableID_paginate").on("click", "a", function() { alert("clicked") });

Replace "#dataTableID_" with the ID of your table, of course. And I'm using JQuery's ON method as that is the current best practice.

Copy folder recursively, excluding some folders

Similar to Jeff's idea (untested):

find . -name * -print0 | grep -v "exclude" | xargs -0 -I {} cp -a {} destination/

Swift performSelector:withObject:afterDelay: is unavailable

Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
    // your function here
}

Swift 3

DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(0.1)) {
    // your function here
}

Swift 2

let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) 
dispatch_after(dispatchTime, dispatch_get_main_queue(), { 
    // your function here 
})

How do I add an existing Solution to GitHub from Visual Studio 2013

OK this worked for me.

  1. Open the solution in Visual Studio 2013
  2. Select File | Add to Source Control
  3. Select the Microsoft Git Provider

That creates a local GIT repository

  1. Surf to GitHub
  2. Create a new repository DO NOT SELECT Initialize this repository with a README

That creates an empty repository with no Master branch

  1. Once created open the repository and copy the URL (it's on the right of the screen in the current version)
  2. Go back to Visual Studio
    • Make sure you have the Microsoft Git Provider selected under Tools/Options/Source Control/Plug-in Selection
  3. Open Team Explorer
  4. Select Home | Unsynced Commits
  5. Enter the GitHub URL into the yellow box (use HTTPS URL, not the default shown SSH one)
  6. Click Publish
  7. Select Home | Changes
  8. Add a Commit comment
  9. Select Commit and Push from the drop down

Your solution is now in GitHub

Conda activate not working?

As of conda 4.4, the command

conda activate <envname>

is the same on all platforms. The procedure to add conda to the PATH environment variable for non-Windows platforms (on Windows you should use the Anaconda Prompt), as well as the change in environment activation procedure, is detailed in the release notes for conda 4.4.0.


For conda versions older than 4.4, command is either

source activate <envname>

on Linux and macOS or

activate <envname>

on Windows. You need to remove the conda.

How to use andWhere and orWhere in Doctrine?

$q->where("a = 1")
  ->andWhere("b = 1 OR b = 2")
  ->andWhere("c = 2 OR c = 2")
  ;

Only using @JsonIgnore during serialization, but not deserialization

You can also do like:

@JsonIgnore
@JsonProperty(access = Access.WRITE_ONLY)
private String password;

It's worked for me

Build fat static library (device + simulator) using Xcode and SDK 4+

I have spent many hours trying to build a fat static library that will work on armv7, armv7s, and the simulator. Finally found a solution.

The gist is to build the two libraries (one for the device and then one for the simulator) separately, rename them to distinguish from each other, and then lipo -create them into one library.

lipo -create libPhone.a libSimulator.a -output libUniversal.a

I tried it and it works!

Gradle store on local file system

Many answers are correct! I want to add that you can easily find your download location with

gradle --info build

like described in https://stackoverflow.com/a/54000767/4471199.

New downloaded artifacts will be shown in stdout:

Downloading https://plugins.gradle.org/m2/org/springframework/boot/spring-boot-parent/2.1.7.RELEASE/spring-boot-parent-2.1.7.RELEASE.pom to /tmp/gradle_download551283009937119777bin

In this case, I used the docker image gradle:5.6.2-jdk12. As you can see, the docker container uses /tmp as download location.

COPY with docker but with exclusion

In my case, my Dockerfile contained an installation step, which produced the vendor directory (the PHP equivalent of node_modules). I then COPY this directory over to the final application image. Therefore, I could not put vendor in my .dockerignore. My solution was simply to delete the directory before performing composer install (the PHP equivalent of npm install).

FROM composer AS composer
WORKDIR /app
COPY . .
RUN rm -rf vendor \
    && composer install 

FROM richarvey/nginx-php-fpm
WORKDIR /var/www/html
COPY --from=composer /app .

This solution works and does not bloat the final image, but it is not ideal, because the vendor directory on the host is copied into the Docker context during the build process, which adds time.

How can I confirm a database is Oracle & what version it is using SQL?

You can either use

SELECT * FROM v$version;

or

SET SERVEROUTPUT ON
EXEC dbms_output.put_line( dbms_db_version.version );

if you don't want to parse the output of v$version.

Printing result of mysql query from variable

well you are returning an array of items from the database. so you need something like this.

   $dave= mysql_query("SELECT order_date, no_of_items, shipping_charge, 
    SUM(total_order_amount) as test FROM `orders` 
    WHERE DATE(`order_date`) = DATE(NOW()) GROUP BY DATE(`order_date`)") 
    or  die(mysql_error());


while ($row = mysql_fetch_assoc($dave)) {
echo $row['order_date'];
echo $row['no_of_items'];
echo $row['shipping_charge'];
echo $row['test '];
}

Converting time stamps in excel to dates

below formula worked form me in MS EXEL

=TEXT(CELL_VALUE/24/60/60/1000 + 25569,"YYYY-MM-DD HH:MM")

CELL_VALUE is timestamp in milliseconds

here is explanation for text function.

How to get the current time as datetime

if you just need the hour of the day

let calendar = NSCalendar.currentCalendar()
var hour = calendar.component(.Hour,fromDate: NSDate())

Limit the output of the TOP command to a specific process name

Using the answer from here I was able to create a one liner

top -pid $(pgrep process_name | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/ -pid /g')

This works for me on MacOS 10.12 (Sierra)

How to get object length

You may use something like Lodash lib and _.toLength(object) should give you the length of your object

Can someone post a well formed crossdomain.xml sample?

If you're using webservices, you'll also need the 'allow-http-request-headers-from' element. Here's our default, development, 'allow everything' policy.

<?xml version="1.0" ?>
<cross-domain-policy>
  <site-control permitted-cross-domain-policies="master-only"/>
  <allow-access-from domain="*"/>
  <allow-http-request-headers-from domain="*" headers="*"/>
</cross-domain-policy>

Run a php app using tomcat?

There this PHP/Java bridge. This is basically running PHP via FastCGI. I have not used it myself.

Passing command line arguments to R CMD BATCH

You need to put arguments before my_script.R and use - on the arguments, e.g.

R CMD BATCH -blabla my_script.R

commandArgs() will receive -blabla as a character string in this case. See the help for details:

$ R CMD BATCH --help
Usage: R CMD BATCH [options] infile [outfile]

Run R non-interactively with input from infile and place output (stdout
and stderr) to another file.  If not given, the name of the output file
is the one of the input file, with a possible '.R' extension stripped,
and '.Rout' appended.

Options:
  -h, --help        print short help message and exit
  -v, --version     print version info and exit
  --no-timing           do not report the timings
  --            end processing of options

Further arguments starting with a '-' are considered as options as long
as '--' was not encountered, and are passed on to the R process, which
by default is started with '--restore --save --no-readline'.
See also help('BATCH') inside R.

How to remove all non-alpha numeric characters from a string in MySQL?

the alphanum function (self answered) have a bug, but I don't know why. For text "cas synt ls 75W140 1L" return "cassyntls75W1401", "L" from the end is missing some how.

Now I use

delimiter //
DROP FUNCTION IF EXISTS alphanum //
CREATE FUNCTION alphanum(prm_strInput varchar(255))
RETURNS VARCHAR(255)
DETERMINISTIC
BEGIN
  DECLARE i INT DEFAULT 1;
  DECLARE v_char VARCHAR(1);
  DECLARE v_parseStr VARCHAR(255) DEFAULT ' ';
WHILE (i <= LENGTH(prm_strInput) )  DO
  SET v_char = SUBSTR(prm_strInput,i,1);
  IF v_char REGEXP  '^[A-Za-z0-9]+$' THEN 
        SET v_parseStr = CONCAT(v_parseStr,v_char);  
  END IF;
  SET i = i + 1;
END WHILE;
RETURN trim(v_parseStr);
END
//

(found on google)

How to know what the 'errno' means?

I use the following script:

#!/usr/bin/python

import errno
import os
import sys

toname = dict((str(getattr(errno, x)), x) 
              for x in dir(errno) 
              if x.startswith("E"))
tocode = dict((x, getattr(errno, x)) 
              for x in dir(errno) 
              if x.startswith("E"))

for arg in sys.argv[1:]:
    if arg in tocode:
        print arg, tocode[arg], os.strerror(tocode[arg])
    elif arg in toname:
        print toname[arg], arg, os.strerror(int(arg))
    else:
        print "Unknown:", arg

How to hash a password

Most of the other answers here are somewhat out-of-date with today's best practices. As such here is the application of using PBKDF2/Rfc2898DeriveBytes to store and verify passwords. The following code is in a stand-alone class in this post: Another example of how to store a salted password hash. The basics are really easy, so here it is broken down:

STEP 1 Create the salt value with a cryptographic PRNG:

byte[] salt;
new RNGCryptoServiceProvider().GetBytes(salt = new byte[16]);

STEP 2 Create the Rfc2898DeriveBytes and get the hash value:

var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 100000);
byte[] hash = pbkdf2.GetBytes(20);

STEP 3 Combine the salt and password bytes for later use:

byte[] hashBytes = new byte[36];
Array.Copy(salt, 0, hashBytes, 0, 16);
Array.Copy(hash, 0, hashBytes, 16, 20);

STEP 4 Turn the combined salt+hash into a string for storage

string savedPasswordHash = Convert.ToBase64String(hashBytes);
DBContext.AddUser(new User { ..., Password = savedPasswordHash });

STEP 5 Verify the user-entered password against a stored password

/* Fetch the stored value */
string savedPasswordHash = DBContext.GetUser(u => u.UserName == user).Password;
/* Extract the bytes */
byte[] hashBytes = Convert.FromBase64String(savedPasswordHash);
/* Get the salt */
byte[] salt = new byte[16];
Array.Copy(hashBytes, 0, salt, 0, 16);
/* Compute the hash on the password the user entered */
var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 100000);
byte[] hash = pbkdf2.GetBytes(20);
/* Compare the results */
for (int i=0; i < 20; i++)
    if (hashBytes[i+16] != hash[i])
        throw new UnauthorizedAccessException();

Note: Depending on the performance requirements of your specific application, the value 100000 can be reduced. A minimum value should be around 10000.

MySql sum elements of a column

select
  sum(a) as atotal,
  sum(b) as btotal,
  sum(c) as ctotal
from
  yourtable t
where
  t.id in (1, 2, 3)

Asynchronous Function Call in PHP

This old question has a new answer. There are a few "async" solutions for PHP this days (which are equivalent to Python's multiprocess in the sense that they spawn new independent PHP processes rather than manage it at the framework level)

The two solutions I have seen are

Give them a try!

Custom circle button

here is how you can perform simply, make a drawable resource file in drawable.xml. Say round_button.xml and then paste the following code.

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

    <item>
       <shape
           android:shape="oval">

           <solid
               android:color="@color/button_start_gradient_color"/>
       </shape>
    </item>
    <item
        android:drawable="@drawable/microphone"/>
</layer-list>

Note:- use your own color and drawable resource as i have used @drawable/microphone

Following is the result [1]: https://i.stack.imgur.com/QyhdJ.png

Git status shows files as changed even though contents are the same

For me the issue was a case difference in the file.

I renamed the file and committed the delete, It showed both the upper and lower case versions of the file to be deleted.

After the delete was committed I renamed the file back to its original name and pushed.

Breaking to a new line with inline-block?

I think floats may work best for you here, if you dont want the element to occupy the whole line, float it left should work.

.text span {
       background:rgba(165, 220, 79, 0.8);
       float: left;
       clear: left;
       padding:7px 10px;
       color:white;
    }

Note:Remove <br/>'s before using this off course.

INNER JOIN same table

You can also use UNION like

SELECT  user_fname ,
        user_lname
FROM    users 
WHERE   user_id = $_GET[id]
UNION
SELECT  user_fname ,
        user_lname
FROM    users 
WHERE   user_parent_id = $_GET[id]

"query function not defined for Select2 undefined error"

Covered in this google group thread

The problem was because of the extra div that was being added by the select2. Select2 had added new div with class "select2-container form-select" to wrap the select created. So the next time i loaded the function, the error was being thrown as select2 was being attached to the div element. I changed my selector...

Prefix select2 css identifier with specific tag name "select":

$('select.form-select').select2();

How to insert &nbsp; in XSLT

Use the entity code &#160; instead.

&nbsp; is a HTML "character entity reference". There is no named entity for non-breaking space in XML, so you use the code &#160;.

Wikipedia includes a list of XML and HTML entities, and you can see that there are only 5 "predefined entities" in XML, but HTML has over 200. I'll also point over to Creating a space (&nbsp;) in XSL which has excellent answers.

how to define ssh private key for servers fetched by dynamic inventory in files

The best solution I could find for this problem is to specify private key file in ansible.cfg (I usually keep it in the same folder as a playbook):

[defaults]
inventory=ec2.py
vault_password_file = ~/.vault_pass.txt
host_key_checking = False
private_key_file = /Users/eric/.ssh/secret_key_rsa

Though, it still sets private key globally for all hosts in playbook.

Note: You have to specify full path to the key file - ~user/.ssh/some_key_rsa silently ignored.

Hiding user input on terminal in Linux script

I always like to use Ansi escape characters:

echo -e "Enter your password: \x1B[8m"
echo -e "\x1B[0m"

8m makes text invisible and 0m resets text to "normal." The -e makes Ansi escapes possible.

The only caveat is that you can still copy and paste the text that is there, so you probably shouldn't use this if you really want security.

It just lets people not look at your passwords when you type them in. Just don't leave your computer on afterwards. :)


NOTE:

The above is platform independent as long as it supports Ansi escape sequences.

However, for another Unix solution, you could simply tell read to not echo the characters...

printf "password: "
let pass $(read -s)
printf "\nhey everyone, the password the user just entered is $pass\n"

What does 'IISReset' do?

IISReset restarts the entire webserver (including all associated sites). If you're just looking to reset a single ASP.NET website, you should just recycle that AppDomain.

The most common way to reset an ASP.NET website is to edit the web.config file, but you can also create an admin page with the following:

public partial class Recycle : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        HttpRuntime.UnloadAppDomain();
    }
}

Here's a blog post I wrote with more info: Avoid IISRESET in ASP.NET Applications

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

Rebuilding the slave using LVM

Here is the method we use to rebuild MySQL slaves using Linux LVM. This guarantees a consistent snapshot while requiring very minimal downtime on your master.

Set innodb max dirty pages percent to zero on the master MySQL server. This will force MySQL to write all the pages to the disk which will significantly speed up the restart.

set global innodb_max_dirty_pages_pct = 0;

To monitor the number of dirty pages run the command

mysqladmin ext -i10 | grep dirty

Once the number stop decreasing you have reach the point to continue. Next reset the master to clear the old bin logs / relay logs:

RESET MASTER;

Execute lvdisplay to get LV Path

lvdisplay

Output will look like this

--- Logical volume ---
LV Path                /dev/vg_mysql/lv_data
LV Name                lv_data
VG Name                vg_mysql

Shutdown the master database with command

service mysql stop

Next take a snaphot, mysql_snapshot will be the new logical volume name. If binlogs are place on the OS drive those need to be snapshot as well.

lvcreate --size 10G --snapshot --name mysql_snapshot /dev/vg_mysql/lv_data

Start master again with command

service mysql start

Restore dirty pages setting to the default

set global innodb_max_dirty_pages_pct = 75;

Run lvdisplay again to make sure the snapshot is there and visible

lvdisplay

Output:

--- Logical volume ---
LV Path                /dev/vg_mysql/mysql_snapshot
LV Name                mysql_snapshot
VG Name                vg_mysql

Mount the snapshot

mkdir /mnt/mysql_snapshot
mount /dev/vg_mysql/mysql_snapshot /mnt/mysql_snapshot

If you have an existing MySQL slave running you need to stop it

service mysql stop

Next you need to clear MySQL data folder

cd /var/lib/mysql
rm -fr *

Back to master. Now rsync the snapshot to the MySQL slave

rsync --progress -harz /mnt/mysql_snapshot/ targethostname:/var/lib/mysql/

Once rsync has completed you may unmount and remove the snapshot

umount /mnt/mysql_snapshot
lvremove -f /dev/vg_mysql/mysql_snapshot

Create replication user on the master if the old replication user doesn't exist or password is unknown

GRANT REPLICATION SLAVE on *.* to 'replication'@'[SLAVE IP]' identified by 'YourPass';

Verify that /var/lib/mysql data files are owned by the mysql user, if so you can omit the following command:

chown -R mysql:mysql /var/lib/mysql

Next record the binlog position

ls -laF | grep mysql-bin

You will see something like

..
-rw-rw----     1 mysql mysql  1073750329 Aug 28 03:33 mysql-bin.000017
-rw-rw----     1 mysql mysql  1073741932 Aug 28 08:32 mysql-bin.000018
-rw-rw----     1 mysql mysql   963333441 Aug 28 15:37 mysql-bin.000019
-rw-rw----     1 mysql mysql    65657162 Aug 28 16:44 mysql-bin.000020

Here the master log file is the highest file number in sequence and bin log position is the file size. Record these values:

master_log_file=mysql-bin.000020
master_log_post=65657162

Next start the slave MySQL

service mysql start

Execute change master command on the slave by executing the following:

CHANGE MASTER TO 
master_host="10.0.0.12", 
master_user="replication", 
master_password="YourPass", 
master_log_file="mysql-bin.000020", 
master_log_pos=65657162; 

Finally start the slave

SLAVE START;

Check slave status:

SHOW SLAVE STATUS;

Make sure Slave IO is running and there are no connection errors. Good luck!

BR, Juha Vehnia

I recently wrote this on my blog which is found here... There are few more details there but the story is the same.

http://www.juhavehnia.com/2015/05/rebuilding-mysql-slave-using-linux-lvm.html

how do you filter pandas dataframes by multiple columns

Start from pandas 0.13, this is the most efficient way.

df.query('Gender=="Male" & Year=="2014" ')

How to calculate the IP range when the IP address and the netmask is given?

You might already know this, but to check that you're getting this stuff right have a look at http://www.subnet-calculator.com/ - you can see there how the bits represent the network and host portions of the address.

Does adding a duplicate value to a HashSet/HashMap replace the previous value

HashMap basically contains Entry which subsequently contains Key(Object) and Value(Object).Internally HashSet are HashMap and HashMap do replace values as some of you already pointed..but does it really replaces the keys???No ..and that is the trick here. HashMap keeps its value as key in the underlying HashMap and value is just a dummy object.So if u try to reinsert same Value in HashMap(Key in underlying Map).It just replaces the dummy value and not the Key(Value for HashSet).

Look at the below code for HashSet Class:

public boolean  [More ...] add(E e) {

   return map.put(e, PRESENT)==null;
}

Here e is the value for HashSet but key for underlying map.and key is never replaced. Hope i am able to clear the confusion.

Should I use alias or alias_method?

I think there is an unwritten rule (something like a convention) that says to use 'alias' just for registering a method-name alias, means if you like to give the user of your code one method with more than one name:

class Engine
  def start
    #code goes here
  end
  alias run start
end

If you need to extend your code, use the ruby meta alternative.

class Engine
  def start
    puts "start me"
  end
end

Engine.new.start() # => start me

Engine.class_eval do
  unless method_defined?(:run)
    alias_method :run, :start
    define_method(:start) do
      puts "'before' extension"
      run()
      puts "'after' extension"
    end
  end
end

Engine.new.start
# => 'before' extension
# => start me
# => 'after' extension

Engine.new.run # => start me

How to perform a fade animation on Activity transition?

You could create your own .xml animation files to fade in a new Activity and fade out the current Activity:

fade_in.xml

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
           android:interpolator="@android:anim/accelerate_interpolator"
           android:fromAlpha="0.0" android:toAlpha="1.0"
           android:duration="500" />

fade_out.xml

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
           android:interpolator="@android:anim/accelerate_interpolator"
           android:fromAlpha="1.0" android:toAlpha="0.0"
           android:fillAfter="true"
           android:duration="500" />

Use it in code like that: (Inside your Activity)

Intent i = new Intent(this, NewlyStartedActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

The above code will fade out the currently active Activity and fade in the newly started Activity resulting in a smooth transition.

UPDATE: @Dan J pointed out that using the built in Android animations improves performance, which I indeed found to be the case after doing some testing. If you prefer working with the built in animations, use:

overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

Notice me referencing android.R instead of R to access the resource id.

UPDATE: It is now common practice to perform transitions using the Transition class introduced in API level 19.

Sort Pandas Dataframe by Date

You can use pd.to_datetime() to convert to a datetime object. It takes a format parameter, but in your case I don't think you need it.

>>> import pandas as pd
>>> df = pd.DataFrame( {'Symbol':['A','A','A'] ,
    'Date':['02/20/2015','01/15/2016','08/21/2015']})
>>> df
         Date Symbol
0  02/20/2015      A
1  01/15/2016      A
2  08/21/2015      A
>>> df['Date'] =pd.to_datetime(df.Date)
>>> df.sort('Date') # This now sorts in date order
        Date Symbol
0 2015-02-20      A
2 2015-08-21      A
1 2016-01-15      A

For future search, you can change the sort statement:

>>> df.sort_values(by='Date') # This now sorts in date order
        Date Symbol
0 2015-02-20      A
2 2015-08-21      A
1 2016-01-15      A

How to ignore files/directories in TFS for avoiding them to go to central source repository?

If you're using local workspaces (TFS 2012+) you can now use the .tfignore file to exclude local folders and files from being checked in.

If you add that file to source control you can ensure others on your team share the same exclusion settings.

Full details on MSDN - http://msdn.microsoft.com/en-us/library/ms245454.aspx#tfignore

For the lazy:

You can configure which kinds of files are ignored by placing a text file called .tfignore in the folder where you want rules to apply. The effects of the .tfignore file are recursive. However, you can create .tfignore files in sub-folders to override the effects of a .tfignore file in a parent folder.

The following rules apply to a .tfignore file:

  • # begins a comment line
  • The * and ? wildcards are supported.
  • A filespec is recursive unless prefixed by the \ character.
  • ! negates a filespec (files that match the pattern are not ignored)

Example file:

# Ignore .cpp files in the ProjA sub-folder and all its subfolders
ProjA\*.cpp
# 
# Ignore .txt files in this folder 
\*.txt
#
# Ignore .xml files in this folder and all its sub-folders
*.xml
#
# Ignore all files in the Temp sub-folder
\Temp
#
# Do not ignore .dll files in this folder nor in any of its sub-folders
!*.dll

Difference between webdriver.Dispose(), .Close() and .Quit()

This is a good question I have seen people use Close() when they shouldn't. I looked in the source code for the Selenium Client & WebDriver C# Bindings and found the following.

  1. webDriver.Close() - Close the browser window that the driver has focus of
  2. webDriver.Quit() - Calls Dispose()
  3. webDriver.Dispose() Closes all browser windows and safely ends the session

The code below will dispose the driver object, ends the session and closes all browsers opened during a test whether the test fails or passes.

public IWebDriver Driver;

[SetUp]
public void SetupTest()
{
    Driver = WebDriverFactory.GetDriver();
}

[TearDown]
public void TearDown()
{
    if (Driver != null)
      Driver.Quit();
}

In summary ensure that Quit() or Dispose() is called before exiting the program, and don't use the Close() method unless you're sure of what you're doing.

Note
I found this question when try to figure out a related problem why my VM's were running out of harddrive space. Turns out an exception was causing Quit() or Dispose() to not be called every run which then caused the appData folder to fill the hard drive. So we were using the Quit() method correctly but the code was unreachable. Summary make sure all code paths will clean up your unmanaged objects by using exception safe patterns or implement IDisposable

Also
In the case of RemoteDriver calling Quit() or Dispose() will also close the session on the Selenium Server. If the session isn't closed the log files for that session remain in memory.

In LaTeX, how can one add a header/footer in the document class Letter?

With regard to Brent.Longborough's answer (appering only on page 2 onward), perhaps you need to set the \thispagestyle{} after \begin{document}. I wonder if the letter class is setting the first page style to empty.

How do I import a Swift file from another Swift file?

Check target-membership of PrimeNumberModel.swift in your testing target.

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

I think you should need to check for isset and not empty value, like form was submitted without input data so isset will be true This will prevent you to have any error or notice.

if((isset($_POST['name'])) && !empty($_POST['name']))
{
    $name = $_POST['name']; //note i used $_POST since you have a post form **method='post'**
    echo $name;
}

Removing all script tags from html with JS Regular Expression

/(?:(?!</s\w)<[^<])</s\w*/gi; - Removes any sequence in any combination with

What is the difference between a definition and a declaration?

From the C++ standard section 3.1:

A declaration introduces names into a translation unit or redeclares names introduced by previous declarations. A declaration specifies the interpretation and attributes of these names.

The next paragraph states (emphasis mine) that a declaration is a definition unless...

... it declares a function without specifying the function’s body:

void sqrt(double);  // declares sqrt

... it declares a static member within a class definition:

struct X
{
    int a;         // defines a
    static int b;  // declares b
};

... it declares a class name:

class Y;

... it contains the extern keyword without an initializer or function body:

extern const int i = 0;  // defines i
extern int j;  // declares j
extern "C"
{
    void foo();  // declares foo
}

... or is a typedef or using statement.

typedef long LONG_32;  // declares LONG_32
using namespace std;   // declares std

Now for the big reason why it's important to understand the difference between a declaration and definition: the One Definition Rule. From section 3.2.1 of the C++ standard:

No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, or template.

rails generate model

You need to create new rails application first. Run

rails new mebay
cd mebay
bundle install
rails generate model ...

And try to find Rails 3 tutorial, there are a lot of changes since 2.1 Guides (http://guides.rubyonrails.org/getting_started.html) are good start point.

How to trigger Jenkins builds remotely and to pass parameters

You can trigger Jenkins builds remotely and to pass parameters by using the following query.

JENKINS_URL/job/job-name/buildWithParameters?token=TOKEN_NAME&param_name1=value&param_name1=value

JENKINS_URL (can be) = https://<your domain name or server address>

TOKE_NAME can be created using configure tab

How do I dump the data of some SQLite3 tables?

You can specify one or more table arguments to the .dump special command, e.g.sqlite3 db ".dump 'table1' 'table2'".

Why should you use strncpy instead of strcpy?

The strncpy() function is the safer one: you have to pass the maximum length the destination buffer can accept. Otherwise it could happen that the source string is not correctly 0 terminated, in which case the strcpy() function could write more characters to destination, corrupting anything which is in the memory after the destination buffer. This is the buffer-overrun problem used in many exploits

Also for POSIX API functions like read() which does not put the terminating 0 in the buffer, but returns the number of bytes read, you will either manually put the 0, or copy it using strncpy().

In your example code, index is actually not an index, but a count - it tells how many characters at most to copy from source to destination. If there is no null byte among the first n bytes of source, the string placed in destination will not be null terminated

Send email using the GMail SMTP server from a PHP page

Set

'auth' => false,

Also, see if port 25 works.

Android set height and width of Custom view programmatically

On Kotlin you can set width and height of any view directly using their virtual properties:

someView.layoutParams.width = 100
someView.layoutParams.height = 200

Split output of command by columns using Bash?

Using array variables

set $(ps | egrep "^11383 "); echo $4

or

A=( $(ps | egrep "^11383 ") ) ; echo ${A[3]}

100% width background image with an 'auto' height

It's 2017, and now you can use object-fit which has decent support. It works in the same way as a div's background-size but on the element itself, and on any element including images.

.your-img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

How to get date, month, year in jQuery UI datepicker?

$("#date").datepicker('getDate').getMonth() + 1; 

The month on the datepicker is 0 based (0-11), so add 1 to get the month as it appears in the date.

How can a file be copied?

open(destination, 'wb').write(open(source, 'rb').read())

Open the source file in read mode, and write to destination file in write mode.

Code line wrapping - how to handle long lines

I think that moving last operator to the beginning of the next line is a good practice. That way you know right away the purpose of the second line, even it doesn't start with an operator. I also recommend 2 indentation spaces (2 tabs) for a previously broken tab, to differ it from the normal indentation. That is immediately visible as continuing previous line. Therefore I suggest this:

private static final Map<Class<? extends Persistent>, PersistentHelper> class2helper 
            = new HashMap<Class<? extends Persistent>, PersistentHelper>();

Python+OpenCV: cv2.imwrite

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

Alternatively, with MTCNN and OpenCV(other dependencies including TensorFlow also required), you can:

1 Perform face detection(Input an image, output all boxes of detected faces):

from mtcnn.mtcnn import MTCNN
import cv2

face_detector = MTCNN()

img = cv2.imread("Anthony_Hopkins_0001.jpg")
detect_boxes = face_detector.detect_faces(img)
print(detect_boxes)

[{'box': [73, 69, 98, 123], 'confidence': 0.9996458292007446, 'keypoints': {'left_eye': (102, 116), 'right_eye': (150, 114), 'nose': (129, 142), 'mouth_left': (112, 168), 'mouth_right': (146, 167)}}]

2 save all detected faces to separate files:

for i in range(len(detect_boxes)):
    box = detect_boxes[i]["box"]
    face_img = img[box[1]:(box[1] + box[3]), box[0]:(box[0] + box[2])]
    cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)

3 or Draw rectangles of all detected faces:

for box in detect_boxes:
    box = box["box"]
    pt1 = (box[0], box[1]) # top left
    pt2 = (box[0] + box[2], box[1] + box[3]) # bottom right
    cv2.rectangle(img, pt1, pt2, (0,255,0), 2)
cv2.imwrite("detected-boxes.jpg", img)

setOnItemClickListener on custom ListView

If in the listener you get the root layout of the item (say itemLayout), and you gave some id's to the textviews, you can then get them with something like itemLayout.findViewById(R.id.textView1).

Simulate a click on 'a' element using javascript/jquery

Using jQuery: $('#gift-close').trigger('click');

Using JavaScript: document.getElementById('gift-close').click();

Remove all git files from a directory?

Unlike other source control systems like SVN or CVS, git stores all of its metadata in a single directory, rather than in every subdirectory of the project. So just delete .git from the root (or use a script like git-export) and you should be fine.

Fatal error: Please read "Security" section of the manual to find out how to run mysqld as root

you might try this if you logged in with root:

mysqld --user=root

Recursively find files with a specific extension

As a script you can use:

find "${2:-.}" -iregex ".*${1:-Robert}\.\(h\|cpp\)$" -print
  • save it as findcc
  • chmod 755 findcc

and use it as

findcc [name] [[search_direcory]]

e.g.

findcc                 # default name 'Robert' and directory .
findcc Joe             # default directory '.'
findcc Joe /somewhere  # no defaults

note you cant use

findcc /some/where    #eg without the name...

also as alternative, you can use

find "$1" -print | grep "$@" 

and

findcc directory grep_options

like

findcc . -P '/Robert\.(h|cpp)$'

jQuery table sort

You can use a jQuery plugin (breedjs) that provides sort, filter and pagination:

HTML:

<table>
  <thead>
    <tr>
      <th sort='name'>Name</th>
      <th>Phone</th>
      <th sort='city'>City</th>
      <th>Speciality</th>
    </tr>
  </thead>
  <tbody>
    <tr b-scope="people" b-loop="person in people">
      <td b-sort="name">{{person.name}}</td>
      <td>{{person.phone}}</td>
      <td b-sort="city">{{person.city}}</td>
      <td>{{person.speciality}}</td>
    </tr>
  </tbody>
</table>

JS:

$(function(){
  var data = {
    people: [
      {name: 'c', phone: 123, city: 'b', speciality: 'a'},
      {name: 'b', phone: 345, city: 'a', speciality: 'c'},
      {name: 'a', phone: 234, city: 'c', speciality: 'b'},
    ]
  };
  breed.run({
    scope: 'people',
    input: data
  });
  $("th[sort]").click(function(){
    breed.sort({
      scope: 'people',
      selector: $(this).attr('sort')
    });
  });
});

Working example on fiddle

How might I find the largest number contained in a JavaScript array?

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max

_x000D_
_x000D_
const inputArray = [ 1, 3, 4, 9, 16, 2, 20, 18];_x000D_
const maxNumber = Math.max(...inputArray);_x000D_
console.log(maxNumber);
_x000D_
_x000D_
_x000D_

Python: pandas merge multiple dataframes

Thank you for your help @jezrael, @zipa and @everestial007, both answers are what I need. If I wanted to make a recursive, this would also work as intended:

def mergefiles(dfs=[], on=''):
    """Merge a list of files based on one column"""
    if len(dfs) == 1:
         return "List only have one element."

    elif len(dfs) == 2:
        df1 = dfs[0]
        df2 = dfs[1]
        df = df1.merge(df2, on=on)
        return df

    # Merge the first and second datafranes into new dataframe
    df1 = dfs[0]
    df2 = dfs[1]
    df = dfs[0].merge(dfs[1], on=on)

    # Create new list with merged dataframe
    dfl = []
    dfl.append(df)

    # Join lists
    dfl = dfl + dfs[2:] 
    dfm = mergefiles(dfl, on)
    return dfm

What is the best way to call a script from another script?

Add this to your python script.

import os
os.system("exec /path/to/another/script")

This executes that command as if it were typed into the shell.

How to flush output of print function?

On Python 3, print can take an optional flush argument

print("Hello world!", flush=True)

On Python 2 you'll have to do

import sys
sys.stdout.flush()

after calling print. By default, print prints to sys.stdout (see the documentation for more about file objects).

open() in Python does not create a file if it doesn't exist

If you want to open it to read and write, I'm assuming you don't want to truncate it as you open it and you want to be able to read the file right after opening it. So this is the solution I'm using:

file = open('myfile.dat', 'a+')
file.seek(0, 0)

Adding a library/JAR to an Eclipse Android project

Error parsing XML: unbound prefix

Resource '/playteddy/res' does not exist.

I got the above two errors and finally I solved it.

Right click your project -> properties -> java build path -> googleadmobadsdk (select and put it top), then you run and problem solved. It is solved my runtime error.

In plain English, what does "git reset" do?

Checkout points the head at a specific commit.

Reset points a branch at a specific commit. (A branch is a pointer to a commit.)

Incidentally, if your head doesn’t point to a commit that’s also pointed to by a branch then you have a detached head. (turned out to be wrong. See comments...)

What is a C++ delegate?

The need for C++ delegate implementations are a long lasting embarassment to the C++ community. Every C++ programmer would love to have them, so they eventually use them despite the facts that:

  1. std::function() uses heap operations (and is out of reach for serious embedded programming).

  2. All other implementations make concessions towards either portability or standard conformity to larger or lesser degrees (please verify by inspecting the various delegate implementations here and on codeproject). I have yet to see an implementation which does not use wild reinterpret_casts, Nested class "prototypes" which hopefully produce function pointers of the same size as the one passed in by the user, compiler tricks like first forward declare, then typedef then declare again, this time inheriting from another class or similar shady techniques. While it is a great accomplishment for the implementers who built that, it is still a sad testimoney on how C++ evolves.

  3. Only rarely is it pointed out, that now over 3 C++ standard revisions, delegates were not properly addressed. (Or the lack of language features which allow for straightforward delegate implementations.)

  4. With the way C++11 lambda functions are defined by the standard (each lambda has anonymous, different type), the situation has only improved in some use cases. But for the use case of using delegates in (DLL) library APIs, lambdas alone are still not usable. The common technique here, is to first pack the lambda into a std::function and then pass it across the API.

Proper way to rename solution (and directories) in Visual Studio

Manually edit .sln file

This method is entirely aimed at renaming the directory for the project, as viewed in Windows Explorer.

This method does not suffer from the problems in the Remove/add project file method below (references disappearing), but it can result in problems if your project is under source control (see notes below). This is why step 2 (backup) is so important.

  1. Close Visual Studio.
  2. Create a backup of your .sln file (you can always roll back).
  3. Imagine you want to rename directory Project1 to Project2.
  4. If not using source control, rename the folder from Project1 to Project2 using Windows Explorer.
  5. If using source control, rename the folder from Project1 to Project2 using the functions supplied by source control. This preserves the history of the file. For example, with TortoiseSVN, right click on the file, select TortoiseSVN .. Rename.
  6. In the .sln file, edit all instances of Project1 to be Project2, using a text editor like NotePad.
  7. Restart Visual Studio, and everything will work as before, but with the project in a different directory.

You can also see renaming solution manually or post which describes this manual process.

Advantages

  • You can make the directory within Windows Explorer match the project name within the solution.
  • This method does not remove any references from other projects to this file (an advantage over the Remove/add project file method, see my other answer below).

Warnings

  • It's important to back everything up into a .zip file before renaming anything, as this method can create issues with source control.
  • If your project is under source control, it may create issues if you rename files or directories outside of source control (using Windows Explorer). Its preferable to rename the file using the source control framework itself, if you can, to preserve the history of that file (check out the context menu on a right click - it may have a function to rename the file).

Update 2014-11-02

ReSharper has added an automated method for achieving the same result as the manual method above. If the namespace is underlined with a squiggly blue line, click on the action pyramid icon to either:

  • Rename the namespace to match the directory name in Windows Explorer, or;
  • Rename the directory in Windows Explorer to match the namespace.

In the second case, the final word defines the new directory name in Windows Explorer, e.g. if we changed the namespace to ViewModel2, it would offer to move the file to folder ViewModel2.

However, this will not necessarily update files in source control, so you may still have to use the manual method.

enter image description here

Update 2018-01-31

Tested with Visual Studio 2008, 2010, 2012, 2013, 2015, 2017 Update 1, 2, 3, 4, 5.

Update 2020-05-02

Tested with Visual Studio 2019.

Difference between x86, x32, and x64 architectures?

As the 64bit version is an x86 architecture and was accordingly first called x86-64, that would be the most appropriate name, IMO. Also, x32 is a thing (as mentioned before)—‘x64’, however, is not a continuation of that, so is (theoretically) missleading (even though many people will know what you are talking about) and should thus only be recognised as a marketing thing, not an ‘official’ architecture (again, IMO–obviously, others disagree).

How to extract numbers from a string and get an array of ints?

  StringBuffer sBuffer = new StringBuffer();
  Pattern p = Pattern.compile("[0-9]+.[0-9]*|[0-9]*.[0-9]+|[0-9]+");
  Matcher m = p.matcher(str);
  while (m.find()) {
    sBuffer.append(m.group());
  }
  return sBuffer.toString();

This is for extracting numbers retaining the decimal

How to parse JSON Array (Not Json Object) in Android

Create a POJO Java Class for the objects in the list like so:

class NameUrlClass{
       private String name;
       private String url;
       //Constructor
       public NameUrlClass(String name,String url){
              this.name = name;
              this.url = url; 
        }
}

Now simply create a List of NameUrlClass and initialize it to an ArrayList like so:

List<NameUrlClass> obj = new ArrayList<NameUrlClass>;

You can use store the JSON array in this object

obj = JSONArray;//[{"name":"name1","url":"url1"}{"name":"name2","url":"url2"},...]

PG::ConnectionBad - could not connect to server: Connection refused

I had the same problem. I Check the last line of PostgreSQL log files in /var/log/postgresql. There was an unrecognized configuration parameter in file /etc/postgresql/9.5/main/postgresql.conf. Commenting the error line in postgresql.conf resolved my problem.

is there a require for json in node.js

As of node v0.5.x yes you can require your JSON just as you would require a js file.

var someObject = require('./somefile.json')

In ES6:

import someObject from ('./somefile.json')

Regex that accepts only numbers (0-9) and NO characters

Your regex ^[0-9] matches anything beginning with a digit, including strings like "1A". To avoid a partial match, append a $ to the end:

^[0-9]*$

This accepts any number of digits, including none. To accept one or more digits, change the * to +. To accept exactly one digit, just remove the *.

UPDATE: You mixed up the arguments to IsMatch. The pattern should be the second argument, not the first:

if (!System.Text.RegularExpressions.Regex.IsMatch(textbox.Text, "^[0-9]*$"))

CAUTION: In JavaScript, \d is equivalent to [0-9], but in .NET, \d by default matches any Unicode decimal digit, including exotic fare like ? (Myanmar 2) and ? (N'Ko 9). Unless your app is prepared to deal with these characters, stick with [0-9] (or supply the RegexOptions.ECMAScript flag).

How can I extract embedded fonts from a PDF as valid font files?

Even though this question is 10 years old, it is still valid and as technology changes so does a valid answer.

In searching the current answers noticed none of them note WOFF (Web Open Font Format) (W3C) (Wikipedia) which can be used to recreate the individual characters (glyphs) and display them in a web page accurately.

Using the free online web page by IDR Solutions, PDF to HTML5 (link), convert a PDF to a zip file. In the resulting zip will be a font directory of woff file types. Current Internet browsers support woff files if you were not aware. (reference) These can be examined at the online site FontDrop! (link).

WOFF files can be converted to/from OTF or TTF at WOFFer – WOFF font converter

Also the zip file from PDF to HTML5 will contain an HTML file for each page of the PDF that can be opened in an Internet browser and is one of the best and most accurate PDF translations I have found or seen.

While I am just learning how to use WOFF files, this is worth passing along. Enjoy.

PS, I will probably update with more info as I learn more about using woff file types, but as this is creative commons, feel free to edit this answer if you have something of value to pass along.

Pushing value of Var into an Array

.val() does not return an array from a DOM element: $('#fruit') is going to find the element in the document with an ID of #fruit and get its value (if it has a value).

Access-Control-Allow-Origin Multiple Origin Domains?

Below answer is specific to C#, but the concept should be applicable to all the different platforms.

To allow Cross Origin Requests from a web api, You need to allow Option requests to your Application and Add below annotation at controller level.

[EnableCors(UrlString,Header, Method)] Now the origins can be passed only a s string. SO if you want to pass more than one URL in the request pass it as a comma seperated value.

UrlString = "https://a.hello.com,https://b.hello.com"

CMake does not find Visual C++ compiler

I had a similar problem with the Visual Studio 2017 project generated through CMake. Some of the packages were missing while installing Visual Studio in Desktop development with C++. See snapshot:

Visual Studio 2017 Packages:

Visual Studio2017 Packages

Also, upgrade CMake to the latest version.

<select> HTML element with height

I've used a few CSS hacks and targeted Chrome/Safari/Firefox/IE individually, as each browser renders selects a bit differently. I've tested on all browsers except IE.

For Safari/Chrome, set the height and line-height you want for your <select />.

For Firefox, we're going to kill Firefox's default padding and border, then set our own. Set padding to whatever you like.

For IE 8+, just like Chrome, we've set the height and line-height properties. These two media queries can be combined. But I kept it separate for demo purposes. So you can see what I'm doing.

Please note, for the height/line-height property to work in Chrome/Safari OSX, you must set the background to a custom value. I changed the color in my example.

Here's a jsFiddle of the below: http://jsfiddle.net/URgCB/4/

For the non-hack route, why not use a custom select plug-in via jQuery? Check out this: http://codepen.io/wallaceerick/pen/ctsCz

HTML:

<select>
    <option>Here's one option</option>
    <option>here's another option</option>
</select>

CSS:

@media screen and (-webkit-min-device-pixel-ratio:0) {  /*safari and chrome*/
    select {
        height:30px;
        line-height:30px;
        background:#f4f4f4;
    } 
}
select::-moz-focus-inner { /*Remove button padding in FF*/ 
    border: 0;
    padding: 0;
}
@-moz-document url-prefix() { /* targets Firefox only */
    select {
        padding: 15px 0!important;
    }
}        
@media screen\0 { /* IE Hacks: targets IE 8, 9 and 10 */        
    select {
        height:30px;
        line-height:30px;
    }     
}

getActionBar() returns null

Use getSupportActionBar() instead of getActionBar()

Calculate relative time in C#

you can try this.I think it will work correctly.

long delta = new Date().getTime() - date.getTime();
const int SECOND = 1;
const int MINUTE = 60 * SECOND;
const int HOUR = 60 * MINUTE;
const int DAY = 24 * HOUR;
const int MONTH = 30 * DAY;

if (delta < 0L)
{
  return "not yet";
}
if (delta < 1L * MINUTE)
{
  return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago";
}
if (delta < 2L * MINUTE)
{
  return "a minute ago";
}
if (delta < 45L * MINUTE)
{
  return ts.Minutes + " minutes ago";
}
if (delta < 90L * MINUTE)
{
  return "an hour ago";
}
if (delta < 24L * HOUR)
{
  return ts.Hours + " hours ago";
}
if (delta < 48L * HOUR)
{
  return "yesterday";
}
if (delta < 30L * DAY)
{
  return ts.Days + " days ago";
}
if (delta < 12L * MONTH)
{
  int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));
  return months <= 1 ? "one month ago" : months + " months ago";
}
else
{
  int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));
  return years <= 1 ? "one year ago" : years + " years ago";
}

CSS Box Shadow Bottom Only

Try this

-moz-box-shadow:0 5px 5px rgba(182, 182, 182, 0.75);
-webkit-box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);
box-shadow: 0 5px 5px rgba(182, 182, 182, 0.75);

You can see it in http://jsfiddle.net/wJ7qp/

Scrollview vertical and horizontal in android

Since this seems to be the first search result in Google for "Android vertical+horizontal ScrollView", I thought I should add this here. Matt Clark has built a custom view based on the Android source, and it seems to work perfectly: Two Dimensional ScrollView

Beware that the class in that page has a bug calculating the view's horizonal width. A fix by Manuel Hilty is in the comments:

Solution: Replace the statement on line 808 by the following:

final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED);


Edit: The Link doesn't work anymore but here is a link to an old version of the blogpost.

How can I control the speed that bootstrap carousel slides in items?

You need to set interval in the main DIV as data-interval tag. The it will work fine and you can give different time to different slides.

<div class="carousel" data-interval="5000">

MySQL, update multiple tables with one query

Let's say I have Table1 with primary key _id and a boolean column doc_availability; Table2 with foreign key _id and DateTime column last_update and I want to change the availability of a document with _id 14 in Table1 to 0 i.e unavailable and update Table2 with the timestamp when the document was last updated. The following query would do the task:

UPDATE Table1, Table2 
SET doc_availability = 0, last_update = NOW() 
WHERE Table1._id = Table2._id AND Table1._id = 14

Nginx 403 forbidden for all files

Old question, but I had the same issue. I tried every answer above, nothing worked. What fixed it for me though was removing the domain, and adding it again. I'm using Plesk, and I installed Nginx AFTER the domain was already there.

Did a local backup to /var/www/backups first though. So I could easily copy back the files.

Strange problem....

How to get names of enum entries?

It seems that none of the answers here will work with string-enums in strict-mode.

Consider enum as:

enum AnimalEnum {
  dog = "dog", cat = "cat", mouse = "mouse"
}

Accessing this with AnimalEnum["dog"] may result in an error like:

Element implicitly has an 'any' type because expression of type 'any' can't be used to index type 'typeof AnimalEnum'.ts(7053).

Proper solution for that case, write it as:

AnimalEnum["dog" as keyof typeof AnimalEnum]

How to find longest string in the table column data

If column datatype is text you should use DataLength function like:

select top 1 CR, DataLength(CR)
from tbl
order by DataLength(CR) desc

HTML Button : Navigate to Other Page - Different Approaches

I use method 3 because it's the most understandable for others (whenever you see an <a> tag, you know it's a link) and when you are part of a team, you have to make simple things ;).

And finally I don't think it's useful and efficient to use JS simply to navigate to an other page.

Why does JSON.parse fail with the empty string?

Because '' is not a valid Javascript/JSON object. An empty object would be '{}'

For reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

What's the quickest way to multiply multiple cells by another number?

As one of the answers above says: " then drag the formula fill handle." This KEY feature is not mentioned in MS's explanation, nor in others here. I spent over an hour trying to follow the various instructions, to no avail. This is because you have to click and hold near the bottom of the cell just right (and at least on my computer that is not at all easy) so that a sort of "handle" appears. Once you're luck enough to get that, then carefully slide ["drag"] your cursor down to the lowermost of the cells you want to be multiplied by the constant. The products should show up in each cell as you move down. Just dragging down will give you only the answer in the first cell and a lot of white space.

Node.js heap out of memory

For other beginners like me, who didn't find any suitable solution for this error, check the node version installed (x32, x64, x86). I have a 64-bit CPU and I've installed x86 node version, which caused the CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory error.

How to set array length in c# dynamically

Use this:

 Array.Resize(ref myArr, myArr.Length + 5);

Spring Boot - Handle to Hibernate SessionFactory

SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);

where entityManagerFactory is an JPA EntityManagerFactory.

Try reinstalling `node-sass` on node 0.12?

I ran into this error using node 0.12.0 and it was fixed by deleting the existing /node_modules directory and running npm update.

Error: Uncaught SyntaxError: Unexpected token <

It usually works when you change the directory name, where the file is. It worked for me when I moved it from "js/" to "../js"

How do I make a WinForms app go Full Screen

You can use the following code to fit your system screen and task bar is visible.

    private void Form1_Load(object sender, EventArgs e)
    {   
        // hide max,min and close button at top right of Window
        this.FormBorderStyle = FormBorderStyle.None;
        // fill the screen
        this.Bounds = Screen.PrimaryScreen.Bounds;
    }

No need to use:

    this.TopMost = true;

That line interferes with alt+tab to switch to other application. ("TopMost" means the window stays on top of other windows, unless they are also marked "TopMost".)

Finding the position of bottom of a div with jquery

var bottom = $('#bottom').position().top + $('#bottom').height();

"Can't find Project or Library" for standard VBA functions

I found references to an AVAYA/CMS programme file? Totally random, this was in MS Access, nothing to do with AVAYA. I do have AVAYA on my PC, and others don't, so this explains why it worked on my machine and not others - but not how Access got linked to AVAYA. Anyway - I just unchecked the reference and that seems to have fixed the problem

Get WooCommerce product categories from WordPress

Improving Suman.hassan95's answer by adding a link to subcategory as well. Replace the following code:

$sub_cats = get_categories( $args2 );
    if($sub_cats) {
        foreach($sub_cats as $sub_category) {
            echo  $sub_category->name ;
        }

    }

with:

$sub_cats = get_categories( $args2 );
            if($sub_cats) {
                foreach($sub_cats as $sub_category) {
                    echo  '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
                }
            }

or if you also wish a counter for each subcategory, replace with this:

$sub_cats = get_categories( $args2 );
            if($sub_cats) {
                foreach($sub_cats as $sub_category) {
                    echo  '<br/><a href="'. get_term_link($sub_category->slug, 'product_cat') .'">'. $sub_category->name .'</a>';
                    echo apply_filters( 'woocommerce_subcategory_count_html', ' <span class="cat-count">' . $sub_category->count . '</span>', $category );
                }
            }

Twitter Bootstrap Form File Element Upload Button

enter image description here

The following code makes as above the picture

Html

<form>
<div class="row">
<div class="col-lg-6">
<label for="file">
<div class="input-group">
<span class="input-group-btn">
<button class="btn btn-default" type="button">Browse</button>
</span>
<input type="text" class="form-control" id="info" readonly="" style="background: #fff;" placeholder="Search for...">
</div><!-- /input-group -->
</label>
</div><!-- /.col-lg-6 -->
</div>

</div>
<input type="file" style="display: none;" onchange="$('#info').val($(this).val().split(/[\\|/]/).pop()); " name="file" id="file">
</form>

Javascript

<script type="text/javascript">

$(function() {
    $("label[for=file]").click(function(event) {
        event.preventDefault();
        $("#file").click();
    });
});

</script>

How to change the pop-up position of the jQuery DatePicker control

A very simple jquery function.

$(".datepicker").focus(function(event){
                var dim = $(this).offset();
                $("#ui-datepicker-div").offset({
                    top     :   dim.top - 180,
                    left    :   dim.left + 150
                });
            });

How to get the HTML for a DOM element in javascript

You'll want something like this for it to be cross browser.

function OuterHTML(element) {
    var container = document.createElement("div");
    container.appendChild(element.cloneNode(true));

    return container.innerHTML;
}

How to convert entire dataframe to numeric while preserving decimals?

> df2 <- data.frame(sapply(df1, function(x) as.numeric(as.character(x))))
> df2
     a b
1 0.01 2
2 0.02 4
3 0.03 5
4 0.04 7
> sapply(df2, class)
        a         b 
"numeric" "numeric" 

xsl: how to split strings?

I. Plain XSLT 1.0 solution:

This transformation:

<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="text()" name="split">
  <xsl:param name="pText" select="."/>
  <xsl:if test="string-length($pText)">
   <xsl:if test="not($pText=.)">
    <br />
   </xsl:if>
   <xsl:value-of select=
    "substring-before(concat($pText,';'),';')"/>
   <xsl:call-template name="split">
    <xsl:with-param name="pText" select=
     "substring-after($pText, ';')"/>
   </xsl:call-template>
  </xsl:if>
 </xsl:template>
</xsl:stylesheet>

when applied on this XML document:

<t>123 Elm Street;PO Box 222;c/o James Jones</t>

produces the wanted, corrected result:

123 Elm Street<br />PO Box 222<br />c/o James Jones

II. FXSL 1 (for XSLT 1.0):

Here we just use the FXSL template str-map (and do not have to write recursive template for the 999th time):

<xsl:stylesheet version="1.0" 
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:f="http://fxsl.sf.net/"
xmlns:testmap="testmap"
exclude-result-prefixes="xsl f testmap"
>
   <xsl:import href="str-dvc-map.xsl"/>

   <testmap:testmap/>

   <xsl:output omit-xml-declaration="yes" indent="yes"/>

   <xsl:template match="/">
     <xsl:variable name="vTestMap" select="document('')/*/testmap:*[1]"/>
     <xsl:call-template name="str-map">
       <xsl:with-param name="pFun" select="$vTestMap"/>
       <xsl:with-param name="pStr" select=
       "'123 Elm Street;PO Box 222;c/o James Jones'"/>
     </xsl:call-template>
   </xsl:template>

    <xsl:template name="replace" mode="f:FXSL"
         match="*[namespace-uri() = 'testmap']">
      <xsl:param name="arg1"/>

      <xsl:choose>
       <xsl:when test="not($arg1=';')">
        <xsl:value-of select="$arg1"/>
       </xsl:when>
       <xsl:otherwise><br /></xsl:otherwise>
      </xsl:choose>
    </xsl:template>
</xsl:stylesheet>

when this transformation is applied on any XML document (not used), the same, wanted correct result is produced:

123 Elm Street<br/>PO Box 222<br/>c/o James Jones

III. Using XSLT 2.0

<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="text()">
  <xsl:for-each select="tokenize(.,';')">
   <xsl:sequence select="."/>
   <xsl:if test="not(position() eq last())"><br /></xsl:if>
  </xsl:for-each>
 </xsl:template>
</xsl:stylesheet>

when this transformation is applied on this XML document:

<t>123 Elm Street;PO Box 222;c/o James Jones</t>

the wanted, correct result is produced:

123 Elm Street<br />PO Box 222<br />c/o James Jones

Pass a String from one Activity to another Activity in Android

In activity1

    String easyPuzzle  = "630208010200050089109060030"+
                 "008006050000187000060500900"+
                 "09007010681002000502003097";

    Intent i = new Intent (this, activity2.class);

    i.putExtra("puzzle", easyPuzzle);
    startActivity(i);

In activity2

    Intent i = getIntent();
    String easyPuzzle = i.getStringExtra("puzzle");

Group by & count function in sqlalchemy

The documentation on counting says that for group_by queries it is better to use func.count():

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

submit the form using ajax

Nobody has actually given a pure javascript answer (as requested by OP), so here it is:

function postAsync(url2get, sendstr)    {
    var req;
    if (window.XMLHttpRequest) {
        req = new XMLHttpRequest();
        } else if (window.ActiveXObject) {
        req = new ActiveXObject("Microsoft.XMLHTTP");
        }
    if (req != undefined) {
        // req.overrideMimeType("application/json"); // if request result is JSON
        try {
            req.open("POST", url2get, false); // 3rd param is whether "async"
            }
        catch(err) {
            alert("couldnt complete request. Is JS enabled for that domain?\\n\\n" + err.message);
            return false;
            }
        req.send(sendstr); // param string only used for POST

        if (req.readyState == 4) { // only if req is "loaded"
            if (req.status == 200)  // only if "OK"
                { return req.responseText ; }
            else    { return "XHR error: " + req.status +" "+req.statusText; }
            }
        }
    alert("req for getAsync is undefined");
}

var var_str = "var1=" + var1  + "&var2=" + var2;
var ret = postAsync(url, var_str) ;
    // hint: encodeURIComponent()

if (ret.match(/^XHR error/)) {
    console.log(ret);
    return;
    }

In your case:

var var_str = "video_time=" + document.getElementById('video_time').value 
     + "&video_id=" + document.getElementById('video_id').value;

Is it possible to get an Excel document's row count without loading the entire document into memory?

https://pythonhosted.org/pyexcel/iapi/pyexcel.sheets.Sheet.html see : row_range() Utility function to get row range

if you use pyexcel, can call row_range get max rows.

python 3.4 test pass.

Passing ArrayList through Intent

    public class StructMain implements Serializable {
    public  int id;
    public String name;
    public String lastName;
}

this my item . implement Serializable and create ArrayList

ArrayList<StructMain> items =new ArrayList<>();

and put in Bundle

Bundle bundle=new Bundle();
bundle.putSerializable("test",items);

and create a new Intent that put Bundle to Intent

Intent intent=new Intent(ActivityOne.this,ActivityTwo.class);
intent.putExtras(bundle);
startActivity(intent);

for receive bundle insert this code

Bundle bundle = getIntent().getExtras();
ArrayList<StructMain> item = (ArrayList<StructMain>) bundle.getSerializable("test");

Swift add icon/image in UITextField

I created a simple IBDesignable. Use it however u like. Just make your UITextField confirm to this class.

import UIKit

@IBDesignable
class RoundTextField : UITextField {
    @IBInspectable var cornerRadius : CGFloat = 0{
        didSet{
            layer.cornerRadius = cornerRadius
            layer.masksToBounds = cornerRadius > 0
        }
    }

    @IBInspectable var borderWidth : CGFloat = 0 {
        didSet{
            layer.borderWidth = borderWidth
        }
    }

    @IBInspectable var borderColor : UIColor? {
        didSet {
            layer.borderColor = borderColor?.cgColor
        }
    }

    @IBInspectable var bgColor : UIColor? {
        didSet {
            backgroundColor = bgColor
        }
    }

    @IBInspectable var leftImage : UIImage? {
        didSet {
            if let image = leftImage{
                leftViewMode = .always
                let imageView = UIImageView(frame: CGRect(x: 20, y: 0, width: 20, height: 20))
                imageView.image = image
                imageView.tintColor = tintColor
                let view = UIView(frame : CGRect(x: 0, y: 0, width: 25, height: 20))
                view.addSubview(imageView)
                leftView = view
            }else {
                leftViewMode = .never
            }

        }
    }

    @IBInspectable var placeholderColor : UIColor? {
        didSet {
            let rawString = attributedPlaceholder?.string != nil ? attributedPlaceholder!.string : ""
            let str = NSAttributedString(string: rawString, attributes: [NSForegroundColorAttributeName : placeholderColor!])
            attributedPlaceholder = str
        }
    }

    override func textRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: 50, dy: 5)
    }

    override func editingRect(forBounds bounds: CGRect) -> CGRect {
        return bounds.insetBy(dx: 50, dy: 5)
    }

}

Bootstrap modal: close current, open new

By using the following code you can hide first modal and immediately open second modal, by using same strategy you can hide second modal and show the first one.

$("#buttonId").on("click", function(){
    $("#currentModalId").modal("hide");
    $("#currentModalId").on("hidden.bs.modal",function(){
    $("#newModalId").modal("show");
    });
});

Create sequence of repeated values, in sequence?

You missed the each= argument to rep():

R> n <- 3
R> rep(1:5, each=n)
 [1] 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5
R> 

so your example can be done with a simple

R> rep(1:8, each=20)

Border length smaller than div width?

I did something like this in my project. I would like to share it here. You can add another div as a child and give it a border with small width and place it left, centre or right with usual CSS

HTML code:

    <div>
        content 
        <div class ="ac-brdr"></div>
    </div>

CSS as below:

   .active {
    color: magneta;
  }
   .active .ac-brdr {
        width: 20px;
        margin: 0 auto;
        border-bottom: 1px solid magneta;
  }

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

I've never actually used this, but try view.getClass().getGenericSuperclass()

Failed to load resource under Chrome

I recently ran into this problem and discovered that it was caused by the "Adblock" extension (my best guess is that it's because I had the words "banner" and "ad" in the filename).

As a quick test to see if that's your problem, start Chrome in incognito mode with extensions disabled (ctrl+shift+n) and see if your page works now. Note that by default all extensions will be already disabled in incognito mode unless you've specifically set them to run (via chrome://extensions).

Mod in Java produces negative numbers

The problem here is that in Python the % operator returns the modulus and in Java it returns the remainder. These functions give the same values for positive arguments, but the modulus always returns positive results for negative input, whereas the remainder may give negative results. There's some more information about it in this question.

You can find the positive value by doing this:

int i = (((-1 % 2) + 2) % 2)

or this:

int i = -1 % 2;
if (i<0) i += 2;

(obviously -1 or 2 can be whatever you want the numerator or denominator to be)

How do I create sql query for searching partial matches?

This may work as well.

SELECT * 
FROM myTable
WHERE CHARINDEX('mall', name) > 0
  OR CHARINDEX('mall', description) > 0

jackson deserialization json to java-objects

You have to change the line

product userFromJSON = mapper.readValue(userDataJSON, product.class);

to

product[] userFromJSON = mapper.readValue(userDataJSON, product[].class);

since you are deserializing an array (btw: you should start your class names with upper case letters as mentioned earlier). Additionally you have to create setter methods for your fields or mark them as public in order to make this work.

Edit: You can also go with Steven Schlansker's suggestion and use

List<product> userFromJSON =
        mapper.readValue(userDataJSON, new TypeReference<List<product>>() {});

instead if you want to avoid arrays.

Use jQuery to scroll to the bottom of a div with lots of text

No need to calculate the actual height of the contents; you can just scroll down a lot:

$(function () {
  $('.messageScrollArea').scrollTop(1E10);
});

Remove substring from the string

How about str.gsub("subString", "") Check out the Ruby Doc

ORACLE: Updating multiple columns at once

I guess the issue here is that you are updating INV_DISCOUNT and the INV_TOTAL uses the INV_DISCOUNT. so that is the issue here. You can use returning clause of update statement to use the new INV_DISCOUNT and use it to update INV_TOTAL.

this is a generic example let me know if this explains the point i mentioned

CREATE OR REPLACE PROCEDURE SingleRowUpdateReturn
IS
    empName VARCHAR2(50);
    empSalary NUMBER(7,2);      
BEGIN
    UPDATE emp
    SET sal = sal + 1000
    WHERE empno = 7499
    RETURNING ename, sal
    INTO empName, empSalary;

    DBMS_OUTPUT.put_line('Name of Employee: ' || empName);
    DBMS_OUTPUT.put_line('New Salary: ' || empSalary);
END;

Is key-value observation (KVO) available in Swift?

Currently Swift does not support any built in mechanism for observing property changes of objects other than 'self', so no, it does not support KVO.

However, KVO is such a fundamental part of Objective-C and Cocoa that it seems quite likely that it will be added in the future. The current documentation seems to imply this:

Key-Value Observing

Information forthcoming.

Using Swift with Cocoa and Objective-C

How to install python developer package?

If you use yum search you can find the python dev package for your version of python.

For me I was using python 3.5. I ran the following

yum search python | grep devel

Which returned the following

enter image description here

I was then able to install the correct package for my version of python with the following cmd.

sudo yum install python35u-devel.x86_64

This works on centos for ubuntu or debian you would need to use apt-get

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

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

foo.in_groups_of(3)

Correct way to try/except using Python requests module?

One additional suggestion to be explicit. It seems best to go from specific to general down the stack of errors to get the desired error to be caught, so the specific ones don't get masked by the general one.

url='http://www.google.com/blahblah'

try:
    r = requests.get(url,timeout=3)
    r.raise_for_status()
except requests.exceptions.HTTPError as errh:
    print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
    print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
    print ("Timeout Error:",errt)
except requests.exceptions.RequestException as err:
    print ("OOps: Something Else",err)

Http Error: 404 Client Error: Not Found for url: http://www.google.com/blahblah

vs

url='http://www.google.com/blahblah'

try:
    r = requests.get(url,timeout=3)
    r.raise_for_status()
except requests.exceptions.RequestException as err:
    print ("OOps: Something Else",err)
except requests.exceptions.HTTPError as errh:
    print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
    print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
    print ("Timeout Error:",errt)     

OOps: Something Else 404 Client Error: Not Found for url: http://www.google.com/blahblah

How to connect to a remote MySQL database with Java?

Close all the connection which is open & connected to the server listen port, whatever it is from application or client side tool (navicat) or on running server (apache or weblogic). First close all connection then restart all tools MySQL,apache etc.

Last executed queries for a specific database

This works for me to find queries on any database in the instance. I'm sysadmin on the instance (check your privileges):

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This is the same answer that Aaron Bertrand provided but it wasn't placed in an answer.

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

For me the solution was besides using "Ntlm" as credential type:

    XxxSoapClient xxxClient = new XxxSoapClient();
    ApplyCredentials(userName, password, xxxClient.ClientCredentials);

    private static void ApplyCredentials(string userName, string password, ClientCredentials clientCredentials)
    {
        clientCredentials.UserName.UserName = userName;
        clientCredentials.UserName.Password = password;
        clientCredentials.Windows.ClientCredential.UserName = userName;
        clientCredentials.Windows.ClientCredential.Password = password;
        clientCredentials.Windows.AllowNtlm = true;
        clientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;
    }  

Posting a File and Associated Data to a RESTful WebService preferably as JSON

Please ensure that you have following import. Ofcourse other standard imports

import org.springframework.core.io.FileSystemResource


    void uploadzipFiles(String token) {

        RestBuilder rest = new RestBuilder(connectTimeout:10000, readTimeout:20000)

        def zipFile = new File("testdata.zip")
        def Id = "001G00000"
        MultiValueMap<String, String> form = new LinkedMultiValueMap<String, String>()
        form.add("id", id)
        form.add('file',new FileSystemResource(zipFile))
        def urld ='''http://URL''';
        def resp = rest.post(urld) {
            header('X-Auth-Token', clientSecret)
            contentType "multipart/form-data"
            body(form)
        }
        println "resp::"+resp
        println "resp::"+resp.text
        println "resp::"+resp.headers
        println "resp::"+resp.body
        println "resp::"+resp.status
    }

How to run JUnit test cases from the command line

Personally I would use the Maven surefire JUnit runner to do that.

Run text file as commands in Bash

Execute

. example.txt

That does exactly what you ask for, without setting an executable flag on the file or running an extra bash instance.

For a detailed explanation see e.g. https://unix.stackexchange.com/questions/43882/what-is-the-difference-between-sourcing-or-source-and-executing-a-file-i

Classes vs. Functions

I'm going to break from the herd on this one and provide an alternate point of view:

Never create classes.

Reliance on classes has a significant tendency to cause coders to create bloated and slow code. Classes getting passed around (since they're objects) take a lot more computational power than calling a function and passing a string or two. Proper naming conventions on functions can do pretty much everything creating a class can do, and with only a fraction of the overhead and better code readability.

That doesn't mean you shouldn't learn to understand classes though. If you're coding with others, people will use them all the time and you'll need to know how to juggle those classes. Writing your code to rely on functions means the code will be smaller, faster, and more readable. I've seen huge sites written using only functions that were snappy and quick, and I've seen tiny sites that had minimal functionality that relied heavily on classes and broke constantly. (When you have classes extending classes that contain classes as part of their classes, you know you've lost all semblance of easy maintainability.)

When it comes down to it, all data you're going to want to pass can easily be handled by the existing datatypes.

Classes were created as a mental crutch and provide no actual extra functionality, and the overly-complicated code they have a tendency to create defeats the point of that crutch in the long run.

How to insert a new line in Linux shell script?

echo $'Create the snapshots\nSnapshot created\n'

Finish all activities at a time

Following two flags worked for me. They will clear all the previous activities and start a new one

  Intent intent = new Intent(getApplicationContext(), MyDetails.class);
  intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(intent);

Hope this helps.

Adding an onclick event to a table row

Something like this.

function addRowHandlers() {
  var table = document.getElementById("tableId");
  var rows = table.getElementsByTagName("tr");
  for (i = 0; i < rows.length; i++) {
    var currentRow = table.rows[i];
    var createClickHandler = function(row) {
      return function() {
        var cell = row.getElementsByTagName("td")[0];
        var id = cell.innerHTML;
        alert("id:" + id);
      };
    };
    currentRow.onclick = createClickHandler(currentRow);
  }
}

EDIT

Working demo.

How can I add an image file into json object?

You're only adding the File object to the JSON object. The File object only contains meta information about the file: Path, name and so on.

You must load the image and read the bytes from it. Then put these bytes into the JSON object.

How to properly reference local resources in HTML?

  • A leading slash tells the browser to start at the root directory.
  • If you don't have the leading slash, you're referencing from the current directory.
  • If you add two dots before the leading slash, it means you're referencing the parent of the current directory.

Take the following folder structure

demo folder structure

notice:

  • the ROOT checkmark is green,
  • the second checkmark is orange,
  • the third checkmark is purple,
  • the forth checkmark is yellow

Now in the index.html.en file you'll want to put the following markup

<p>
    <span>src="check_mark.png"</span>
    <img src="check_mark.png" />
    <span>I'm purple because I'm referenced from this current directory</span>
</p>

<p>
    <span>src="/check_mark.png"</span>
    <img src="/check_mark.png" />
    <span>I'm green because I'm referenced from the ROOT directory</span>
</p>

<p>
    <span>src="subfolder/check_mark.png"</span>
    <img src="subfolder/check_mark.png" />
    <span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>

<p>
    <span>src="/subfolder/check_mark.png"</span>
    <img src="/subfolder/check_mark.png" />
    <span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>

<p>
    <span>src="../subfolder/check_mark.png"</span>
    <img src="../subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>

<p>
    <span>src="subfolder/subfolder/check_mark.png"</span>
    <img src="subfolder/subfolder/check_mark.png" />
    <span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>

<p>
    <span>src="/subfolder/subfolder/check_mark.png"</span>
    <img src="/subfolder/subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>

Now if you load up the index.html.en file located in the second subfolder
http://example.com/subfolder/subfolder/

This will be your output

enter image description here

Object Required Error in excel VBA

The Set statement is only used for object variables (like Range, Cell or Worksheet in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer. You can find a good explanation for when to use set here.

The other problem is, that your variable g1val isn't actually declared as Integer, but has the type Variant. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant. You can only shorten your Dim statement this way:

Dim intColumn As Integer, intRow As Integer  'This creates two integers

For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.

Try this example to understand the difference:

Sub Dimming()

  Dim thisBecomesVariant, thisIsAnInteger As Integer
  Dim integerOne As Integer, integerTwo As Integer

  MsgBox TypeName(thisBecomesVariant)  'Will display "Empty"
  MsgBox TypeName(thisIsAnInteger )  'Will display "Integer"
  MsgBox TypeName(integerOne )  'Will display "Integer"
  MsgBox TypeName(integerTwo )  'Will display "Integer"

  'By assigning an Integer value to a Variant it becomes Integer, too
  thisBecomesVariant = 0
  MsgBox TypeName(thisBecomesVariant)  'Will display "Integer"

End Sub

Two further notices on your code:

First remark: Instead of writing

'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
  g1val = g1val   'Don't change g1val
Else
  g1val = Cells(33, i).Value  'Otherwise set g1val to the cell's value
End If

you could simply write

'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
  g1val = Cells(33, i).Value  'Set g1val to the cell's value 
End If

Since you don't want to change g1val in the other case.

Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

In app store connect now if we are using ads in our app then we will answer as yes to Does this app use the Advertising Identifier (IDFA)?

further 3 questions will be asked as

enter image description here

if your using just admob then check the first one and leave other two unchecked. Other two options (2nd , 3rd ) will be checked if your using app flyer to show ads. all options are explained with detail here

How to retrieve the first word of the output of a command in bash?

If you are sure there are no leading spaces, you can use bash parameter substitution:

$ string="word1  word2"
$ echo ${string/%\ */}
word1

Watch out for escaping the single space. See here for more examples of substitution patterns. If you have bash > 3.0, you could also use regular expression matching to cope with leading spaces - see here:

$ string="  word1   word2"
$ [[ ${string} =~ \ *([^\ ]*) ]]
$ echo ${BASH_REMATCH[1]}
word1

X11/Xlib.h not found in Ubuntu

Andrew White's answer is sufficient to get you moving. Here's a step-by-step for beginners.

A simple get started:

Create test.cpp: (This will be built and run to verify you got things set up right.)

#include <X11/Xlib.h>
#include <unistd.h>


main()
{
  // Open a display.
  Display *d = XOpenDisplay(0);

  if ( d )
    {
      // Create the window
      Window w = XCreateWindow(d, DefaultRootWindow(d), 0, 0, 200,
                   100, 0, CopyFromParent, CopyFromParent,
                   CopyFromParent, 0, 0);

      // Show the window
      XMapWindow(d, w);
      XFlush(d);

      // Sleep long enough to see the window.
      sleep(10);
    }
  return 0;
}

(Source: LinuxGazette)

Try: g++ test.cpp -lX11 If it builds to a.out, try running it. If you see a simple window drawn, you have the necessary libraries, and some other root problem is afoot.

If your response is:

    test.cpp:1:22: fatal error: X11/Xlib.h: No such file or directory
    compilation terminated.

you need to install X11 development libraries. sudo apt-get install libx11-dev

Retry g++ test.cpp -lX11

If it works, you're golden.

Tested using a fresh install of libX11-dev_2%3a1.5.0-1_i386.deb

How to increase icons size on Android Home Screen?

Unless you write your own Homescreen launcher or use an existing one from Goolge Play, there's "no way" to resize icons.

Well, "no way" does not mean its impossible:

  • As said, you can write your own launcher as discussed in Stackoverflow.
  • You can resize elements on the home screen, but these elements are AppWidgets. Since API level 14 they can be resized and user can - in limits - change the size. But that are Widgets not Shortcuts for launching icons.

How to redirect the output of print to a TXT file

To redirect output for all prints, you can do this:

import sys
with open('c:\\goat.txt', 'w') as f:
    sys.stdout = f
    print "test"

Drawing a dot on HTML5 canvas

The above claim that "If you are planning to draw a lot of pixel, it's a lot more efficient to use the image data of the canvas to do pixel drawing" seems to be quite wrong - at least with Chrome 31.0.1650.57 m or depending on your definition of "lot of pixel". I would have preferred to comment directly to the respective post - but unfortunately I don't have enough stackoverflow points yet:

I think that I am drawing "a lot of pixels" and therefore I first followed the respective advice for good measure I later changed my implementation to a simple ctx.fillRect(..) for each drawn point, see http://www.wothke.ch/webgl_orbittrap/Orbittrap.htm

Interestingly it turns out the silly ctx.fillRect() implementation in my example is actually at least twice as fast as the ImageData based double buffering approach.

At least for my scenario it seems that the built-in ctx.getImageData/ctx.putImageData is in fact unbelievably SLOW. (It would be interesting to know the percentage of pixels that need to be touched before an ImageData based approach might take the lead..)

Conclusion: If you need to optimize performance you have to profile YOUR code and act on YOUR findings..

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

Align Div at bottom on main Div

Please try this:

#b {
display: -webkit-inline-flex;
display: -moz-inline-flex;
display: inline-flex;

-webkit-flex-flow: row nowrap;
-moz-flex-flow: row nowrap;
flex-flow: row nowrap;

-webkit-align-items: flex-end;
-moz-align-items: flex-end;
align-items: flex-end;}

Here's a JSFiddle demo: http://jsfiddle.net/rudiedirkx/7FGKN/.

preventDefault() on an <a> tag

Set the href attribute as href="javascript:;"

<ul class="product-info">
  <li>
   <a href="javascript:;">YOU CLICK THIS TO SHOW/HIDE</a>
  <div class="toggle">
    <p>CONTENT TO SHOW/HIDE</p>
  </div>
 </li>
</ul>

How do I tokenize a string sentence in NLTK?

This is actually on the main page of nltk.org:

>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']

Regex: Check if string contains at least one digit

In Java:

public boolean containsNumber(String string)
{
    return string.matches(".*\\d+.*");
}  

Determine the data types of a data frame's columns

Another option is using the map function of the purrr package.

library(purrr)
map(df,class)

Copy table without copying data

Try

CREATE TABLE foo LIKE bar;

so the keys and indexes are copied over as, well.

Documentation

CSS last-child(-1)

You can use :nth-last-child(); in fact, besides :nth-last-of-type() I don't know what else you could use. I'm not sure what you mean by "dynamic", but if you mean whether the style applies to the new second last child when more children are added to the list, yes it will. Interactive fiddle.

ul li:nth-last-child(2)

returning a Void object

The Void class is an uninstantiable placeholder class to hold a reference to the Class object representing the Java keyword void.

So any of the following would suffice:

  • parameterizing with Object and returning new Object() or null
  • parameterizing with Void and returning null
  • parameterizing with a NullObject of yours

You can't make this method void, and anything else returns something. Since that something is ignored, you can return anything.

Rotate label text in seaborn factorplot

Aman is correct that you can use normal matplotlib commands, but this is also built into the FacetGrid:

import seaborn as sns
planets = sns.load_dataset("planets")
g = sns.factorplot("year", data=planets, aspect=1.5, kind="count", color="b")
g.set_xticklabels(rotation=30)

enter image description here

There are some comments and another answer claiming this "doesn't work", however, anyone can run the code as written here and see that it does work. The other answer does not provide a reproducible example of what isn't working, making it very difficult to address, but my guess is that people are trying to apply this solution to the output of functions that return an Axes object instead of a Facet Grid. These are different things, and the Axes.set_xticklabels() method does indeed require a list of labels and cannot simply change the properties of the existing labels on the Axes. The lesson is that it's important to pay attention to what kind of objects you are working with.

how do I get the bullet points of a <ul> to center with the text?

Add list-style-position: inside to the ul element. (example)

The default value for the list-style-position property is outside.

_x000D_
_x000D_
ul {_x000D_
    text-align: center;_x000D_
    list-style-position: inside;_x000D_
}
_x000D_
<ul>_x000D_
    <li>one</li>_x000D_
    <li>two</li>_x000D_
    <li>three</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Another option (which yields slightly different results) would be to center the entire ul element:

_x000D_
_x000D_
.parent {_x000D_
  text-align: center;_x000D_
}_x000D_
.parent > ul {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <ul>_x000D_
    <li>one</li>_x000D_
    <li>two</li>_x000D_
    <li>three</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I avoid the specification of the username and password at every git push?

As far as I know, there are simply two safe ways: ssh or passwd encrypted using a keystore.

SSH

  1. Log in your github;
  2. Visit: https://github.com/settings/keys;
  3. New SSH key;
  4. cat ~/.ssh/id_rsa.pub, paste it there, name and save it (if you have no such file, generate one for yourself by ssh-keygen -t rsa - just Enter for all prompts);
  5. Go to your local repository and update your remote by git remote set-url origin git+ssh://[email protected]/username/reponame.git - you can check it first by git remote -v);
  6. Here you go, just touch t; git add t; git commit -m "test"; git push and confirm yes to enjoy the password-free world.

passwd ENCRYPTED using a keystore

If you just use git config --global credential.helper store as others mentioned, your unencrypted passwords will be just stored in a plain text under ~/.git-credentials which is not safe as it sounds.

Try to encrypt it as

sudo apt-get install libgnome-keyring-dev
sudo make --directory=/usr/share/doc/git/contrib/credential/gnome-keyring
git config --global credential.helper /usr/share/doc/git/contrib/credential/gnome-keyring/git-credential-gnome-keyring

git config --global credential.helper store

In this case, you are using https://[email protected]/username/reponame.git.

What is the effect of encoding an image in base64?

It will be bigger in base64.

Base64 uses 6 bits per byte to encode data, whereas binary uses 8 bits per byte. Also, there is a little padding overhead with Base64. Not all bits are used with Base64 because it was developed in the first place to encode binary data on systems that can only correctly process non-binary data.

That means that the encoded image will be around 33%-36% larger (33% from not using 2 of the bits per byte, plus possible padding accounting for the remaining 3%).

align right in a table cell with CSS

How to position block elements in a td cell

The answers provided do a great job to right-align text in a td cell.

This might not be the solution when you're looking to align a block element as commented in the accepted answer. To achieve such with a block element, I have found it useful to make use of margins;

general syntax

selector {
  margin: top right bottom left;
}

justify right

td {
  /* there is a shorthand, TODO!  */
  margin: auto 0 auto auto;
}

justify center

td {
  margin: auto auto auto auto;
}

/* or the short-hand */
margin: auto;

align center

td {
  margin: auto;
}

JS Fiddle example

Alternatively, you could make you td content display inline-block if that's an option, but that may distort the position of its child elements.

How to shutdown a Spring Boot Application in a correct way?

If you are in a linux environment all you have to do is to create a symlink to your .jar file from inside /etc/init.d/

sudo ln -s /path/to/your/myboot-app.jar /etc/init.d/myboot-app

Then you can start the application like any other service

sudo /etc/init.d/myboot-app start

To close the application

sudo /etc/init.d/myboot-app stop

This way, application will not terminate when you exit the terminal. And application will shutdown gracefully with stop command.

cout is not a member of std

Also remember that it must be:

#include "stdafx.h"
#include <iostream>

and not the other way around

#include <iostream>
#include "stdafx.h"

CSS3 Continuous Rotate Animation (Just like a loading sundial)

You could use animation like this:

-webkit-animation: spin 1s infinite linear;

@-webkit-keyframes spin {
    0%   {-webkit-transform: rotate(0deg)}
    100% {-webkit-transform: rotate(360deg)}
}

Best way to convert string to bytes in Python 3?

The absolutely best way is neither of the 2, but the 3rd. The first parameter to encode defaults to 'utf-8' ever since Python 3.0. Thus the best way is

b = mystring.encode()

This will also be faster, because the default argument results not in the string "utf-8" in the C code, but NULL, which is much faster to check!

Here be some timings:

In [1]: %timeit -r 10 'abc'.encode('utf-8')
The slowest run took 38.07 times longer than the fastest. 
This could mean that an intermediate result is being cached.
10000000 loops, best of 10: 183 ns per loop

In [2]: %timeit -r 10 'abc'.encode()
The slowest run took 27.34 times longer than the fastest. 
This could mean that an intermediate result is being cached.
10000000 loops, best of 10: 137 ns per loop

Despite the warning the times were very stable after repeated runs - the deviation was just ~2 per cent.


Using encode() without an argument is not Python 2 compatible, as in Python 2 the default character encoding is ASCII.

>>> 'äöä'.encode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)

How do I center align horizontal <UL> menu?

This is the simplest way I found. I used your html. The padding is just to reset browser defaults.

_x000D_
_x000D_
ul {_x000D_
  text-align: center;_x000D_
  padding: 0;_x000D_
}_x000D_
li {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div class="topmenu-design">_x000D_
  <!-- Top menu content: START -->_x000D_
  <ul id="topmenu firstlevel">_x000D_
    <li class="firstli" id="node_id_64">_x000D_
      <div><a href="#"><span>Om kampanjen</span></a>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li id="node_id_65">_x000D_
      <div><a href="#"><span>Fakta om inneklima</span></a>_x000D_
      </div>_x000D_
    </li>_x000D_
    <li class="lastli" id="node_id_66">_x000D_
      <div><a href="#"><span>Statistikk</span></a>_x000D_
      </div>_x000D_
    </li>_x000D_
  </ul>_x000D_
  <!-- Top menu content: END -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

Removing numbers from string

Would this work for your situation?

>>> s = '12abcd405'
>>> result = ''.join([i for i in s if not i.isdigit()])
>>> result
'abcd'

This makes use of a list comprehension, and what is happening here is similar to this structure:

no_digits = []
# Iterate through the string, adding non-numbers to the no_digits list
for i in s:
    if not i.isdigit():
        no_digits.append(i)

# Now join all elements of the list with '', 
# which puts all of the characters together.
result = ''.join(no_digits)

As @AshwiniChaudhary and @KirkStrauser point out, you actually do not need to use the brackets in the one-liner, making the piece inside the parentheses a generator expression (more efficient than a list comprehension). Even if this doesn't fit the requirements for your assignment, it is something you should read about eventually :) :

>>> s = '12abcd405'
>>> result = ''.join(i for i in s if not i.isdigit())
>>> result
'abcd'

Java Runtime.getRuntime(): getting output from executing a command line program

Try reading the InputStream of the runtime:

Runtime rt = Runtime.getRuntime();
String[] commands = {"system.exe", "-send", argument};
Process proc = rt.exec(commands);
BufferedReader br = new BufferedReader(
    new InputStreamReader(proc.getInputStream()));
String line;
while ((line = br.readLine()) != null)
    System.out.println(line);

You might also need to read the error stream (proc.getErrorStream()) if the process is printing error output. You can redirect the error stream to the input stream if you use ProcessBuilder.

How does database indexing work?

The first time I read this it was very helpful to me. Thank you.

Since then I gained some insight about the downside of creating indexes: if you write into a table (UPDATE or INSERT) with one index, you have actually two writing operations in the file system. One for the table data and another one for the index data (and the resorting of it (and - if clustered - the resorting of the table data)). If table and index are located on the same hard disk this costs more time. Thus a table without an index (a heap) , would allow for quicker write operations. (if you had two indexes you would end up with three write operations, and so on)

However, defining two different locations on two different hard disks for index data and table data can decrease/eliminate the problem of increased cost of time. This requires definition of additional file groups with according files on the desired hard disks and definition of table/index location as desired.

Another problem with indexes is their fragmentation over time as data is inserted. REORGANIZE helps, you must write routines to have it done.

In certain scenarios a heap is more helpful than a table with indexes,

e.g:- If you have lots of rivalling writes but only one nightly read outside business hours for reporting.

Also, a differentiation between clustered and non-clustered indexes is rather important.

Helped me:- What do Clustered and Non clustered index actually mean?

jQuery - Uncaught RangeError: Maximum call stack size exceeded

Your calls are made recursively which pushes functions on to the stack infinitely that causes max call stack exceeded error due to recursive behavior. Instead try using setTimeout which is a callback.

Also based on your markup your selector is wrong. it should be #advisersDiv

Demo

function fadeIn() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
    setTimeout(fadeOut,1); //<-- Provide any delay here
};

function fadeOut() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
    setTimeout(fadeIn,1);//<-- Provide any delay here
};
fadeIn();