Programs & Examples On #Compact policy

When using .net MVC RadioButtonFor(), how do you group so only one selection can be made?

In cases where the name attribute is different it is easiest to control the radio group via JQuery. When an option is selected use JQuery to un-select the other options.

How to set the java.library.path from Eclipse

You can add vm argument in your Eclipse.

Example :

-Djava.ext.dirs=cots_lib

where cots_lib is your external folder library.

How to set an button align-right with Bootstrap?

This work for me in bootstrap 4:

    <div class="alert alert-info">
      <a href="#" class="alert-link">Summary:Its some description.......testtesttest</a>  
      <button type="button" class="btn btn-primary btn-lg float-right">Large button</button>
    </div>

Importing Maven project into Eclipse

Maven have a Eclipse plugin and Eclipse have a Maven plugin we are going to discus those things.when we using maven with those command line stuffs and etc when we are going through eclipse we don't want to that command line codes it have very much helpful, Maven and eclipse giving good integration ,they will work very well together thanks for that plugins

Step 1: Go to the maven project. Here my project is FirstApp.(Example my project is FirstApp)

There you can see one pom.xml file, now what we want is to generate an eclipse project using that pom.xml.

Step 2: Use mvn eclipse:eclipse command

Step 3: Verify the project

after execution of this command notice that two new files have been created

Note:- both these files are created for Eclipse. When you open those files you will notice a "M2_REPO" class variable is generate. You want to add that class path in eclipse, otherwise eclipse will show a error.

Step 4: Importing eclipse project

File -> Import -> General -> Existing Projects in Workspace -> Select root directory -> Done

More details here

Convert an array into an ArrayList

As an ArrayList that line would be

import java.util.ArrayList;
...
ArrayList<Card> hand = new ArrayList<Card>();

To use the ArrayList you have do

hand.get(i); //gets the element at position i 
hand.add(obj); //adds the obj to the end of the list
hand.remove(i); //removes the element at position i
hand.add(i, obj); //adds the obj at the specified index
hand.set(i, obj); //overwrites the object at i with the new obj

Also read this http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html

Where can I download an offline installer of Cygwin?

Not a direct answer to your question, but you can get the most commonly used utilities from http://www.mingw.org/ without having to jump through the hoops with that horrible Cygwin installer.

Here is a slightly more informative link http://sourceforge.net/apps/mediawiki/cobcurses/index.php?title=Install-MSYS.

INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE

I've solved this without having to resort to uninstalling the alternate apk first (what a pain, right?). To successfully install both a debug and release version of an apk, simply use gradle's built-in ${applicationId} placeholder within the AndroidManifest.xml to modify the permissions' android:name values at compile time.

The build.gradle file snippet:

buildTypes {
    debug {
        applicationIdSuffix ".debug"
        ...
    }
}

The AndroidStudio.xml file snippet:

<uses-permission android:name="${applicationId}.permission.C2D_MESSAGE"/>
<permission
    android:name="${applicationId}.permission.C2D_MESSAGE"
    android:protectionLevel="signature"/>

You can inspect the modified AndroidManifest.xml file within the apk using aapt l -a app-debug.apk to ensure the placeholder was properly applied. If you use various product flavors, I'm sure you can apply a variation of this method to suit your needs.

changing minDate option in JQuery DatePicker not working

Change the minDate dynamically

.datepicker("destroy")

For example

<script>
    $(function() {
      $( "#datepicker" ).datepicker("destroy");
      $( "#datepicker" ).datepicker();
    });
  </script>

  <p>Date: <input type="text" id="datepicker" /></p>

Which icon sizes should my Windows application's icon include?

In the case of Windows 10 this is not exactly accurate, in fact none of the answers on stackoverflow was, I found this out when I tried to use pixel art as an icon and it got rescaled when it was not supposed to(it was easy to see in this case cause of the interpolation and smoothing windows does) even thou I used the sizes from this post.

So I made an app and did the work on all DPI settings, see it here:
Windows 10 all icon resolutions on all DPI settings
You can also use my app to create icons, also with nearest neighbor interpolation with smoothing off, which is not done with any of the bad editors I have seen.

If you only want the resolutions:
16, 20, 24, 28, 30, 31, 32, 40, 42, 47, 48, 56, 60, 63, 84, 256
and you should use all PNG icons and anything you put in beside these it won't be displayed. See my post why.

Text in Border CSS HTML

Yes, but it's not a div, it's a fieldset

_x000D_
_x000D_
fieldset {
    border: 1px solid #000;
}
_x000D_
<fieldset>
  <legend>AAA</legend>
</fieldset>
_x000D_
_x000D_
_x000D_

Using form input to access camera and immediately upload photos using web app

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);

How to extract svg as file from web page

I don't know if this already been answered correctly or not. Well. Downloading the file from the source is not the resolution. How to grab *.svg from URL.

I installed 'svg-grabber' add-on to Google Chrome. That only partially resolve my problem, as Google Chrome does not have the shortcut to 'Back' one page.

I was trying to download the files from URL, but I kept getting an error, that there are no svg files on this page when I can see 40 of them. You can click on them, so they will open, but you cannot save it.

The folder within WordPress: .../static/img/icons/

I added 'Go Back With Backspace' add-on to Chrome, as I had to click on each file separately, as if they are white icons (that I am currently looking for), you will not see them. You have to click on the file. Then back. It was taking too long. Now is fine. There is a soft to download specific folder, but I do not want to download half of the internet, to just have get a white .

When you click on a white icon, a new tab opens, but it is all white. Then you click on svg-grabber icon in Chrome and it will open it in a new window on a black background with a button download all svg.

get parent's view from a layout

If you are trying to find a View from your Fragment then try doing it like this:

int w = ((EditText)getActivity().findViewById(R.id.editText1)).getLayoutParams().width;

Get integer value of the current year in Java

In Java version 8+ can (advised to) use java.time library. ISO 8601 sets standard way to write dates: YYYY-MM-DD and java.time.Instant uses it, so (for UTC):

import java.time.Instant;
int myYear = Integer.parseInt(Instant.now().toString().substring(0,4));

P.S. just in case (and shorted for getting String, not int), using Calendar looks better and can be made zone-aware.

java.net.SocketException: Connection reset by peer: socket write error When serving a file

This problem is usually caused by writing to a connection that had already been closed by the peer. In this case it could indicate that the user cancelled the download for example.

How to use confirm using sweet alert?

You need To use then() function, like this

swal({
    title: "Are you sure?",
    text: "You will not be able to recover this imaginary file!",
    type: "warning",
    showCancelButton: true,
    confirmButtonColor: '#DD6B55',
    confirmButtonText: 'Yes, I am sure!',
    cancelButtonText: "No, cancel it!"
 }).then(
       function () { /*Your Code Here*/ },
       function () { return false; });

Scrollview vertical and horizontal in android

use this way I tried this I fixed it

Put All your XML layout inside

<android.support.v4.widget.NestedScrollView 

I explained this in this link vertical recyclerView and Horizontal recyclerview scrolling together

Windows shell command to get the full path to the current directory?

Based on the follow up question (store the data in a variable) in the comments to the chdir post I'm betting he wants to store the current path to restore it after changeing directories.

The original user should look at "pushd", which changes directory and pushes the current one onto a stack that can be restored with a "popd". On any modern Windows cmd shell that is the way to go when making batch files.

If you really need to grab the current path then modern cmd shells also have a %CD% variable that you can easily stuff away in another variable for reference.

How to make <label> and <input> appear on the same line on an HTML form?

I found "display:flex" style is a good way to make these elements in same line. No matter what kind of element in the div. Especially if the input class is form-control,other solutions like bootstrap, inline-block will not work well.

Example:

<div style="display:flex; flex-direction: row; justify-content: center; align-items: center">
    <label for="Student">Name:</label>
    <input name="Student" />
</div>

More detail about display:flex:

flex-direction: row, column

justify-content: flex-end, center, space-between, space-around

align-items: stretch, flex-start, flex-end, center

Set ImageView width and height programmatically?

I have played this one with pixel and dp.

private int dimensionInPixel = 200;

How to set by pixel:

view.getLayoutParams().height = dimensionInPixel;
view.getLayoutParams().width = dimensionInPixel;
view.requestLayout();

How to set by dp:

int dimensionInDp = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dimensionInPixel, getResources().getDisplayMetrics());
view.getLayoutParams().height = dimensionInDp;
view.getLayoutParams().width = dimensionInDp;
view.requestLayout();

Hope this would help you.

Coding Conventions - Naming Enums

This will probably not make me a lot of new friends, but it should be added that the C# people have a different guideline: The enum instances are "Pascal case" (upper/lower case mixed). See stackoverflow discussion and MSDN Enumeration Type Naming Guidelines.

As we are exchanging data with a C# system, I am tempted to copy their enums exactly, ignoring Java's "constants have uppercase names" convention. Thinking about it, I don't see much value in being restricted to uppercase for enum instances. For some purposes .name() is a handy shortcut to get a readable representation of an enum constant and a mixed case name would look nicer.

So, yes, I dare question the value of the Java enum naming convention. The fact that "the other half of the programming world" does indeed use a different style makes me think it is legitimate to doubt our own religion.

How can I run NUnit tests in Visual Studio 2017?

This one helped me:

Getting started with .NET unit testing using NUnit

Basically:

  • Add the NUnit 3 library in NuGet.
  • Create the class you want to test.
  • Create a separate testing class. This should have [TestFixture] above it.
  • Create a function in the testing class. This should have [Test] above it.
  • Then go into TEST/WINDOW/TEST EXPLORER (across the top).
  • Click run to the left-hand side. It will tell you what has passed and what has failed.

My example code is here:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;

namespace NUnitTesting
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }

    public class Maths
    {
        public int Add(int a, int b)
        {
            int x = a + b;
            return x;
        }
    }

    [TestFixture]
    public class TestLogging
    {
        [Test]
        public void Add()
        {
            Maths add = new Maths();
            int expectedResult = add.Add(1, 2);
            Assert.That(expectedResult, Is.EqualTo(3));
        }
    }
}

This will return true, and if you change the parameter in Is.EqualTo it will fail, etc.

How to Sort Multi-dimensional Array by Value?

If anyone need sort according to key best is to use below

usort($array, build_sorter('order'));

function build_sorter($key) {
   return function ($a, $b) use ($key) {
      return strnatcmp($a[$key], $b[$key]);
   };
}

AngularJS check if form is valid in controller

I have updated the controller to:

.controller('BusinessCtrl',
    function ($scope, $http, $location, Business, BusinessService, UserService, Photo) {
        $scope.$watch('createBusinessForm.$valid', function(newVal) {
            //$scope.valid = newVal;
            $scope.informationStatus = true;
        });
        ...

auto run a bat script in windows 7 at login

To run the batch file when the VM user logs in:

Drag the shortcut--the one that's currently on your desktop--(or the batch file itself) to Start - All Programs - Startup. Now when you login as that user, it will launch the batch file.

Another way to do the same thing is to save the shortcut or the batch file in %AppData%\Microsoft\Windows\Start Menu\Programs\Startup\.

As far as getting it to run full screen, it depends a bit what you mean. You can have it launch maximized by editing your batch file like this:

start "" /max "C:\Program Files\Oracle\VirtualBox\VirtualBox.exe" --comment "VM" --startvm "12dada4d-9cfd-4aa7-8353-20b4e455b3fa"

But if VirtualBox has a truly full-screen mode (where it hides even the taskbar), you'll have to look for a command-line parameter on VirtualBox.exe. I'm not familiar with that product.

Config Error: This configuration section cannot be used at this path

Browse to “C:\Windows\System32\inetsrv\config” (you will need administrator rights here) Open applicationHost.config

Note: In IISExpress and Visual Studio 2015 the applicationHost.config is stored in $(solutionDir).vs\config\applicationhost.config

Find the section that showed up in the “config source” part of the error message page. For me this has typically been “modules” or “handlers”

Change the overrideModeDefault attribute to be Allow

So the whole line now looks like:

<section name="modules" allowDefinition="MachineToApplication" overrideModeDefault="Allow" />

After saving the file, the page loaded up fine in my browser.

Warning: Editing applicationHost.config on 64-bit Windows

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

The difference is that one modifies the data-structure itself (in-place operation) b += 1 while the other just reassigns the variable a = a + 1.


Just for completeness:

x += y is not always doing an in-place operation, there are (at least) three exceptions:

  • If x doesn't implement an __iadd__ method then the x += y statement is just a shorthand for x = x + y. This would be the case if x was something like an int.

  • If __iadd__ returns NotImplemented, Python falls back to x = x + y.

  • The __iadd__ method could theoretically be implemented to not work in place. It'd be really weird to do that, though.

As it happens your bs are numpy.ndarrays which implements __iadd__ and return itself so your second loop modifies the original array in-place.

You can read more on this in the Python documentation of "Emulating Numeric Types".

These [__i*__] methods are called to implement the augmented arithmetic assignments (+=, -=, *=, @=, /=, //=, %=, **=, <<=, >>=, &=, ^=, |=). These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). If a specific method is not defined, the augmented assignment falls back to the normal methods. For instance, if x is an instance of a class with an __iadd__() method, x += y is equivalent to x = x.__iadd__(y) . Otherwise, x.__add__(y) and y.__radd__(x) are considered, as with the evaluation of x + y. In certain situations, augmented assignment can result in unexpected errors (see Why does a_tuple[i] += ["item"] raise an exception when the addition works?), but this behavior is in fact part of the data model.

New line in JavaScript alert box

List of Special Character codes in JavaScript:

Code    Outputs
\'  single quote
\"  double quote
\\  backslash
\n  new line
\r  carriage return
\t  tab
\b  backspace
\f  form feed

Git merge errors

It's worth understanding what those error messages mean - needs merge and error: you need to resolve your current index first indicate that a merge failed, and that there are conflicts in those files. If you've decided that whatever merge you were trying to do was a bad idea after all, you can put things back to normal with:

git reset --merge

However, otherwise you should resolve those merge conflicts, as described in the git manual.


Once you've dealt with that by either technique you should be able to checkout the 9-sign-in-out branch. The problem with just renaming your 9-sign-in-out to master, as suggested in wRAR's answer is that if you've shared your previous master branch with anyone, this will create problems for them, since if the history of the two branches diverged, you'll be publishing rewritten history.

Essentially what you want to do is to merge your topic branch 9-sign-in-out into master but exactly keep the versions of the files in the topic branch. You could do this with the following steps:

# Switch to the topic branch:
git checkout 9-sign-in-out

# Create a merge commit, which looks as if it's merging in from master, but is
# actually discarding everything from the master branch and keeping everything
# from 9-sign-in-out:
git merge -s ours master

# Switch back to the master branch:
git checkout master

# Merge the topic branch into master - this should now be a fast-forward
# that leaves you with master exactly as 9-sign-in-out was:
git merge 9-sign-in-out

What is the correct way to read a serial port using .NET framework?

I used similar code to @MethodMan but I had to keep track of the data the serial port was sending and look for a terminating character to know when the serial port was done sending data.

private string buffer { get; set; }
private SerialPort _port { get; set; }

public Port() 
{
    _port = new SerialPort();
    _port.DataReceived += new SerialDataReceivedEventHandler(dataReceived);
    buffer = string.Empty;
}

private void dataReceived(object sender, SerialDataReceivedEventArgs e)
{    
    buffer += _port.ReadExisting();

    //test for termination character in buffer
    if (buffer.Contains("\r\n"))
    {
        //run code on data received from serial port
    }
}

How could I create a function with a completion handler in Swift?

In addition to above : Trailing closure can be used .

downloadFileFromURL(NSURL(string: "url_str")!)  { (success) -> Void in

  // When download completes,control flow goes here.
  if success {
      // download success
  } else {
    // download fail
  }
}

JavaScript/jQuery: replace part of string?

It should be like this

$(this).text($(this).text().replace('N/A, ', ''))

Java file path in Linux

I think Todd is correct, but I think there's one other thing you should consider. You can reliably get the home directory from the JVM at runtime, and then you can create files objects relative to that location. It's not that much more trouble, and it's something you'll appreciate if you ever move to another computer or operating system.

File homedir = new File(System.getProperty("user.home"));
File fileToRead = new File(homedir, "java/ex.txt");

Can't access Eclipse marketplace

in my case the solution was to set the proxy to "native" I had configured the proxy under linux with cntlm and also in Firefox (used as eclipse browser also.

Anaconda / Python: Change Anaconda Prompt User Path

In both: Anaconda prompt and the old cmd.exe, you change your directory by first changing to the drive you want, by simply writing its name followed by a ':', exe: F: , which will take you to the drive named 'F' on your machine. Then using the command cd to navigate your way inside that drive as you normally would.

Monitor the Graphics card usage

If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:

Screenshot from MSDN: enter image description here

Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:

In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.

Source: http://blogs.msdn.com/b/ianhu/archive/2014/12/16/gpu-usage-for-directx-in-visual-studio.aspx

How to redirect to another page in node.js

The If else statement needs to be wrapped in a .get or a .post to redirect. Such as

app.post('/login', function(req, res) {
});

or

app.get('/login', function(req, res) {
});

Sort hash by key, return hash in Ruby

@ordered = {}
@unordered.keys.sort.each do |key|
  @ordered[key] = @unordered[key]
end

UIView touch event in controller

Swift 4 / 5:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction))
self.myView.addGestureRecognizer(gesture)

@objc func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}

Swift 3:

let gesture = UITapGestureRecognizer(target: self, action:  #selector(self.checkAction(sender:)))
self.myView.addGestureRecognizer(gesture)

func checkAction(sender : UITapGestureRecognizer) {
    // Do what you want
}

Entity Framework Refresh context?

The best way to refresh entities in your context is to dispose your context and create a new one.

If you really need to refresh some entity and you are using Code First approach with DbContext class, you can use

    public static void ReloadEntity<TEntity>(
        this DbContext context, 
        TEntity entity)
        where TEntity : class
    {
        context.Entry(entity).Reload();
    }

To reload collection navigation properties, you can use

    public static void ReloadNavigationProperty<TEntity, TElement>(
        this DbContext context, 
        TEntity entity, 
        Expression<Func<TEntity, ICollection<TElement>>> navigationProperty)
        where TEntity : class
        where TElement : class
    {
        context.Entry(entity).Collection<TElement>(navigationProperty).Query();
    }

Reference: https://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.dbentityentry.reload(v=vs.113).aspx#M:System.Data.Entity.Infrastructure.DbEntityEntry.Reload

jQuery AJAX Call to PHP Script with JSON Return

I recommend you use:

var returnedData = JSON.parse(data);

to convert the JSON string (if it is just text) to a JavaScript object.

casting Object array to Integer array error

Or do the following:

...

  Integer[] integerArray = new Integer[integerList.size()];
  integerList.toArray(integerArray);

  return integerArray;

}

Algorithm for Determining Tic Tac Toe Game Over

a non-loop way to determine if the point was on the anti diag:

`if (x + y == n - 1)`

How to add data into ManyToMany field?

There's a whole page of the Django documentation devoted to this, well indexed from the contents page.

As that page states, you need to do:

my_obj.categories.add(fragmentCategory.objects.get(id=1))

or

my_obj.categories.create(name='val1')

Why do I always get the same sequence of random numbers with rand()?

Rand does not get you a random number. It gives you the next number in a sequence generated by a pseudorandom number generator. To get a different sequence every time you start your program, you have to seed the algorithm by calling srand.

A (very bad) way to do it is by passing it the current time:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    srand(time(NULL));
    int i, j = 0;
    for(i = 0; i <= 10; i++) {
        j = rand();
        printf("j = %d\n", j);
    }
    return 0;
}

Why this is a bad way? Because a pseudorandom number generator is as good as its seed, and the seed must be unpredictable. That is why you may need a better source of entropy, like reading from /dev/urandom.

Python: fastest way to create a list of n lists

Here are two methods, one sweet and simple(and conceptual), the other more formal and can be extended in a variety of situations, after having read a dataset.

Method 1: Conceptual

X2=[]
X1=[1,2,3]
X2.append(X1)
X3=[4,5,6]
X2.append(X3)
X2 thus has [[1,2,3],[4,5,6]] ie a list of lists. 

Method 2 : Formal and extensible

Another elegant way to store a list as a list of lists of different numbers - which it reads from a file. (The file here has the dataset train) Train is a data-set with say 50 rows and 20 columns. ie. Train[0] gives me the 1st row of a csv file, train[1] gives me the 2nd row and so on. I am interested in separating the dataset with 50 rows as one list, except the column 0 , which is my explained variable here, so must be removed from the orignal train dataset, and then scaling up list after list- ie a list of a list. Here's the code that does that.

Note that I am reading from "1" in the inner loop since I am interested in explanatory variables only. And I re-initialize X1=[] in the other loop, else the X2.append([0:(len(train[0])-1)]) will rewrite X1 over and over again - besides it more memory efficient.

X2=[]
for j in range(0,len(train)):
    X1=[]
    for k in range(1,len(train[0])):
        txt2=train[j][k]
        X1.append(txt2)
    X2.append(X1[0:(len(train[0])-1)])

Add error bars to show standard deviation on a plot in R

A Problem with csgillespie solution appears, when You have an logarithmic X axis. The you will have a different length of the small bars on the right an the left side (the epsilon follows the x-values).

You should better use the errbar function from the Hmisc package:

d = data.frame(
  x  = c(1:5)
  , y  = c(1.1, 1.5, 2.9, 3.8, 5.2)
  , sd = c(0.2, 0.3, 0.2, 0.0, 0.4)
)

##install.packages("Hmisc", dependencies=T)
library("Hmisc")

# add error bars (without adjusting yrange)
plot(d$x, d$y, type="n")
with (
  data = d
  , expr = errbar(x, y, y+sd, y-sd, add=T, pch=1, cap=.1)
)

# new plot (adjusts Yrange automatically)
with (
  data = d
  , expr = errbar(x, y, y+sd, y-sd, add=F, pch=1, cap=.015, log="x")
)

Could not find a version that satisfies the requirement <package>

This approach (having all dependencies in a directory and not downloading from an index) only works when the directory contains all packages. The directory should therefore contain all dependencies but also all packages that those dependencies depend on (e.g., six, pytz etc).

You should therefore manually include these in requirements.txt (so that the first step downloads them explicitly) or you should install all packages using PyPI and then pip freeze > requirements.txt to store the list of all packages needed.

Delete last commit in bitbucket

You can write the command also for Bitbucket as mentioned by Dustin:

git push -f origin HEAD^:master

Note: instead of master you can use any branch. And it deletes just push on Bitbucket.

To remove last commit locally in git use:

git reset --hard HEAD~1

Call asynchronous method in constructor?

Try to replace this:

myLongList.ItemsSource = writings;

with this

Dispatcher.BeginInvoke(() => myLongList.ItemsSource = writings);

what does numpy ndarray shape do?

yourarray.shape or np.shape() or np.ma.shape() returns the shape of your ndarray as a tuple; And you can get the (number of) dimensions of your array using yourarray.ndim or np.ndim(). (i.e. it gives the n of the ndarray since all arrays in NumPy are just n-dimensional arrays (shortly called as ndarrays))

For a 1D array, the shape would be (n,) where n is the number of elements in your array.

For a 2D array, the shape would be (n,m) where n is the number of rows and m is the number of columns in your array.

Please note that in 1D case, the shape would simply be (n, ) instead of what you said as either (1, n) or (n, 1) for row and column vectors respectively.

This is to follow the convention that:

For 1D array, return a shape tuple with only 1 element   (i.e. (n,))
For 2D array, return a shape tuple with only 2 elements (i.e. (n,m))
For 3D array, return a shape tuple with only 3 elements (i.e. (n,m,k))
For 4D array, return a shape tuple with only 4 elements (i.e. (n,m,k,j))

and so on.

Also, please see the example below to see how np.shape() or np.ma.shape() behaves with 1D arrays and scalars:

# sample array
In [10]: u = np.arange(10)

# get its shape
In [11]: np.shape(u)    # u.shape
Out[11]: (10,)

# get array dimension using `np.ndim`
In [12]: np.ndim(u)
Out[12]: 1

In [13]: np.shape(np.mean(u))
Out[13]: ()       # empty tuple (to indicate that a scalar is a 0D array).

# check using `numpy.ndim`
In [14]: np.ndim(np.mean(u))
Out[14]: 0

P.S.: So, the shape tuple is consistent with our understanding of dimensions of space, at least mathematically.

Convert hex string to int in Python

If you are using the python interpreter, you can just type 0x(your hex value) and the interpreter will convert it automatically for you.

>>> 0xffff

65535

How eliminate the tab space in the column in SQL Server 2008

Try this code

SELECT REPLACE([Column], char(9), '') From [dbo.Table] 

char(9) is the TAB character

HTML tag <a> want to add both href and onclick working

No jQuery needed.

Some people say using onclick is bad practice...

This example uses pure browser javascript. By default, it appears that the click handler will evaluate before the navigation, so you can cancel the navigation and do your own if you wish.

<a id="myButton" href="http://google.com">Click me!</a>
<script>
    window.addEventListener("load", () => {
        document.querySelector("#myButton").addEventListener("click", e => {
            alert("Clicked!");
            // Can also cancel the event and manually navigate
            // e.preventDefault();
            // window.location = e.target.href;
        });
    });
</script>

Wamp Server not goes to green color

Open cmd and type the command below.

netstat -o -n -a | findstr 0.0:80

Last column of each row is the process identifier (PID)

You can find the application that reserves port 80, using taskmanager services tab or just type tasklist in cmd.

Then follow this link: http://www.ttkalec.com/blog/resolving-yellow-wamp-server-status-freeing-up-port-80-for-apache/

Best way to "negate" an instanceof

No, there is no better way; yours is canonical.

Select Multiple Fields from List in Linq

Anonymous types allow you to select arbitrary fields into data structures that are strongly typed later on in your code:

var cats = listObject
    .Select(i => new { i.category_id, i.category_name })
    .Distinct()
    .OrderByDescending(i => i.category_name)
    .ToArray();

Since you (apparently) need to store it for later use, you could use the GroupBy operator:

Data[] cats = listObject
    .GroupBy(i => new { i.category_id, i.category_name })
    .OrderByDescending(g => g.Key.category_name)
    .Select(g => g.First())
    .ToArray();

How do you exit from a void function in C++?

Use a return statement!

return;

or

if (condition) return;

You don't need to (and can't) specify any values, if your method returns void.

How to download/upload files from/to SharePoint 2013 using CSOM?

A little late this comment but I will leave here my results working with the library of SharePoin Online and it is very easy to use and implement in your project, just go to the NuGet administrator of .Net and Add Microsoft.SharePoint.CSOM to your project .

https://developer.microsoft.com/en-us/office/blogs/new-sharepoint-csom-version-released-for-office-365-may-2017/

The following code snippet will help you connect your credentials to your SharePoint site, you can also read and download files from a specific site and folder.

using System;
using System.IO;
using System.Linq;
using System.Web;
using Microsoft.SharePoint.Client;
using System.Security;

using ClientOM = Microsoft.SharePoint.Client;

namespace MvcApplication.Models.Home
{
    public class SharepointModel
    {
        public ClientContext clientContext { get; set; }
        private string ServerSiteUrl = "https://somecompany.sharepoint.com/sites/ITVillahermosa";
        private string LibraryUrl = "Shared Documents/Invoices/";
        private string UserName = "[email protected]";
        private string Password = "********";
        private Web WebClient { get; set; }

        public SharepointModel()
        {
            this.Connect();
        }

        public void Connect()
        {
            try
            {
                using (clientContext = new ClientContext(ServerSiteUrl))
                {
                    var securePassword = new SecureString();
                    foreach (char c in Password)
                    {
                        securePassword.AppendChar(c);
                    }

                    clientContext.Credentials = new SharePointOnlineCredentials(UserName, securePassword);
                    WebClient = clientContext.Web;
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        public string UploadMultiFiles(HttpRequestBase Request, HttpServerUtilityBase Server)
        {
            try
            {
                HttpPostedFileBase file = null;
                for (int f = 0; f < Request.Files.Count; f++)
                {
                    file = Request.Files[f] as HttpPostedFileBase;

                    string[] SubFolders = LibraryUrl.Split('/');
                    string filename = System.IO.Path.GetFileName(file.FileName);
                    var path = System.IO.Path.Combine(Server.MapPath("~/App_Data/uploads"), filename);
                    file.SaveAs(path);

                    clientContext.Load(WebClient, website => website.Lists, website => website.ServerRelativeUrl);
                    clientContext.ExecuteQuery();

                    //https://somecompany.sharepoint.com/sites/ITVillahermosa/Shared Documents/
                    List documentsList = clientContext.Web.Lists.GetByTitle("Documents"); //Shared Documents -> Documents
                    clientContext.Load(documentsList, i => i.RootFolder.Folders, i => i.RootFolder);
                    clientContext.ExecuteQuery();

                    string SubFolderName = SubFolders[1];//Get SubFolder 'Invoice'
                    var folderToBindTo = documentsList.RootFolder.Folders;
                    var folderToUpload = folderToBindTo.Where(i => i.Name == SubFolderName).First();

                    var fileCreationInformation = new FileCreationInformation();
                    //Assign to content byte[] i.e. documentStream
                    fileCreationInformation.Content = System.IO.File.ReadAllBytes(path);
                    //Allow owerwrite of document
                    fileCreationInformation.Overwrite = true;
                    //Upload URL
                    fileCreationInformation.Url = ServerSiteUrl + LibraryUrl + filename;

                    Microsoft.SharePoint.Client.File uploadFile = documentsList.RootFolder.Files.Add(fileCreationInformation);

                    //Update the metadata for a field having name "DocType"
                    uploadFile.ListItemAllFields["Title"] = "UploadedCSOM";

                    uploadFile.ListItemAllFields.Update();
                    clientContext.ExecuteQuery();
                }

                return "";
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        public string DownloadFiles()
        {
            try
            {
                string tempLocation = @"c:\Downloads\Sharepoint\";
                System.IO.DirectoryInfo di = new DirectoryInfo(tempLocation);
                foreach (FileInfo file in di.GetFiles())
                {
                    file.Delete();
                }

                FileCollection files = WebClient.GetFolderByServerRelativeUrl(this.LibraryUrl).Files;
                clientContext.Load(files);
                clientContext.ExecuteQuery();

                if (clientContext.HasPendingRequest)
                    clientContext.ExecuteQuery();

                foreach (ClientOM.File file in files)
                {
                    FileInformation fileInfo = ClientOM.File.OpenBinaryDirect(clientContext, file.ServerRelativeUrl);
                    clientContext.ExecuteQuery();

                    var filePath = tempLocation + file.Name;
                    using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create))
                    {
                        fileInfo.Stream.CopyTo(fileStream);
                    }
                }

                return "";
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

    }
}

Then to invoke the functions from the controller in this case MVC ASP.NET is done in the following way.


using MvcApplication.Models.Home;
using System;
using System.Web.Mvc;

namespace MvcApplication.Controllers
{
    public class SharepointController : MvcBoostraBaseController
    {
        [HttpPost]
        public ActionResult Upload(FormCollection form)
        {
            try
            {
                SharepointModel sharepointModel = new SharepointModel();
                return Json(sharepointModel.UploadMultiFiles(Request, Server), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return ThrowJSONError(ex);
            }
        }

        public ActionResult Download(string ServerUrl, string RelativeUrl)
        {
            try
            {
                SharepointModel sharepointModel = new SharepointModel();
                return Json(sharepointModel.DownloadFiles(), JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return ThrowJSONError(ex);
            }
        }
    }
}

If you need the source code of this project you can request it to [email protected]

Java AES and using my own Key

You should use a KeyGenerator to generate the Key,

AES key lengths are 128, 192, and 256 bit depending on the cipher you want to use.

Take a look at the tutorial here

Here is the code for Password Based Encryption, this has the password being entered through System.in you can change that to use a stored password if you want.

        PBEKeySpec pbeKeySpec;
        PBEParameterSpec pbeParamSpec;
        SecretKeyFactory keyFac;

        // Salt
        byte[] salt = {
            (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
            (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
        };

        // Iteration count
        int count = 20;

        // Create PBE parameter set
        pbeParamSpec = new PBEParameterSpec(salt, count);

        // Prompt user for encryption password.
        // Collect user password as char array (using the
        // "readPassword" method from above), and convert
        // it into a SecretKey object, using a PBE key
        // factory.
        System.out.print("Enter encryption password:  ");
        System.out.flush();
        pbeKeySpec = new PBEKeySpec(readPassword(System.in));
        keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

        // Create PBE Cipher
        Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");

        // Initialize PBE Cipher with key and parameters
        pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

        // Our cleartext
        byte[] cleartext = "This is another example".getBytes();

        // Encrypt the cleartext
        byte[] ciphertext = pbeCipher.doFinal(cleartext);

How do I sort a list of dictionaries by a value of the dictionary?

I guess you've meant:

[{'name':'Homer', 'age':39}, {'name':'Bart', 'age':10}]

This would be sorted like this:

sorted(l,cmp=lambda x,y: cmp(x['name'],y['name']))

How can I switch language in google play?

Answer below the dotted line below is the original that's now outdated.

Here is the latest information ( Thank you @deadfish ):

add &hl=<language> like &hl=pl or &hl=en

example: https://play.google.com/store/apps/details?id=com.example.xxx&hl=en or https://play.google.com/store/apps/details?id=com.example.xxx&hl=pl

All available languages and abbreviations can be looked up here: https://support.google.com/googleplay/android-developer/table/4419860?hl=en

......................................................................

To change the actual local market:

Basically the market is determined automatically based on your IP. You can change some local country settings from your Gmail account settings but still IP of the country you're browsing from is more important. To go around it you'd have to Proxy-cheat. Check out some ways/sites: http://www.affilorama.com/forum/market-research/how-to-change-country-search-settings-in-google-t4160.html

To do it from an Android phone you'd need to find an app. I don't have my Droid anymore but give this a try: http://forum.xda-developers.com/showthread.php?t=694720

Python List vs. Array - when to use?

Basically, Python lists are very flexible and can hold completely heterogeneous, arbitrary data, and they can be appended to very efficiently, in amortized constant time. If you need to shrink and grow your list time-efficiently and without hassle, they are the way to go. But they use a lot more space than C arrays, in part because each item in the list requires the construction of an individual Python object, even for data that could be represented with simple C types (e.g. float or uint64_t).

The array.array type, on the other hand, is just a thin wrapper on C arrays. It can hold only homogeneous data (that is to say, all of the same type) and so it uses only sizeof(one object) * length bytes of memory. Mostly, you should use it when you need to expose a C array to an extension or a system call (for example, ioctl or fctnl).

array.array is also a reasonable way to represent a mutable string in Python 2.x (array('B', bytes)). However, Python 2.6+ and 3.x offer a mutable byte string as bytearray.

However, if you want to do math on a homogeneous array of numeric data, then you're much better off using NumPy, which can automatically vectorize operations on complex multi-dimensional arrays.

To make a long story short: array.array is useful when you need a homogeneous C array of data for reasons other than doing math.

Return value from nested function in Javascript

you have to call a function before it can return anything.

function mainFunction() {
      function subFunction() {
            var str = "foo";
            return str;
      }
      return subFunction();
}

var test = mainFunction();
alert(test);

Or:

function mainFunction() {
      function subFunction() {
            var str = "foo";
            return str;
      }
      return subFunction;
}

var test = mainFunction();
alert( test() );

for your actual code. The return should be outside, in the main function. The callback is called somewhere inside the getLocations method and hence its return value is not recieved inside your main function.

function reverseGeocode(latitude,longitude){
    var address = "";
    var country = "";
    var countrycode = "";
    var locality = "";

    var geocoder = new GClientGeocoder();
    var latlng = new GLatLng(latitude, longitude);

    geocoder.getLocations(latlng, function(addresses) {
     address = addresses.Placemark[0].address;
     country = addresses.Placemark[0].AddressDetails.Country.CountryName;
     countrycode = addresses.Placemark[0].AddressDetails.Country.CountryNameCode;
     locality = addresses.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
    });   
    return country
   }

How do I dynamically set HTML5 data- attributes using react?

Note - if you want to pass a data attribute to a React Component, you need to handle them a little differently than other props.

2 options

Don't use camel case

<Option data-img-src='value' ... />

And then in the component, because of the dashes, you need to refer to the prop in quotes.

// @flow
class Option extends React.Component {

  props: {
    'data-img-src': string
  }

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props['data-img-src']} >...</option>
    )
  }
}

Or use camel case

<Option dataImgSrc='value' ... />

And then in the component, you need to convert.

// @flow
class Option extends React.Component {

  props: {
    dataImgSrc: string
  }

And when you refer to it later, you don't use the dot syntax

  render () {
    return (
      <option data-img-src={this.props.dataImgSrc} >...</option>
    )
  }
}

Mainly just realize data- attributes and aria- attributes are treated specially. You are allowed to use hyphens in the attribute name in those two cases.

Convert String array to ArrayList

String[] words= new String[]{"ace","boom","crew","dog","eon"};
List<String> wordList = Arrays.asList(words);

Get the Id of current table row with Jquery

First, your jQuery will not work at all unless you enclose all your trs and tds in a table:

<table>
    <tr>...</tr>
    ...
</table>

Second, your code gets the id of the first tr of the page, since you select all the trs of the page and get the id of the first one (.attr() returns the attribute of the first element in the set of elements it is used on)

Your current code:

  $('input[type=button]' ).click(function() {
   bid = (this.id) ; // button ID 
   trid = $('tr').attr('id'); // ID of the the first TR on the page
                              // $('tr') selects all trs in the DOM
  });

trid is always TEST1 (jsFiddle)


Instead of selecting all trs on the page with $('tr'), you want to select the first ancestor of the clicked upon input that is a tr. Use .closest() for this in the form $(this).closest('tr').

You can reference the clicked on element as this, make a jQuery object out of it with the form $(this), so you have access to all the jQuery methods on it.

What your code should look like:

  // On DOM ready...
$(function() {

      $('input[type=button]' ).click(function() {

          var bid, trid; // Declare variables. If you don't use var 
                         // you will bind bid and trid 
                         // to the window, since you make them global variables.

          bid = (this.id) ; // button ID 

          trid = $(this).closest('tr').attr('id'); // table row ID 
      });
});

jsFiddle example

Multiple submit buttons on HTML form – designate one button as default

The first button is always the default; it can't be changed. Whilst you can try to fix it up with JavaScript, the form will behave unexpectedly in a browser without scripting, and there are some usability/accessibility corner cases to think about. For example, the code linked to by Zoran will accidentally submit the form on Enter press in a <input type="button">, which wouldn't normally happen, and won't catch IE's behaviour of submitting the form for Enter press on other non-field content in the form. So if you click on some text in a <p> in the form with that script and press Enter, the wrong button will be submitted... especially dangerous if, as given in that example, the real default button is ‘Delete’!

My advice would be to forget about using scripting hacks to reassign defaultness. Go with the flow of the browser and just put the default button first. If you can't hack the layout to give you the on-screen order you want, then you can do it by having a dummy invisible button first in the source, with the same name/value as the button you want to be default:

<input type="submit" class="defaultsink" name="COMMAND" value="Save" />

.defaultsink {
    position: absolute; left: -100%;
}

(note: positioning is used to push the button off-screen because display: none and visibility: hidden have browser-variable side-effects on whether the button is taken as default and whether it's submitted.)

Allow only numbers and dot in script

This works best for me.

I also apply a currency formatter on blur where the decimal part is rounded at 2 digits just in case after validating with parseFloat.

The functions that get and set the cursor position are from Vishal Monpara's blog. I also do some nice stuff on focus with those functions. You can easily remove 2 blocks of code where 2 decimals are forced if you want and get rid of the set/get caret functions.

<html>
<body>
<input type="text" size="30" maxlength="30" onkeypress="return numericValidation(this,event);" />
<script language="JavaScript">
    function numericValidation(obj,evt) {
        var e = event || evt; // for trans-browser compatibility

        var charCode = e.which || e.keyCode;        

        if (charCode == 46) { //one dot
            if (obj.value.indexOf(".") > -1)
                return false;
            else {
                //---if the dot is positioned in the middle give the user a surprise, remember: just 2 decimals allowed
                var idx = doGetCaretPosition(obj);
                var part1 = obj.value.substr(0,idx),
                    part2 = obj.value.substring(idx);

                if (part2.length > 2) {
                    obj.value = part1 + "." + part2.substr(0,2);
                    setCaretPosition(obj, idx + 1);
                    return false;
                }//---

                //allow one dot if not cheating
                return true;
            }
        }
        else if (charCode > 31 && (charCode < 48 || charCode > 57)) { //just numbers
            return false;
        }

        //---just 2 decimals stubborn!
        var arr = obj.value.split(".") , pos = doGetCaretPosition(obj);

        if (arr.length == 2 && pos > arr[0].length && arr[1].length == 2)                               
            return false;
        //---

        //ok it's a number
        return true;
    }

    function doGetCaretPosition (ctrl) {
        var CaretPos = 0;   // IE Support
        if (document.selection) {
        ctrl.focus ();
            var Sel = document.selection.createRange ();
            Sel.moveStart ('character', -ctrl.value.length);
            CaretPos = Sel.text.length;
        }
        // Firefox support
        else if (ctrl.selectionStart || ctrl.selectionStart == '0')
            CaretPos = ctrl.selectionStart;
        return (CaretPos);
    }

    function setCaretPosition(ctrl, pos){
        if(ctrl.setSelectionRange)
        {
            ctrl.focus();
            ctrl.setSelectionRange(pos,pos);
        }
        else if (ctrl.createTextRange) {
            var range = ctrl.createTextRange();
            range.collapse(true);
            range.moveEnd('character', pos);
            range.moveStart('character', pos);
            range.select();
        }
    }
</script>
</body>
</html>

How to enter in a Docker container already running with a new TTY

First step get container id:

docker ps

This will show you something like

CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES

1170fe9e9460 localhost:5000/python:env-7e847468c4d73a0f35e9c5164046ad88 "./run_notebook.sh" 26 seconds ago Up 25 seconds 0.0.0.0:8989->9999/tcp SLURM_TASK-303337_0

1170fe9e9460 is the container id in this case.

Second, enter the docker :

docker exec -it [container_id] bash

so in the above case: docker exec -it 1170fe9e9460 bash

Defining TypeScript callback type

Here is an example - accepting no parameters and returning nothing.

class CallbackTest
{
    public myCallback: {(): void;};

    public doWork(): void
    {
        //doing some work...
        this.myCallback(); //calling callback
    }
}

var test = new CallbackTest();
test.myCallback = () => alert("done");
test.doWork();

If you want to accept a parameter, you can add that too:

public myCallback: {(msg: string): void;};

And if you want to return a value, you can add that also:

public myCallback: {(msg: string): number;};

Difference between Divide and Conquer Algo and Dynamic Programming

Divide and Conquer involves three steps at each level of recursion:

  1. Divide the problem into subproblems.
  2. Conquer the subproblems by solving them recursively.
  3. Combine the solution for subproblems into the solution for original problem.
    • It is a top-down approach.
    • It does more work on subproblems and hence has more time consumption.
    • eg. n-th term of Fibonacci series can be computed in O(2^n) time complexity.

Dynamic Programming involves the following four steps:

1. Characterise the structure of optimal solutions.
2. Recursively define the values of optimal solutions.
3. Compute the value of optimal solutions.
4. Construct an Optimal Solution from computed information.

  • It is a Bottom-up approach.
  • Less time consumption than divide and conquer since we make use of the values computed earlier, rather than computing again.
  • eg. n-th term of Fibonacci series can be computed in O(n) time complexity.

For easier understanding, lets see divide and conquer as a brute force solution and its optimisation as dynamic programming.

N.B. divide and conquer algorithms with overlapping subproblems can only be optimised with dp.

How to sort Map values by key in Java?

Just in case you don't wanna use a TreeMap

public static Map<Integer, Integer> sortByKey(Map<Integer, Integer> map) {
        List<Map.Entry<Integer, Integer>> list = new ArrayList<>(map.entrySet());
        list.sort(Comparator.comparingInt(Map.Entry::getKey));
        Map<Integer, Integer> sortedMap = new LinkedHashMap<>();
        list.forEach(e -> sortedMap.put(e.getKey(), e.getValue()));
        return sortedMap;
    }

Also, in-case you wanted to sort your map on the basis of values just change Map.Entry::getKey to Map.Entry::getValue

static files with express.js

use below inside your app.js

app.use(express.static('folderName'));

(folderName is folder which has files) - remember these assets are accessed direct through server path (i.e. http://localhost:3000/abc.png (where as abc.png is inside folderName folder)

Can I make a phone call from HTML on Android?

I have just written an app which can make a call from a web page - I don't know if this is any use to you, but I include anyway:

in your onCreate you'll need to use a webview and assign a WebViewClient, as below:

browser = (WebView) findViewById(R.id.webkit);
browser.setWebViewClient(new InternalWebViewClient());

then handle the click on a phone number like this:

private class InternalWebViewClient extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
         if (url.indexOf("tel:") > -1) {
            startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
}

Let me know if you need more pointers.

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

From documentation:

To comply with the SQL standard, IN returns NULL not only if the expression on the left hand side is NULL, but also if no match is found in the list and one of the expressions in the list is NULL.

This is exactly your case.

Both IN and NOT IN return NULL which is not an acceptable condition for WHERE clause.

Rewrite your query as follows:

SELECT  *
FROM    match m
WHERE   NOT EXISTS
        (
        SELECT  1
        FROM    email e
        WHERE   e.id = m.id
        )

How to make Python speak

Please note that this only work with python 2.x

You should try using the PyTTSx package since PyTTS is outdated. PyTTSx works with the lastest python version.

http://pypi.python.org/pypi/pyttsx/1.0 -> The package

Hope it helps

XML Serialize generic list of serializable objects

Below is a Util class in my project:

namespace Utils
{
    public static class SerializeUtil
    {
        public static void SerializeToFormatter<F>(object obj, string path) where F : IFormatter, new()
        {
            if (obj == null)
            {
                throw new NullReferenceException("obj Cannot be Null.");
            }

            if (obj.GetType().IsSerializable == false)
            {
                //  throw new 
            }
            IFormatter f = new F();
            SerializeToFormatter(obj, path, f);
        }

        public static T DeserializeFromFormatter<T, F>(string path) where F : IFormatter, new()
        {
            T t;
            IFormatter f = new F();
            using (FileStream fs = File.OpenRead(path))
            {
                t = (T)f.Deserialize(fs);
            }
            return t;
        }

        public static void SerializeToXML<T>(string path, object obj)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            using (FileStream fs = File.Create(path))
            {
                xs.Serialize(fs, obj);
            }
        }

        public static T DeserializeFromXML<T>(string path)
        {
            XmlSerializer xs = new XmlSerializer(typeof(T));
            using (FileStream fs = File.OpenRead(path))
            {
                return (T)xs.Deserialize(fs);
            }
        }

        public static T DeserializeFromXml<T>(string xml)
        {
            T result;

            var ser = new XmlSerializer(typeof(T));
            using (var tr = new StringReader(xml))
            {
                result = (T)ser.Deserialize(tr);
            }
            return result;
        }


        private static void SerializeToFormatter(object obj, string path, IFormatter formatter)
        {
            using (FileStream fs = File.Create(path))
            {
                formatter.Serialize(fs, obj);
            }
        }
    }
}

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

AngularJS - convert dates in controller

i suggest in Javascript:

var item=1387843200000;
var date1=new Date(item);

and then date1 is a Date.

How to compile the finished C# project and then run outside Visual Studio?

Compile the Release version as .exe file, then just copy onto a machine with a suitable version of .NET Framework installed and run it there. The .exe file is located in the bin\Release subfolder of the project folder.

Changing fonts in ggplot2

A simple answer if you don't want to install anything new

To change all the fonts in your plot plot + theme(text=element_text(family="mono")) Where mono is your chosen font.

List of default font options:

  • mono
  • sans
  • serif
  • Courier
  • Helvetica
  • Times
  • AvantGarde
  • Bookman
  • Helvetica-Narrow
  • NewCenturySchoolbook
  • Palatino
  • URWGothic
  • URWBookman
  • NimbusMon
  • URWHelvetica
  • NimbusSan
  • NimbusSanCond
  • CenturySch
  • URWPalladio
  • URWTimes
  • NimbusRom

R doesn't have great font coverage and, as Mike Wise points out, R uses different names for common fonts.

This page goes through the default fonts in detail.

How to use SVG markers in Google Maps API v3

You need to pass optimized: false.

E.g.

var img = { url: 'img/puff.svg', scaledSide: new google.maps.Size(5, 5) };
new google.maps.Marker({position: this.mapOptions.center, map: this.map, icon: img, optimized: false,});

Without passing optimized: false, my svg appeared as a static image.

Binding an enum to a WinForms combo box, and then setting it

Old question perhaps here but I had the issue and the solution was easy and simple, I found this http://www.c-sharpcorner.com/UploadFile/mahesh/1220/

It makes use of the databining and works nicely so check it out.

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

In my case, there was no process to kill.

Updating docker fixed the problem.

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

Hope you are using Python 3 , Str are unicode by default, so please Replace Unicode function with String Str function.

if isinstance(unicode_or_str, str):    ##Replaces with str
    text = unicode_or_str
    decoded = False

How do you obtain a Drawable object from a resource id in android package?

best way is

 button.setBackgroundResource(android.R.drawable.ic_delete);

OR this for Drawable left and something like that for right etc.

int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);

and

getResources().getDrawable() is now deprecated

How to hide scrollbar in Firefox?

I used this and it worked. https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-width

html {
scrollbar-width: none;
}

Note: User Agents must apply any scrollbar-width value set on the root element to the viewport.

String to list in Python

You can use the split() function, which returns a list, to separate them.

letters = 'QH QD JC KD JS'

letters_list = letters.split()

Printing letters_list would now format it like this:

['QH', 'QD', 'JC', 'KD', 'JS']

Now you have a list that you can work with, just like you would with any other list. For example accessing elements based on indexes:

print(letters_list[2])

This would print the third element of your list, which is 'JC'

How can you search Google Programmatically Java API

Just an alternative. Searching google and parsing the results can also be done in a generic way using any HTML Parser such as Jsoup in Java. Following is the link to the mentioned example.

Update: Link no longer works. Please look for any other example. https://www.codeforeach.com/java/example-how-to-search-google-using-java

How do I parse a URL query parameters, in Javascript?

Today (2.5 years after this answer) you can safely use Array.forEach. As @ricosrealm suggests, decodeURIComponent was used in this function.

function getJsonFromUrl(url) {
  if(!url) url = location.search;
  var query = url.substr(1);
  var result = {};
  query.split("&").forEach(function(part) {
    var item = part.split("=");
    result[item[0]] = decodeURIComponent(item[1]);
  });
  return result;
}

actually it's not that simple, see the peer-review in the comments, especially:

  • hash based routing (@cmfolio)
  • array parameters (@user2368055)
  • proper use of decodeURIComponent and non-encoded = (@AndrewF)
  • non-encoded + (added by me)

For further details, see MDN article and RFC 3986.

Maybe this should go to codereview SE, but here is safer and regexp-free code:

function getJsonFromUrl(url) {
  if(!url) url = location.href;
  var question = url.indexOf("?");
  var hash = url.indexOf("#");
  if(hash==-1 && question==-1) return {};
  if(hash==-1) hash = url.length;
  var query = question==-1 || hash==question+1 ? url.substring(hash) : 
  url.substring(question+1,hash);
  var result = {};
  query.split("&").forEach(function(part) {
    if(!part) return;
    part = part.split("+").join(" "); // replace every + with space, regexp-free version
    var eq = part.indexOf("=");
    var key = eq>-1 ? part.substr(0,eq) : part;
    var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
    var from = key.indexOf("[");
    if(from==-1) result[decodeURIComponent(key)] = val;
    else {
      var to = key.indexOf("]",from);
      var index = decodeURIComponent(key.substring(from+1,to));
      key = decodeURIComponent(key.substring(0,from));
      if(!result[key]) result[key] = [];
      if(!index) result[key].push(val);
      else result[key][index] = val;
    }
  });
  return result;
}

This function can parse even URLs like

var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a",  "c",  "[x]":"b"]}

var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
  console.log(key,":",obj[key]);
}
/*
  0 : a a
  1 : c
  [x] : b
*/

How do I find an element that contains specific text in Selenium WebDriver (Python)?

Interestingly virtually all answers revolve around XPath's function contains(), neglecting the fact it is case sensitive - contrary to the OP's ask.

If you need case insensitivity, that is achievable in XPath 1.0 (the version contemporary browsers support), though it's not pretty - by using the translate() function. It substitutes a source character to its desired form, by using a translation table.

Constructing a table of all upper case characters will effectively transform the node's text to its lower() form - allowing case-insensitive matching (here's just the prerogative):

[
  contains(
    translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz'),
    'my button'
  )
]
# will match a source text like "mY bUTTon"

The full Python call:

driver.find_elements_by_xpath("//*[contains(translate(text(), 'ABCDEFGHIJKLMNOPQRSTUVWXYZ?', 'abcdefghijklmnopqrstuvwxyz?'), 'my button')]")

Naturally this approach has its drawbacks - as given, it'll work only for Latin text; if you want to cover Unicode characters - you'll have to add them to the translation table. I've done that in the sample above - the last character is the Cyrillic symbol "?".


And if we lived in a world where browsers supported XPath 2.0 and up (, but not happening any time soon ??), we could having used the functions lower-case() (yet, not fully locale-aware), and matches (for regex searches, with the case-insensitive ('i') flag).

How can I use a C++ library from node.js?

You can use a node.js extension to provide bindings for your C++ code. Here is one tutorial that covers that:

http://syskall.com/how-to-write-your-own-native-nodejs-extension

android pinch zoom

There is also this project that does the job and worked perfectly for me: https://github.com/chrisbanes/PhotoView

Create thumbnail image

Here is a version based on the accepted answer. It fixes two problems...

  1. Improper disposing of the images.
  2. Maintaining the aspect ratio of the image.

I found this tool to be fast and effective for both JPG and PNG files.

private static FileInfo CreateThumbnailImage(string imageFileName, string thumbnailFileName)
{
    const int thumbnailSize = 150;
    using (var image = Image.FromFile(imageFileName))
    {
        var imageHeight = image.Height;
        var imageWidth = image.Width;
        if (imageHeight > imageWidth)
        {
            imageWidth = (int) (((float) imageWidth / (float) imageHeight) * thumbnailSize);
            imageHeight = thumbnailSize;
        }
        else
        {
            imageHeight = (int) (((float) imageHeight / (float) imageWidth) * thumbnailSize);
            imageWidth = thumbnailSize;
        }

        using (var thumb = image.GetThumbnailImage(imageWidth, imageHeight, () => false, IntPtr.Zero))
            //Save off the new thumbnail
            thumb.Save(thumbnailFileName);
    }

    return new FileInfo(thumbnailFileName);
}

Using JavaScript to display a Blob

If you want to use fetch instead:

var myImage = document.querySelector('img');

fetch('flowers.jpg').then(function(response) {
  return response.blob();
}).then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
});

Source:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Executing a command stored in a variable from PowerShell

Here is yet another way without Invoke-Expression but with two variables (command:string and parameters:array). It works fine for me. Assume 7z.exe is in the system path.

$cmd = '7z.exe'
$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'

& $cmd $prm

If the command is known (7z.exe) and only parameters are variable then this will do

$prm = 'a', '-tzip', 'c:\temp\with space\test1.zip', 'C:\TEMP\with space\changelog'

& 7z.exe $prm

BTW, Invoke-Expression with one parameter works for me, too, e.g. this works

$cmd = '& 7z.exe a -tzip "c:\temp\with space\test2.zip" "C:\TEMP\with space\changelog"'

Invoke-Expression $cmd

P.S. I usually prefer the way with a parameter array because it is easier to compose programmatically than to build an expression for Invoke-Expression.

What's the difference between "Layers" and "Tiers"?

Yes my dear friends said correctly. Layer is a logical partition of application whereas tier is physical partition of system tier partition is depends on layer partition. Just like an application execute on single machine but it follows 3 layered architecture, so we can say that layer architecture could be exist in a tier architecture. In simple term 3 layer architecture can implement in single machine then we can say that its is 1 tier architecture. If we implement each layer on separate machine then its called 3 tier architecture. A layer may also able to run several tier. In layer architecture related component to communicate to each other easily.
Just like we follow given below architecture

  1. presentation layer
  2. business logic layer
  3. data access layer

A client could interact to "presentation layer", but they access public component of below layer's (like business logic layer's public component) to "business logic layer" due to security reason.
Q * why we use layer architecture ? because if we implement layer architecture then we increase our applications efficiency like

==>security

==>manageability

==>scalability

other need like after developing application we need to change dbms or modify business logic etc. then it is necessary to all.

Q * why we use tier architecture?

because physically implementation of each layer gives a better efficiency ,without layer architecture we can not implement tier architecture. separate machine to implement separate tier and separate tier is implement one or more layer that's why we use it.
it uses for the purposes of fault tolerance. ==>easy to maintain.

Simple example

Just like a bank open in a chamber, in which categories the employee:

  1. gate keeper
  2. a person for cash
  3. a person who is responsible to introduce banking scheme
  4. manager

they all are the related components of system.

If we going to bank for loan purpose then first a gate keeper open the door with smile after that we goes to near a person that introduce to all scheme of loan after that we goes to manager cabin and pass the loan. After that finally we goes to cashier's counter take loan. These are layer architecture of bank.

What about tier? A bank's branch open in a town, after that in another town, after that in another but what is the basic requirement of each branch

  1. gate keeper
  2. a person for cash
  3. a person who is responsible to introduce banking scheme
  4. manager

exactly the same concept of layer and tier.

How to change the icon of .bat file programmatically?

You can just create a shortcut and then right click on it -> properties -> change icon, and just browse for your desired icon. Hope this help.

To set an icon of a shortcut programmatically, see this article using SetIconLocation:

How Can I Change the Icon for an Existing Shortcut?:

https://devblogs.microsoft.com/scripting/how-can-i-change-the-icon-for-an-existing-shortcut/

Const DESKTOP = &H10&
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(DESKTOP)
Set objFolderItem = objFolder.ParseName("Test Shortcut.lnk")
Set objShortcut = objFolderItem.GetLink
objShortcut.SetIconLocation "C:\Windows\System32\SHELL32.dll", 13
objShortcut.Save

The difference in months between dates in MySQL

This depends on how you want the # of months to be defined. Answer this questions: 'What is difference in months: Feb 15, 2008 - Mar 12, 2009'. Is it defined by clear cut # of days which depends on leap years- what month it is, or same day of previous month = 1 month.

A calculation for Days:

Feb 15 -> 29 (leap year) = 14 Mar 1, 2008 + 365 = Mar 1, 2009. Mar 1 -> Mar 12 = 12 days. 14 + 365 + 12 = 391 days. Total = 391 days / (avg days in month = 30) = 13.03333

A calculation of months:

Feb 15 2008 - Feb 15 2009 = 12 Feb 15 -> Mar 12 = less than 1 month Total = 12 months, or 13 if feb 15 - mar 12 is considered 'the past month'

Convert wchar_t to char

You are looking for wctomb(): it's in the ANSI standard, so you can count on it. It works even when the wchar_t uses a code above 255. You almost certainly do not want to use it.


wchar_t is an integral type, so your compiler won't complain if you actually do:

char x = (char)wc;

but because it's an integral type, there's absolutely no reason to do this. If you accidentally read Herbert Schildt's C: The Complete Reference, or any C book based on it, then you're completely and grossly misinformed. Characters should be of type int or better. That means you should be writing this:

int x = getchar();

and not this:

char x = getchar(); /* <- WRONG! */

As far as integral types go, char is worthless. You shouldn't make functions that take parameters of type char, and you should not create temporary variables of type char, and the same advice goes for wchar_t as well.

char* may be a convenient typedef for a character string, but it is a novice mistake to think of this as an "array of characters" or a "pointer to an array of characters" - despite what the cdecl tool says. Treating it as an actual array of characters with nonsense like this:

for(int i = 0; s[i]; ++i) {
  wchar_t wc = s[i];
  char c = doit(wc);
  out[i] = c;
}

is absurdly wrong. It will not do what you want; it will break in subtle and serious ways, behave differently on different platforms, and you will most certainly confuse the hell out of your users. If you see this, you are trying to reimplement wctombs() which is part of ANSI C already, but it's still wrong.

You're really looking for iconv(), which converts a character string from one encoding (even if it's packed into a wchar_t array), into a character string of another encoding.

Now go read this, to learn what's wrong with iconv.

Difference between Visibility.Collapsed and Visibility.Hidden

Even though a bit old thread, for those who still looking for the differences:

Aside from layout (space) taken in Hidden and not taken in Collapsed, there is another difference.

If we have custom controls inside this 'Collapsed' main control, the next time we set it to Visible, it will "load" all custom controls. It will not pre-load when window is started.

As for 'Hidden', it will load all custom controls + main control which we set as hidden when the "window" is started.

EOL conversion in notepad ++

Depending on your project, you might want to consider using EditorConfig (https://editorconfig.org/). There's a Notepad++ plugin which will load an .editorconfig where you can specify "lf" as the mandatory line ending.

I've only started using it, but it's nice so far, and open source projects I've worked on have included .editorconfig files for years. The "EOL Conversion" setting isn't changed, so it can be a bit confusing, but if you "View > Show Symbol > Show End of Line", you can see that it's adding LF instead of CRLF, even when "EOL Conversion" and the lower bottom corner shows something else (e.g. Windows (CR LF)).

Does it matter what extension is used for SQLite database files?

SQLite doesn't define any particular extension for this, it's your own choice. Personally, I name them with the .sqlite extension, just so there isn't any ambiguity when I'm looking at my files later.

FileProvider - IllegalArgumentException: Failed to find configured root

This confusing me a bit too.

The problem is on "path" attribute in your xml file.

From this document FileProvider 'path' is a subdirectory, but in another document (camera/photobasics) shown 'path' is full path.

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path name="my_images" path="Android/data/com.example.package.name/files/Pictures" />
</paths>

I just change this 'path' to full path and it just work.

Creating a batch file, for simple javac and java command execution

I've also faced a similar situation where I needed a script which can take care of javac and then java(ing) my java program. So, I came up with this BATCH script.

::  @author Rudhin Menon
::  Created on 09/06/2015
::
::  Auto-Concrete is a build tool, which monitor the file under
::  scrutiny for any changes, and compiles or runs the same once
::  it got changed.
::  
::  ========================================
::  md5sum and gawk programs are prerequisites for this script.
::  Please download them before running auto-concrete.
::  ========================================
::  
::  Happy coding ...

@echo off

:: if filename is missing
if [%1] EQU [] goto usage_message

:: Set cmd window name
title Auto-Concrete v0.2

cd versions

if %errorlevel% NEQ 0 (
    echo creating versions directory
    mkdir versions
    cd versions
)

cd ..

javac "%1"

:loop
    :: Get OLD HASH of file
    md5sum "%1" | gawk '{print $1}' > old
    set /p oldHash=<old
    copy "%1" "versions\%oldHash%.java"

    :inner_loop
    :: Get NEW HASH of the same file
    md5sum "%1" | gawk '{print $1}' > new
    set /p newHash=<new

    :: While OLD HASH and NEW HASH are the same
    :: keep comparing OLD HASH and NEW HASH
    if "%newHash%" EQU "%oldHash%" (
        :: Take rest before proceeding
        ping -w 200 0.0.0.0 >nul
        goto inner_loop
    )

    :: Once they differ, compile the source file
    :: and repeat everything again
    echo.
    echo ========= %1 changed on %DATE% at %TIME% ===========
    echo.       
    javac "%1"
goto loop

:usage_message
echo Usage : auto-concrete FILENAME.java

Above batch script will check the file for any changes and compile if any changes are done, you can tweak it for compiling whenever you want. Happy coding :)

Close Window from ViewModel

My proffered way is Declare event in ViewModel and use blend InvokeMethodAction as below.

Sample ViewModel

public class MainWindowViewModel : BindableBase, ICloseable
{
    public DelegateCommand SomeCommand { get; private set; }
    #region ICloseable Implementation
    public event EventHandler CloseRequested;        

    public void RaiseCloseNotification()
    {
        var handler = CloseRequested;
        if (handler != null)
        {
            handler.Invoke(this, EventArgs.Empty);
        }
    }
    #endregion

    public MainWindowViewModel()
    {
        SomeCommand = new DelegateCommand(() =>
        {
            //when you decide to close window
            RaiseCloseNotification();
        });
    }
}

I Closeable interface is as below but don't require to perform this action. ICloseable will help in creating generic view service, so if you construct view and ViewModel by dependency injection then what you can do is

internal interface ICloseable
{
    event EventHandler CloseRequested;
}

Use of ICloseable

var viewModel = new MainWindowViewModel();
        // As service is generic and don't know whether it can request close event
        var window = new Window() { Content = new MainView() };
        var closeable = viewModel as ICloseable;
        if (closeable != null)
        {
            closeable.CloseRequested += (s, e) => window.Close();
        }

And Below is Xaml, You can use this xaml even if you don't implement interface, it will only need your view model to raise CloseRquested.

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPFRx"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" 
xmlns:ViewModels="clr-namespace:WPFRx.ViewModels" x:Name="window" x:Class="WPFRx.MainWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525" 
d:DataContext="{d:DesignInstance {x:Type ViewModels:MainWindowViewModel}}">

<i:Interaction.Triggers>
    <i:EventTrigger SourceObject="{Binding Mode=OneWay}" EventName="CloseRequested" >
        <ei:CallMethodAction TargetObject="{Binding ElementName=window}" MethodName="Close"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

<Grid>
    <Button Content="Some Content" Command="{Binding SomeCommand}" Width="100" Height="25"/>
</Grid>

What do the crossed style properties in Google Chrome devtools mean?

There is some cases when you copy and paste the CSS code in somewhere and it breaks the format so Chrome show the yellow warning. You should try to reformat the CSS code again and it should be fine.

Why does the 260 character path length limit exist in Windows?

One way to cope with the path limit is to shorten path entries with symbolic links.

For example:

  1. create a C:\p directory to keep short links to long paths
  2. mklink /J C:\p\foo C:\Some\Crazy\Long\Path\foo
  3. add C:\p\foo to your path instead of the long path

Validating IPv4 addresses with regexp

You've already got a working answer but just in case you are curious what was wrong with your original approach, the answer is that you need parentheses around your alternation otherwise the (\.|$) is only required if the number is less than 200.

'\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b'
    ^                                    ^

How to add a right button to a UINavigationController?

Just copy and paste this Objective-C code.

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self addRightBarButtonItem];
}
- (void) addRightBarButtonItem {
    UIButton *btnAddContact = [UIButton buttonWithType:UIButtonTypeContactAdd];
    [btnAddContact addTarget:self action:@selector(addCustomerPressed:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithCustomView:btnAddContact];
    self.navigationItem.rightBarButtonItem = barButton;
}

#pragma mark - UIButton
- (IBAction)addCustomerPressed:(id)sender {
// Your right button pressed event
}

django - get() returned more than one topic

I had same problem and solution was obj = ClassName.objects.filter()

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

Here you go: No synchronous tasks.

No synchronous tasks

Synchronous tasks are no longer supported. They often led to subtle mistakes that were hard to debug, like forgetting to return your streams from a task.

When you see the Did you forget to signal async completion? warning, none of the techniques mentioned above were used. You'll need to use the error-first callback or return a stream, promise, event emitter, child process, or observable to resolve the issue.

Using async/await

When not using any of the previous options, you can define your task as an async function, which wraps your task in a promise. This allows you to work with promises synchronously using await and use other synchronous code.

const fs = require('fs');

async function asyncAwaitTask() {
  const { version } = fs.readFileSync('package.json');
  console.log(version);
  await Promise.resolve('some result');
}

exports.default = asyncAwaitTask;

How a thread should close itself in Java?

If the run method ends, the thread will end.

If you use a loop, a proper way is like following:

// In your imlemented Runnable class:
private volatile boolean running = true;

public void run()
{
   while (running)
   {
      ...
   }
}


public void stopRunning()
{
    running = false;
}

Of course returning is the best way.

Java Programming: call an exe from Java and passing parameters

Below works for me if your exe depend on some dll or certain dependency then you need to set directory path. As mention below exePath mean folder where exe placed along with it's references files.

Exe application creating any temporaray file so it will create in folder mention in processBuilder.directory(...)

**

ProcessBuilder processBuilder = new ProcessBuilder(arguments);
processBuilder.redirectOutput(Redirect.PIPE);
processBuilder.directory(new File(exePath));
process = processBuilder.start();
int waitFlag = process.waitFor();// Wait to finish application execution.
if (waitFlag == 0) {
...
 int returnVal = process.exitValue();
} 

**

How do I make a Docker container start automatically on system boot?

More "gentle" mode from the documentation:

docker run -dit --restart unless-stopped <image_name>

Check if string contains only letters in javascript

Try this

var Regex='/^[^a-zA-Z]*$/';

 if(Regex.test(word))
 {
 //...
 }

I think it will be working for you.

Remove all the children DOM elements in div

while (node.hasChildNodes()) {
    node.removeChild(node.lastChild);
}

Add custom headers to WebView resource requests - android

As mentioned before, you can do this:

 WebView  host = (WebView)this.findViewById(R.id.webView);
 String url = "<yoururladdress>";

 Map <String, String> extraHeaders = new HashMap<String, String>();
 extraHeaders.put("Authorization","Bearer"); 
 host.loadUrl(url,extraHeaders);

I tested this and on with a MVC Controller that I extended the Authorize Attribute to inspect the header and the header is there.

How to open standard Google Map application from my application?

Check this page from google :

http://developer.android.com/guide/appendix/g-app-intents.html

You can use a URI of the form

geo:latitude,longitude

to open Google map viewer and point it to a location.

When to use "new" and when not to, in C++?

New is always used to allocate dynamic memory, which then has to be freed.

By doing the first option, that memory will be automagically freed when scope is lost.

Point p1 = Point(0,0); //This is if you want to be safe and don't want to keep the memory outside this function.

Point* p2 = new Point(0, 0); //This must be freed manually. with...
delete p2;

MSOnline can't be imported on PowerShell (Connect-MsolService error)

After reviewing Microsoft's TechNet article "Azure Active Directory Cmdlets" -> section "Install the Azure AD Module", it seems that this process has been drastically simplified, thankfully.

As of 2016/06/30, in order to successfully execute the PowerShell commands Import-Module MSOnline and Connect-MsolService, you will need to install the following applications (64-bit only):

  1. Applicable Operating Systems: Windows 7 to 10
    Name: "Microsoft Online Services Sign-in Assistant for IT Professionals RTW"
    Version: 7.250.4556.0 (latest)
    Installer URL: https://www.microsoft.com/en-us/download/details.aspx?id=41950
    Installer file name: msoidcli_64.msi
  2. Applicable Operating Systems: Windows 7 to 10
    Name: "Windows Azure Active Directory Module for Windows PowerShell"
    Version: Unknown but the latest installer file's SHA-256 hash is D077CF49077EE133523C1D3AE9A4BF437D220B16D651005BBC12F7BDAD1BF313
    Installer URL: https://technet.microsoft.com/en-us/library/dn975125.aspx
    Installer file name: AdministrationConfig-en.msi
  3. Applicable Operating Systems: Windows 7 only
    Name: "Windows PowerShell 3.0"
    Version: 3.0 (later versions will probably work too)
    Installer URL: https://www.microsoft.com/en-us/download/details.aspx?id=34595
    Installer file name: Windows6.1-KB2506143-x64.msu

 

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

How do I find out which keystore was used to sign an app?

Much easier way to view the signing certificate:

jarsigner.exe -verbose -verify -certs myapk.apk

This will only show the DN, so if you have two certs with the same DN, you might have to compare by fingerprint.

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

Unfortunately there is currently no designer support (unlike for SQL Server 2005) for building relationships between tables in SQL Server CE. To build relationships you need to use SQL commands such as:

ALTER TABLE Orders
ADD CONSTRAINT FK_Customer_Order
FOREIGN KEY (CustomerId) REFERENCES Customers(CustomerId)

If you are doing CE development, i would recomend this FAQ:

EDIT: In Visual Studio 2008 this is now possible to do in the GUI by right-clicking on your table.

Custom HTTP headers : naming conventions

The question bears re-reading. The actual question asked is not similar to vendor prefixes in CSS properties, where future-proofing and thinking about vendor support and official standards is appropriate. The actual question asked is more akin to choosing URL query parameter names. Nobody should care what they are. But name-spacing the custom ones is a perfectly valid -- and common, and correct -- thing to do.

Rationale:
It is about conventions among developers for custom, application-specific headers -- "data relevant to their account" -- which have nothing to do with vendors, standards bodies, or protocols to be implemented by third parties, except that the developer in question simply needs to avoid header names that may have other intended use by servers, proxies or clients. For this reason, the "X-Gzip/Gzip" and "X-Forwarded-For/Forwarded-For" examples given are moot. The question posed is about conventions in the context of a private API, akin to URL query parameter naming conventions. It's a matter of preference and name-spacing; concerns about "X-ClientDataFoo" being supported by any proxy or vendor without the "X" are clearly misplaced.

There's nothing special or magical about the "X-" prefix, but it helps to make it clear that it is a custom header. In fact, RFC-6648 et al help bolster the case for use of an "X-" prefix, because -- as vendors of HTTP clients and servers abandon the prefix -- your app-specific, private-API, personal-data-passing-mechanism is becoming even better-insulated against name-space collisions with the small number of official reserved header names. That said, my personal preference and recommendation is to go a step further and do e.g. "X-ACME-ClientDataFoo" (if your widget company is "ACME").

IMHO the IETF spec is insufficiently specific to answer the OP's question, because it fails to distinguish between completely different use cases: (A) vendors introducing new globally-applicable features like "Forwarded-For" on the one hand, vs. (B) app developers passing app-specific strings to/from client and server. The spec only concerns itself with the former, (A). The question here is whether there are conventions for (B). There are. They involve grouping the parameters together alphabetically, and separating them from the many standards-relevant headers of type (A). Using the "X-" or "X-ACME-" prefix is convenient and legitimate for (B), and does not conflict with (A). The more vendors stop using "X-" for (A), the more cleanly-distinct the (B) ones will become.

Example:
Google (who carry a bit of weight in the various standards bodies) are -- as of today, 20141102 in this slight edit to my answer -- currently using "X-Mod-Pagespeed" to indicate the version of their Apache module involved in transforming a given response. Is anyone really suggesting that Google should use "Mod-Pagespeed", without the "X-", and/or ask the IETF to bless its use?

Summary:
If you're using custom HTTP Headers (as a sometimes-appropriate alternative to cookies) within your app to pass data to/from your server, and these headers are, explicitly, NOT intended ever to be used outside the context of your application, name-spacing them with an "X-" or "X-FOO-" prefix is a reasonable, and common, convention.

Storing Images in DB - Yea or Nay?

I will go for both solution, I mean...I will develop a litle component (EJB) that store the images in a DB plus the path of this image into the server. This DB only will be updated if we have a new image or the original image it's updated. Then I will also store the path in the business DB.

From an application point of view, I will always user the file system (retrieving the path from th business DB) and by this way we will fix the backup issue, and also avoid possible performance issues.

The only weakness is that we will store the same image 2 times...the good point is that the memory is cheap, come on!.

How to read a file into vector in C++?

1. In the loop you are assigning value rather than comparing value so

i=((Main.size())-1) -> i=(-1) since Main.size()

Main[i] will yield "Vector Subscript out of Range" coz i = -1.

2. You get Main.size() as 0 maybe becuase its not it can't find the file. Give the file path and check the output. Also it would be good to initialize the variables.

Exit/save edit to sudoers file? Putty SSH

Just open file by nano /file_name

Once done, press CTRL+O and then Enter to save. Then press CTRL+X to return.

Here CTRL+O : is CTRL and O for Orange Not 0 Zero

CSS table layout: why does table-row not accept a margin?

Fiddle

 .row-seperator{
   border-top: solid transparent 50px;
 }

<table>
   <tr><td>Section 1</td></tr>
   <tr><td>row1 1</td></tr>
   <tr><td>row1 2</td></tr>
   <tr>
      <td class="row-seperator">Section 2</td>
   </tr>
   <tr><td>row2 1</td></tr>
   <tr><td>row2 2</td></tr>
</table>


#Outline
Section 1
row1 1
row1 2


Section 2
row2 1
row2 2

this can be another solution

Get product id and product type in magento?

<?php if( $_product->getTypeId() == 'simple' ): ?>
//your code for simple products only
<?php endif; ?>

<?php if( $_product->getTypeId() == 'grouped' ): ?>
//your code for grouped products only
<?php endif; ?>

So on. It works! Magento 1.6.1, place in the view.phtml

Where are shared preferences stored?

Preferences can either be set in code or can be found in res/xml/preferences.xml. You can read more about preferences on the Android SDK website.

Get the decimal part from a double

Better Way -

        double value = 10.567;
        int result = (int)((value - (int)value) * 100);
        Console.WriteLine(result);

Output -

56

Getting value of HTML Checkbox from onclick/onchange events

Use this

<input type="checkbox" onclick="onClickHandler()" id="box" />

<script>
function onClickHandler(){
    var chk=document.getElementById("box").value;

    //use this value

}
</script>

Get Value From Select Option in Angular 4

You just need to put [(ngModel)] on your select element:

<select class="form-control col-lg-8" #corporation required [(ngModel)]="selectedValue">

Finding the median of an unsorted array

The quick select algorithm can find the k-th smallest element of an array in linear (O(n)) running time. Here is an implementation in python:

import random

def partition(L, v):
    smaller = []
    bigger = []
    for val in L:
        if val < v: smaller += [val]
        if val > v: bigger += [val]
    return (smaller, [v], bigger)

def top_k(L, k):
    v = L[random.randrange(len(L))]
    (left, middle, right) = partition(L, v)
    # middle used below (in place of [v]) for clarity
    if len(left) == k:   return left
    if len(left)+1 == k: return left + middle
    if len(left) > k:    return top_k(left, k)
    return left + middle + top_k(right, k - len(left) - len(middle))

def median(L):
    n = len(L)
    l = top_k(L, n / 2 + 1)
    return max(l)

Swift: Testing optionals for nil

One option that hasn't specifically been covered is using Swift's ignored value syntax:

if let _ = xyz {
    // something that should only happen if xyz is not nil
}

I like this since checking for nil feels out of place in a modern language like Swift. I think the reason it feels out of place is that nil is basically a sentinel value. We've done away with sentinels pretty much everywhere else in modern programming so nil feels like it should go too.

Python Unicode Encode Error

Don't hardcode the character encoding of your environment inside your script; print Unicode text directly instead:

assert isinstance(text, unicode) # or str on Python 3
print(text)

If your output is redirected to a file (or a pipe); you could use PYTHONIOENCODING envvar, to specify the character encoding:

$ PYTHONIOENCODING=utf-8 python your_script.py >output.utf8

Otherwise, python your_script.py should work as is -- your locale settings are used to encode the text (on POSIX check: LC_ALL, LC_CTYPE, LANG envvars -- set LANG to a utf-8 locale if necessary).

To print Unicode on Windows, see this answer that shows how to print Unicode to Windows console, to a file, or using IDLE.

Does JavaScript have a method like "range()" to generate a range within the supplied bounds?

function check(){

    var correct=true;

    for(var i=0; i<arguments.length; i++){

    if(typeof arguments[i] != "number"){

    correct=false;  } } return correct; }   

//------------------------------------------

 function range(start,step,end){

  var correct=check(start,step,end);

  if(correct && (step && end)!=0){ 

  for(var i=start; i<=end; i+=step)

  document.write(i+" "); }

  else document.write("Not Correct Data"); }

How to create JSON string in JavaScript?

I think this way helps you...

var name=[];
var age=[];
name.push('sulfikar');
age.push('24');
var ent={};
for(var i=0;i<name.length;i++)
{
ent.name=name[i];
ent.age=age[i];
}
JSON.Stringify(ent);

Adding Table rows Dynamically in Android

Activity
    <HorizontalScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TableLayout
            android:id="@+id/mytable"
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        </TableLayout>
    </HorizontalScrollView>

Your Class

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_testtable);
    table = (TableLayout)findViewById(R.id.mytable);
    showTableLayout();
}


public  void showTableLayout(){
    Date date = new Date();
    int rows = 80;
    int colums  = 10;
    table.setStretchAllColumns(true);
    table.bringToFront();

    for(int i = 0; i < rows; i++){

        TableRow tr =  new TableRow(this);
        for(int j = 0; j < colums; j++)
        {
            TextView txtGeneric = new TextView(this);
            txtGeneric.setTextSize(18);
            txtGeneric.setText( dateFormat.format(date) + "\t\t\t\t" );
            tr.addView(txtGeneric);
            /*txtGeneric.setHeight(30); txtGeneric.setWidth(50);   txtGeneric.setTextColor(Color.BLUE);*/
        }
        table.addView(tr);
    }
}

How to get PID by process name?

To improve the Padraic's answer: when check_output returns a non-zero code, it raises a CalledProcessError. This happens when the process does not exists or is not running.

What I would do to catch this exception is:

#!/usr/bin/python

from subprocess import check_output, CalledProcessError

def getPIDs(process):
    try:
        pidlist = map(int, check_output(["pidof", process]).split())
    except  CalledProcessError:
        pidlist = []
    print 'list of PIDs = ' + ', '.join(str(e) for e in pidlist)

if __name__ == '__main__':
    getPIDs("chrome")

The output:

$ python pidproc.py
list of PIDS = 31840, 31841, 41942

Running a Python script from PHP

If you want to know the return status of the command and get the entire stdout output you can actually use exec:

$command = 'ls';
exec($command, $out, $status);

$out is an array of all lines. $status is the return status. Very useful for debugging.

If you also want to see the stderr output you can either play with proc_open or simply add 2>&1 to your $command. The latter is often sufficient to get things working and way faster to "implement".

Multiline TextBox multiple newline

I had the same problem. If I add one Environment.Newline I get one new line in the textbox. But if I add two Environment.Newline I get one new line. In my web app I use a whitespace modul that removes all unnecessary white spaces. If i disable this module I get two new lines in my textbox. Hope that helps.

How to use mongoimport to import csv

I was perplexed with a similar problem where mongoimport did not give me an error but would report importing 0 records. I had saved my file that didn't work using the OSX Excel for Mac 2011 version using the default "Save as.." "xls as csv" without specifying "Windows Comma Separated(.csv)" format specifically. After researching this site and trying the "Save As again using "Windows Comma Separated (.csv)" format, mongoimport worked fine. I think mongoimport expects a newline character on each line and the default Mac Excel 2011 csv export didn't provide that character at the end of each line.

JavaScript data grid for millions of rows

I suggest sigma grid, sigma grid has embed paging features which could support millions of rows. And also, you may need a remote paging to do it. see the demo http://www.sigmawidgets.com/products/sigma_grid2/demos/example_master_details.html

Android "elevation" not showing a shadow

If you have a view with no background this line will help you

android:outlineProvider="bounds"

If you have a view with background this line will help you

android:outlineProvider="paddedBounds"

Creating files and directories via Python

    import os
    os.mkdir('directory name') #### this command for creating directory
    os.mknod('file name') #### this for creating files
    os.system('touch filename') ###this is another method for creating file by using unix commands in os modules 

string decode utf-8

A string needs no encoding. It is simply a sequence of Unicode characters.

You need to encode when you want to turn a String into a sequence of bytes. The charset the you choose (UTF-8, cp1255, etc.) determines the Character->Byte mapping. Note that a character is not necessarily translated into a single byte. In most charsets, most Unicode characters are translated to at least two bytes.

Encoding of a String is carried out by:

String s1 = "some text";
byte[] bytes = s1.getBytes("UTF-8"); // Charset to encode into

You need to decode when you have ? sequence of bytes and you want to turn them into a String. When y?u d? that you need to specify, again, the charset with which the byt?s were originally encoded (otherwise you'll end up with garbl?d t?xt).

Decoding:

String s2 = new String(bytes, "UTF-8"); // Charset with which bytes were encoded 

If you want to understand this better, a great text is "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)"

Apache and IIS side by side (both listening to port 80) on windows2003

For people with only one IP address and multiple sites on one server, you can configure IIS to listen on a port other than 80, e.g 8080 by setting the TCP port in the properties of each of its sites (including the default one).

In Apache, enable mod_proxy and mod_proxy_http, then add a catch-all VirtualHost (after all others) so that requests Apache isn't explicitly handling get "forwarded" on to IIS.

<VirtualHost *:80>
    ServerName foo.bar
    ServerAlias *
    ProxyPreserveHost On
    ProxyPass / http://127.0.0.1:8080/
</VirtualHost>

Now you can have Apache serve some sites and IIS serve others, with no visible difference to the user.

Edit: your IIS sites must not include their port number in any URLs within their responses, including headers.

String to date in Oracle with milliseconds

I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.

What's the whole point of "localhost", hosts and ports at all?

Everyone seems to focus on the host part of your questions. Ports are used to be able to run several servers (for example for different purposes such as file sharing, web serving, printing, etc) from the same machine (one single IP address).

Inline elements shifting when made bold on hover

An alternative approach would be to "emulate" bold text via text-shadow. This has the bonus (/malus, depending on your case) to work also on font icons.

   nav li a:hover {
      text-decoration: none;
      text-shadow: 0 0 1px; /* "bold" */
   }

Kinda hacky, although it saves you from duplicating text (which is useful if it is a lot, as it was in my case).

Appending to an empty DataFrame in Pandas?

You can concat the data in this way:

InfoDF = pd.DataFrame()
tempDF = pd.DataFrame(rows,columns=['id','min_date'])

InfoDF = pd.concat([InfoDF,tempDF])

How do I call paint event?

Refresh would probably also make for much more readable code, depending on context.

How to check if a variable is set in Bash?

The answers above do not work when Bash option set -u is enabled. Also, they are not dynamic, e.g., how to test is variable with name "dummy" is defined? Try this:

is_var_defined()
{
    if [ $# -ne 1 ]
    then
        echo "Expected exactly one argument: variable name as string, e.g., 'my_var'"
        exit 1
    fi
    # Tricky.  Since Bash option 'set -u' may be enabled, we cannot directly test if a variable
    # is defined with this construct: [ ! -z "$var" ].  Instead, we must use default value
    # substitution with this construct: [ ! -z "${var:-}" ].  Normally, a default value follows the
    # operator ':-', but here we leave it blank for empty (null) string.  Finally, we need to
    # substitute the text from $1 as 'var'.  This is not allowed directly in Bash with this
    # construct: [ ! -z "${$1:-}" ].  We need to use indirection with eval operator.
    # Example: $1="var"
    # Expansion for eval operator: "[ ! -z \${$1:-} ]" -> "[ ! -z \${var:-} ]"
    # Code  execute: [ ! -z ${var:-} ]
    eval "[ ! -z \${$1:-} ]"
    return $?  # Pedantic.
}

Related: In Bash, how do I test if a variable is defined in "-u" mode

ng-repeat finish event

Here is a repeat-done directive that calls a specified function when true. I have found that the called function must use $timeout with interval=0 before doing DOM manipulation, such as initializing tooltips on the rendered elements. jsFiddle: http://jsfiddle.net/tQw6w/

In $scope.layoutDone, try commenting out the $timeout line and uncommenting the "NOT CORRECT!" line to see the difference in the tooltips.

<ul>
    <li ng-repeat="feed in feedList" repeat-done="layoutDone()" ng-cloak>
    <a href="{{feed}}" title="view at {{feed | hostName}}" data-toggle="tooltip">{{feed | strip_http}}</a>
    </li>
</ul>

JS:

angular.module('Repeat_Demo', [])

    .directive('repeatDone', function() {
        return function(scope, element, attrs) {
            if (scope.$last) { // all are rendered
                scope.$eval(attrs.repeatDone);
            }
        }
    })

    .filter('strip_http', function() {
        return function(str) {
            var http = "http://";
            return (str.indexOf(http) == 0) ? str.substr(http.length) : str;
        }
    })

    .filter('hostName', function() {
        return function(str) {
            var urlParser = document.createElement('a');
            urlParser.href = str;
            return urlParser.hostname;
        }
    })

    .controller('AppCtrl', function($scope, $timeout) {

        $scope.feedList = [
            'http://feeds.feedburner.com/TEDTalks_video',
            'http://feeds.nationalgeographic.com/ng/photography/photo-of-the-day/',
            'http://sfbay.craigslist.org/eng/index.rss',
            'http://www.slate.com/blogs/trending.fulltext.all.10.rss',
            'http://feeds.current.com/homepage/en_US.rss',
            'http://feeds.current.com/items/popular.rss',
            'http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml'
        ];

        $scope.layoutDone = function() {
            //$('a[data-toggle="tooltip"]').tooltip(); // NOT CORRECT!
            $timeout(function() { $('a[data-toggle="tooltip"]').tooltip(); }, 0); // wait...
        }

    })

Installing Numpy on 64bit Windows 7 with Python 2.7.3

Download numpy-1.9.2+mkl-cp27-none-win32.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy .

Copy the file to C:\Python27\Scripts

Run cmd from the above location and type

pip install numpy-1.9.2+mkl-cp27-none-win32.whl

You will hopefully get the below output:

Processing c:\python27\scripts\numpy-1.9.2+mkl-cp27-none-win32.whl
Installing collected packages: numpy
Successfully installed numpy-1.9.2

Hope that works for you.

EDIT 1
Adding @oneleggedmule 's suggestion:

You can also run the following command in the cmd:

pip2.7 install numpy-1.9.2+mkl-cp27-none-win_amd64.whl

Basically, writing pip alone also works perfectly (as in the original answer). Writing the version 2.7 can also be done for the sake of clarity or specification.

CSS: Truncate table cells, but fit as much as possible

The problem is the 'table-layout:fixed' which create evenly-spaced-fixed-width columns. But disabling this css-property will kill the text-overflow because the table will become as large as possible (and than there is noting to overflow).

I'm sorry but in this case Fred can't have his cake and eat it to.. unless the landlord gives Celldito less space to work with in the first place, Fred cannot use his..

Groovy String to Date

The first argument to parse() is the expected format. You have to change that to Date.parse("E MMM dd H:m:s z yyyy", testDate) for it to work. (Note you don't need to create a new Date object, it's a static method)

If you don't know in advance what format, you'll have to find a special parsing library for that. In Ruby there's a library called Chronic, but I'm not aware of a Groovy equivalent. Edit: There is a Java port of the library called jChronic, you might want to check it out.

LD_LIBRARY_PATH vs LIBRARY_PATH

Since I link with gcc why ld is being called, as the error message suggests?

gcc calls ld internally when it is in linking mode.

How to check if an email address is real or valid using PHP

You should check with SMTP.

That means you have to connect to that email's SMTP server.

After connecting to the SMTP server you should send these commands:

HELO somehostname.com
MAIL FROM: <[email protected]>
RCPT TO: <[email protected]>

If you get "<[email protected]> Relay access denied" that means this email is Invalid.

There is a simple PHP class. You can use it:

http://www.phpclasses.org/package/6650-PHP-Check-if-an-e-mail-is-valid-using-SMTP.html

Disable and later enable all table indexes in Oracle

If you're on Oracle 11g, you may also want to check out dbms_index_utl.

Convert columns to string in Pandas

Here's the other one, particularly useful to convert the multiple columns to string instead of just single column:

In [76]: import numpy as np
In [77]: import pandas as pd
In [78]: df = pd.DataFrame({
    ...:     'A': [20, 30.0, np.nan],
    ...:     'B': ["a45a", "a3", "b1"],
    ...:     'C': [10, 5, np.nan]})
    ...: 

In [79]: df.dtypes ## Current datatype
Out[79]: 
A    float64
B     object
C    float64
dtype: object

## Multiple columns string conversion
In [80]: df[["A", "C"]] = df[["A", "C"]].astype(str) 

In [81]: df.dtypes ## Updated datatype after string conversion
Out[81]: 
A    object
B    object
C    object
dtype: object

Date only from TextBoxFor()

Keep in mind that display will depend on culture. And while in most cases all other answers are correct, it did not work for me. Culture issue will also cause different problems with jQuery datepicker, if attached.

If you wish to force the format escape / in the following manner:

@Html.TextBoxFor(model => model.dtArrivalDate, "{0:MM\\/dd\\/yyyy}")

If not escaped for me it show 08-01-2010 vs. expected 08/01/2010.

Also if not escaped jQuery datepicker will select different defaultDate, in my instance it was May 10, 2012.

JBoss debugging in Eclipse

You need to define a Remote Java Application in the Eclipse debug configurations:

Open the debug configurations (select project, then open from menu run/debug configurations) Select Remote Java Application in the left tree and press "New" button On the right panel select your web app project and enter 8787 in the port field. Here is a link to a detailed description of this process.

When you start the remote debug configuration Eclipse will attach to the JBoss process. If successful the debug view will show the JBoss threads. There is also a disconnect icon in the toolbar/menu to stop remote debugging.

'Found the synthetic property @panelState. Please include either "BrowserAnimationsModule" or "NoopAnimationsModule" in your application.'

Try this

npm install @angular/animations@latest --save

import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

this works for me.

VB.Net: Dynamically Select Image from My.Resources

Dim resources As Object = My.Resources.ResourceManager
PictureBoxName.Image = resources.GetObject("Company_Logo")

Http Servlet request lose params from POST body after read it once

As an aside, an alternative way to solve this problem is to not use the filter chain and instead build your own interceptor component, perhaps using aspects, which can operate on the parsed request body. It will also likely be more efficient as you are only converting the request InputStream into your own model object once.

However, I still think it's reasonable to want to read the request body more than once particularly as the request moves through the filter chain. I would typically use filter chains for certain operations that I want to keep at the HTTP layer, decoupled from the service components.

As suggested by Will Hartung I achieved this by extending HttpServletRequestWrapper, consuming the request InputStream and essentially caching the bytes.

public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
  private ByteArrayOutputStream cachedBytes;

  public MultiReadHttpServletRequest(HttpServletRequest request) {
    super(request);
  }

  @Override
  public ServletInputStream getInputStream() throws IOException {
    if (cachedBytes == null)
      cacheInputStream();

      return new CachedServletInputStream();
  }

  @Override
  public BufferedReader getReader() throws IOException{
    return new BufferedReader(new InputStreamReader(getInputStream()));
  }

  private void cacheInputStream() throws IOException {
    /* Cache the inputstream in order to read it multiple times. For
     * convenience, I use apache.commons IOUtils
     */
    cachedBytes = new ByteArrayOutputStream();
    IOUtils.copy(super.getInputStream(), cachedBytes);
  }

  /* An inputstream which reads the cached request body */
  public class CachedServletInputStream extends ServletInputStream {
    private ByteArrayInputStream input;

    public CachedServletInputStream() {
      /* create a new input stream from the cached request body */
      input = new ByteArrayInputStream(cachedBytes.toByteArray());
    }

    @Override
    public int read() throws IOException {
      return input.read();
    }
  }
}

Now the request body can be read more than once by wrapping the original request before passing it through the filter chain:

public class MyFilter implements Filter {
  @Override
  public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

    /* wrap the request in order to read the inputstream multiple times */
    MultiReadHttpServletRequest multiReadRequest = new MultiReadHttpServletRequest((HttpServletRequest) request);

    /* here I read the inputstream and do my thing with it; when I pass the
     * wrapped request through the filter chain, the rest of the filters, and
     * request handlers may read the cached inputstream
     */
    doMyThing(multiReadRequest.getInputStream());
    //OR
    anotherUsage(multiReadRequest.getReader());
    chain.doFilter(multiReadRequest, response);
  }
}

This solution will also allow you to read the request body multiple times via the getParameterXXX methods because the underlying call is getInputStream(), which will of course read the cached request InputStream.

Edit

For newer version of ServletInputStream interface. You need to provide implementation of few more methods like isReady, setReadListener etc. Refer this question as provided in comment below.

How do I show the changes which have been staged?

For Staging Area vs Repository(last commit) comparison use

 $git diff --staged

The command compares your staged($ git add fileName) changes to your last commit. If you want to see what you’ve staged that will go into your next commit, you can use git diff --staged. This command compares your staged changes to your last commit.

For Working vs Staging comparison use

$ git diff 

The command compares what is in your working directory with what is in your staging area. It’s important to note that git diff by itself doesn’t show all changes made since your last commit — only changes that are still unstaged. If you’ve staged all of your changes($ git add fileName), git diff will give you no output.

Also, if you stage a file($ git add fileName) and then edit it, you can use git diff to see the changes in the file that are staged and the changes that are unstaged.

UnicodeEncodeError: 'charmap' codec can't encode - character maps to <undefined>, print function

I dug deeper into this and found the best solutions are here.

http://blog.notdot.net/2010/07/Getting-unicode-right-in-Python

In my case I solved "UnicodeEncodeError: 'charmap' codec can't encode character "

original code:

print("Process lines, file_name command_line %s\n"% command_line))

New code:

print("Process lines, file_name command_line %s\n"% command_line.encode('utf-8'))  

How can I comment a single line in XML?

Not orthodox, but it works for me sometimes; set your comment as another attribute:

<node usefulAttr="foo" comment="Your comment here..."/>

Warning about `$HTTP_RAW_POST_DATA` being deprecated

N.B : IF YOU ARE USING PHPSTORM enter image description here


I spent an hour trying to solve this problem, thinking that it was my php server problem, So i set 'always_populate_raw_post_data' to '-1' in php.ini and nothing worked.

Until i found out that using phpStorm built in server is what causing the problem as detailed in the answer here : Answer by LazyOne Here , So i thought about sharing it.

CSS Animation onClick

Add a

-webkit-animation-play-state: paused;

to your CSS file, then you can control whether the animation is running or not by using this JS line:

document.getElementById("myDIV").style.WebkitAnimationPlayState = "running";

if you want the animation to run once, every time you click. Remember to set

-webkit-animation-iteration-count: 1;

React won't load local images

Try changing the code in server.js to -

app.use(require('webpack-dev-middleware')(compiler, {
      noInfo: true,
      publicPath: config.output.path
    }));

Calculating the angle between the line defined by two points

A few answers here have tried to explain the "screen" issue where top left is 0,0 and bottom right is (positive) screen width, screen height. Most grids have the Y axis as positive above X not below.

The following method will work with screen values instead of "grid" values. The only difference to the excepted answer is the Y values are inverted.

/**
 * Work out the angle from the x horizontal winding anti-clockwise 
 * in screen space. 
 * 
 * The value returned from the following should be 315. 
 * <pre>
 * x,y -------------
 *     |  1,1
 *     |    \
 *     |     \
 *     |     2,2
 * </pre>
 * @param p1
 * @param p2
 * @return - a double from 0 to 360
 */
public static double angleOf(PointF p1, PointF p2) {
    // NOTE: Remember that most math has the Y axis as positive above the X.
    // However, for screens we have Y as positive below. For this reason, 
    // the Y values are inverted to get the expected results.
    final double deltaY = (p1.y - p2.y);
    final double deltaX = (p2.x - p1.x);
    final double result = Math.toDegrees(Math.atan2(deltaY, deltaX)); 
    return (result < 0) ? (360d + result) : result;
}

Select multiple columns from a table, but group by one

    WITH CTE_SUM AS (
      SELECT ProductID, Sum(OrderQuantity) AS TotalOrderQuantity 
      FROM OrderDetails GROUP BY ProductID
    )
    SELECT DISTINCT OrderDetails.ProductID, OrderDetails.ProductName, OrderDetails.OrderQuantity,CTE_SUM.TotalOrderQuantity 
    FROM 
    OrderDetails INNER JOIN CTE_SUM 
    ON OrderDetails.ProductID = CTE_SUM.ProductID

Please check if this works.

Getter and Setter?

In addition to the already great and respected answers in here, I would like to expand on PHP having no setters/getters.

PHP does not have getter and setter syntax. It provides subclassed or magic methods to allow "hooking" and overriding the property lookup process, as pointed out by Dave.

Magic allows us lazy programmers to do more with less code at a time at which we are actively engaged in a project and know it intimately, but usually at the expense of readability.

Performance Every unnecessary function, that results from forcing a getter/setter-like code-architecture in PHP, involves its own memory stack-frame upon invocation and is wasting CPU cycles.

Readability: The codebase incurs bloating code-lines, which impacts code-navigation as more LOC mean more scrolling,.

Preference: Personally, as my rule of thumb, I take the failure of static code analysis as a sign to avoid going down the magical road as long as obvious long-term benefits elude me at that time.

Fallacies:

A common argument is readability. For instance that $someobject->width is easier to read than $someobject->width(). However unlike a planet's circumference or width, which can be assumed to be static, an object's instance such as $someobject, which requires a width function, likely takes a measurement of the object's instance width.
Therefore readability increases mainly because of assertive naming-schemes and not by hiding the function away that outputs a given property-value.

__get / __set uses:

  • pre-validation and pre-sanitation of property values

  • strings e.g.

    "
    some {mathsobj1->generatelatex} multi
    line text {mathsobj1->latexoutput}
    with lots of variables for {mathsobj1->generatelatex}
     some reason
    "
    

    In this case generatelatex would adhere to a naming scheme of actionname + methodname

  • special, obvious cases

    $dnastringobj->homeobox($one_rememberable_parameter)->gattaca->findrelated()
    $dnastringobj->homeobox($one_rememberable_parameter)->gttccaatttga->findrelated()
    

Note: PHP chose not to implement getter/setter syntax. I am not claiming that getters/setter are generally bad.

Express-js can't GET my static files, why?

The problem with serving __dirname is that __dirname returns the path of the current file, not the project's file. Also, if you use a dynamic header, each page will look for the static files in a different path and it won't work. The best, for me, is to substitute __dirname for process.cwd() which ALWAYS donates the path to the project file.

app.use(express.static(process.cwd() + '/public'));

And in your project:

link rel="stylesheet" href="/styles/default.css"

See: What's the difference between process.cwd() vs __dirname?

Ternary operation in CoffeeScript

In almost any language this should work instead:

a = true  && 5 || 10
a = false && 5 || 10

Bootstrap full responsive navbar with logo or brand name text

If you want to achieve this (you can resize the window to see how it will look for mobile version), all you have to do is to have 2 logo images (1 for desktop and one for mobile) and display them depending of the enviroment using visible-xs and hidden-xs classes.

So i used something like this:

<img class="hidden-xs" src="http://placehold.it/150x50&text=Logo" alt="">
<img class="visible-xs" src="http://placehold.it/120x40&text=Logo" alt=""> 

And ofcourse, i styled the mobile logo using:

@media (max-width: 767px) { 
    .navbar-brand {
        padding: 0;        
    }

    .navbar-brand img {
        margin-top: 5px;
        margin-left: 5px;
    }
}

You can see all the code here. In case you need a text on mobile version insted of the logo, it's not a big deal. Just replace the logo with a <h1 class="visible-xs">AppName</h3> and change the style inside the media query like this:

@media (max-width: 767px) { 
    .navbar-brand {
        padding: 0;        
    }

    .navbar-brand h1{
        //here add your style depending of the position you want the text to be placed
    }
} 

EDIT:

You need this conditions to make it work:

.navbar-toggle {
   margin: 23px 0; 
}

.navbar-nav, .navbar-nav li, .navbar-nav li a {
  height: 80px;
  line-height: 80px;
}

.navbar-nav li a {
  padding-top: 0;
  padding-bottom:0;
}

The permissions granted to user ' are insufficient for performing this operation. (rsAccessDenied)"}

You can also make sure that the Identity in your Application Pool has the right permissions.

  1. Go to IIS Manager

  2. Click Application pools

  3. Identify the application pool of the site you are deploying reports on

  4. Check that the identity is set to some service account or user account that has admin permissions

  5. You can change the identity by stopping the pool, right clicking it, and selecting Advanced Settings...

Under Process Model is the Identity field

SQL grammar for SELECT MIN(DATE)

To get the titles for dates greater than a week ago today, use this:

SELECT title, MIN(date_key_no) AS intro_date FROM table HAVING MIN(date_key_no)>= TO_NUMBER(TO_CHAR(SysDate, 'YYYYMMDD')) - 7

Install tkinter for Python

Fedora release 25 (Twenty Five)

dnf install python3-tkinter

This worked for me.

How do I run a program from command prompt as a different user and as an admin

All of these answers unfortunately miss the point.

There are 2 security context nuances here, and we need them to overlap. - "Run as administrator" - changing your execution level on your local machine - "Run as different user" - selects what user credentials you run the process under.

When UAC is enabled on a workstation, there are processes which refuse to run unless elevated - simply being a member of the local "Administrators" group isn't enough. If your requirement also dictates that you use alternate credentials to those you are signed in with, we need a method to invoke the process both as the alternate credentials AND elevated.

What I found can be used, though a bit of a hassle, is:

  • run a CMD prompt as administrator
  • use the Sysinternals psexec utility as follows:

    psexec \\localworkstation -h -i -u domain\otheruser exetorun.exe

The first elevation is needed to be able to push the psexec service. The -h runs the new "remote" (local) process elevated, and -i lets it interact with the desktop.

Perhaps there are easier ways than this?

PHP FPM - check if running

For php7.0-fpm I call:

service php7.0-fpm status

php7.0-fpm start/running, process 25993

Now watch for the good part. The process name is actually php-fpm7.0

echo `/bin/pidof php-fpm7.0`

26334 26297 26286 26285 26282

jQuery find parent form

see also jquery/js -- How do I select the parent form based on which submit button is clicked?

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

How many socket connections can a web server handle?

It looks like the answer is at least 12 million if you have a beefy server, your server software is optimized for it, you have enough clients. If you test from one client to one server, the number of port numbers on the client will be one of the obvious resource limits (Each TCP connection is defined by the unique combination of IP and port number at the source and destination).

(You need to run multiple clients as otherwise you hit the 64K limit on port numbers first)

When it comes down to it, this is a classic example of the witticism that "the difference between theory and practise is much larger in practise than in theory" - in practise achieving the higher numbers seems to be a cycle of a. propose specific configuration/architecture/code changes, b. test it till you hit a limit, c. Have I finished? If not then d. work out what was the limiting factor, e. go back to step a (rinse and repeat).

Here is an example with 2 million TCP connections onto a beefy box (128GB RAM and 40 cores) running Phoenix http://www.phoenixframework.org/blog/the-road-to-2-million-websocket-connections - they ended up needing 50 or so reasonably significant servers just to provide the client load (their initial smaller clients maxed out to early, eg "maxed our 4core/15gb box @ 450k clients").

Here is another reference for go this time at 10 million: http://goroutines.com/10m.

This appears to be java based and 12 million connections: https://mrotaru.wordpress.com/2013/06/20/12-million-concurrent-connections-with-migratorydata-websocket-server/

Difference between signed / unsigned char

I slightly disagree with the above. The unsigned char simply means: Use the most significant bit instead of treating it as a bit flag for +/- sign when performing arithmetic operations.

It makes significance if you use char as a number for instance:

typedef char BYTE1;
typedef unsigned char BYTE2;

BYTE1 a;
BYTE2 b;

For variable a, only 7 bits are available and its range is (-127 to 127) = (+/-)2^7 -1. For variable b all 8 bits are available and the range is 0 to 255 (2^8 -1).

If you use char as character, "unsigned" is completely ignored by the compiler just as comments are removed from your program.

Regex doesn't work in String.matches()

String.matches returns whether the whole string matches the regex, not just any substring.

Detect click inside/outside of element with single event handler

This question can be answered with X and Y coordinates and without JQuery:

       var isPointerEventInsideElement = function (event, element) {
            var pos = {
                x: event.targetTouches ? event.targetTouches[0].pageX : event.pageX,
                y: event.targetTouches ? event.targetTouches[0].pageY : event.pageY
            };
            var rect = element.getBoundingClientRect();
            return  pos.x < rect.right && pos.x > rect.left && pos.y < rect.bottom && pos.y > rect.top;
        };

        document.querySelector('#my-element').addEventListener('click', function (event) {
           console.log(isPointerEventInsideElement(event, document.querySelector('#my-any-child-element')))
        });

Unsigned keyword in C++

Integer Types:

short            -> signed short
signed short
unsigned short
int              -> signed int
signed int
unsigned int
signed           -> signed int
unsigned         -> unsigned int
long             -> signed long
signed long
unsigned long

Be careful of char:

char  (is signed or unsigned depending on the implmentation)
signed char
unsigned char

Return string without trailing slash

function stripTrailingSlash(str) {
    if(str.substr(-1) === '/') {
        return str.substr(0, str.length - 1);
    }
    return str;
}

Note: IE8 and older do not support negative substr offsets. Use str.length - 1 instead if you need to support those ancient browsers.

HTML5 - mp4 video does not play in IE9

for IE9 I found that a meta tag was required to set the mode

<meta http-equiv="X-UA-Compatible" content="IE=Edge"/>

<video width="400" height="300" preload controls>
<source src="movie.mp4" type="video/mp4" />
Your browser does not support the video tag
</video>

Build Android Studio app via command line

Try this (OS X only):

brew install homebrew/versions/gradle110
gradle build

You can use gradle tasks to see all tasks available for the current project. No Android Studio is needed here.

Get environment value in controller

To simplify: Only configuration files can access environment variables - and then pass them on.

Step 1.) Add your variable to your .env file, for example,

EXAMPLE_URL="http://google.com"

Step 2.) Create a new file inside of the config folder, with any name, for example,

config/example.php

Step 3.) Inside of this new file, I add an array being returned, containing that environment variable.

<?php
return [
  'url' => env('EXAMPLE_URL')
];

Step 4.) Because I named it "example", my configuration 'namespace' is now example. So now, in my controller I can access this variable with:

$url = \config('example.url');

Tip - if you add use Config; at the top of your controller, you don't need the backslash (which designates the root namespace). For example,

namespace App\Http\Controllers;
use Config; // Added this line

class ExampleController extends Controller
{
    public function url() {
        return config('example.url');
    }
}

Finally, commit the changes:

php artisan config:cache

--- IMPORTANT --- Remember to enter php artisan config:cache into the console once you have created your example.php file. Configuration files and variables are cached, so if you make changes you need to flush that cache - the same applies to the .env file being changed / added to.

How to disable anchor "jump" when loading a page?

I did not have much success with the above setTimeout methods in Firefox.

Instead of a setTimeout, I've used an onload function:

window.onload = function () {
    if (location.hash) {
        window.scrollTo(0, 0);
    }
};

It's still very glitchy, unfortunately.