Programs & Examples On #Datadetectortypes

Conditional formatting, entire row based

To set Conditional Formatting for an ENTIRE ROW based on a single cell you must ANCHOR that single cell's column address with a "$", otherwise Excel will only get the first column correct. Why?

Because Excel is setting your Conditional Format for the SECOND column of your row based on an OFFSET of columns. For the SECOND column, Excel has now moved one column to the RIGHT of your intended rule cell, examined THAT cell, and has correctly formatted column two based on a cell you never intended.

Simply anchor the COLUMN portion of your rule cell's address with "$", and you will be happy

For example: You want any row of your table to highlight red if the last cell of that row does not equal 1.

Select the entire table (but not the headings) "Home" > "Conditional Formatting" > "Manage Rules..." > "New Rule" > "Use a formula to determine which cells to format"

Enter: "=$T3<>1" (no quotes... "T" is the rule cell's column, "3" is its row) Set your formatting Click Apply.

Make sure Excel has not inserted quotes into any part of your formula... if it did, Backspace/Delete them out (no arrow keys please).

Conditional Formatting should be set for the entire table.

Update some specific field of an entity in android Room

If you need to update user information for a specific user ID "x",

  1. you need to create a dbManager class that will initialise the database in its constructor and acts as a mediator between your viewModel and DAO, and also .
  2. The ViewModel will initialize an instance of dbManager to access the database. The code should look like this:

       @Entity
        class User{
        @PrimaryKey
        String userId;
        String username;
        }
    
        Interface UserDao{
        //forUpdate
        @Update
        void updateUser(User user)
        }
    
        Class DbManager{
        //AppDatabase gets the static object o roomDatabase.
        AppDatabase appDatabase;
        UserDao userDao;
        public DbManager(Application application ){
        appDatabase = AppDatabase.getInstance(application);
    
        //getUserDao is and abstract method of type UserDao declared in AppDatabase //class
        userDao = appDatabase.getUserDao();
        } 
    
        public void updateUser(User user, boolean isUpdate){
        new InsertUpdateUserAsyncTask(userDao,isUpdate).execute(user);
        }
    
    
    
        public static class InsertUpdateUserAsyncTask extends AsyncTask<User, Void, Void> {
    
    
         private UserDao userDAO;
         private boolean isInsert;
    
         public InsertUpdateBrandAsyncTask(BrandDAO userDAO, boolean isInsert) {
           this. userDAO = userDAO;
           this.isInsert = isInsert;
         }
    
         @Override
         protected Void doInBackground(User... users) {
           if (isInsert)
        userDAO.insertBrand(brandEntities[0]);
           else
        //for update
        userDAO.updateBrand(users[0]);
        //try {
        //  Thread.sleep(1000);
        //} catch (InterruptedException e) {
        //  e.printStackTrace();
        //}
           return null;
         }
          }
        }
    
         Class UserViewModel{
         DbManager dbManager;
         public UserViewModel(Application application){
         dbmanager = new DbMnager(application);
         }
    
         public void updateUser(User user, boolean isUpdate){
         dbmanager.updateUser(user,isUpdate);
         }
    
         }
    
    
    
    
    Now in your activity or fragment initialise your UserViewModel like this:
    
    UserViewModel userViewModel = ViewModelProviders.of(this).get(UserViewModel.class);
    

    Then just update your user item this way, suppose your userId is 1122 and userName is "xyz" which has to be changed to "zyx".

    Get an userItem of id 1122 User object

User user = new user();
 if(user.getUserId() == 1122){
   user.setuserName("zyx");
   userViewModel.updateUser(user);
 }

This is a raw code, hope it helps you.

Happy coding

ProcessBuilder: Forwarding stdout and stderr of started processes without blocking the main thread

A flexible solution with Java 8 lambda that lets you provide a Consumer that will process the output (eg. log it) line by line. run() is a one-liner with no checked exceptions thrown. Alternatively to implementing Runnable, it can extend Thread instead as other answers suggest.

class StreamGobbler implements Runnable {
    private InputStream inputStream;
    private Consumer<String> consumeInputLine;

    public StreamGobbler(InputStream inputStream, Consumer<String> consumeInputLine) {
        this.inputStream = inputStream;
        this.consumeInputLine = consumeInputLine;
    }

    public void run() {
        new BufferedReader(new InputStreamReader(inputStream)).lines().forEach(consumeInputLine);
    }
}

You can then use it for example like this:

public void runProcessWithGobblers() throws IOException, InterruptedException {
    Process p = new ProcessBuilder("...").start();
    Logger logger = LoggerFactory.getLogger(getClass());

    StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), System.out::println);
    StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), logger::error);

    new Thread(outputGobbler).start();
    new Thread(errorGobbler).start();
    p.waitFor();
}

Here the output stream is redirected to System.out and the error stream is logged on the error level by the logger.

gcc: undefined reference to

However, avpicture_get_size is defined.

No, as the header (<libavcodec/avcodec.h>) just declares it.

The definition is in the library itself.

So you might like to add the linker option to link libavcodec when invoking gcc:

-lavcodec

Please also note that libraries need to be specified on the command line after the files needing them:

gcc -I$HOME/ffmpeg/include program.c -lavcodec

Not like this:

gcc -lavcodec -I$HOME/ffmpeg/include program.c

Referring to Wyzard's comment, the complete command might look like this:

gcc -I$HOME/ffmpeg/include program.c -L$HOME/ffmpeg/lib -lavcodec

For libraries not stored in the linkers standard location the option -L specifies an additional search path to lookup libraries specified using the -l option, that is libavcodec.x.y.z in this case.


For a detailed reference on GCC's linker option, please read here.

How does DateTime.Now.Ticks exactly work?

Not really an answer to your question as asked, but thought I'd chip in about your general objective.

There already is a method to generate random file names in .NET.

See System.Path.GetTempFileName and GetRandomFileName.

Alternatively, it is a common practice to use a GUID to name random files.

In AVD emulator how to see sdcard folder? and Install apk to AVD?

These days the location of the emulated SD card is at /storage/emulated/0

What are unit tests, integration tests, smoke tests, and regression tests?

There are some good answers already, but I would like further refine them:

Unit testing is the only form of white box testing here. The others are black box testing. White box testing means that you know the input; you know the inner workings of the mechanism and can inspect it and you know the output. With black box testing you only know what the input is and what the output should be.

So clearly unit testing is the only white box testing here.

  • Unit testing test specific pieces of code. Usually methods.
  • Integration testing test whether your new feature piece of software can integrate with everything else.
  • Regression testing. This is testing done to make sure you haven't broken anything. Everything that used to work should still work.
  • Smoke testing is done as a quick test to make sure everything looks okay before you get involved in the more vigorous testing.

How to replace innerHTML of a div using jQuery?

Example

_x000D_
_x000D_
$( document ).ready(function() {_x000D_
  $('.msg').html('hello world');_x000D_
});
_x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
      <head>_x000D_
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>    _x000D_
      </head>_x000D_
      <body>_x000D_
        <div class="msg"></div>_x000D_
      </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

File path to resource in our war/WEB-INF folder?

Now with Java EE 7 you can find the resource more easily with

InputStream resource = getServletContext().getResourceAsStream("/WEB-INF/my.json");

https://docs.oracle.com/javaee/7/api/javax/servlet/GenericServlet.html#getServletContext--

Function overloading in Javascript - Best practices

Another way to approach this is by using the special variable: arguments, this is an implementation:

function sum() {
    var x = 0;
    for (var i = 0; i < arguments.length; ++i) {
        x += arguments[i];
    }
    return x;
}

so you can modify this code to:

function sum(){
    var s = 0;
    if (typeof arguments[0] !== "undefined") s += arguments[0];
.
.
.
    return s;
}

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

Try the following code:

$cfg['Servers'][$i]['password'] = '';

if you see Password column field as 'No' for the 'root' user in Users Overview page of phpMyAdmin.

Search and get a line in Python

you mentioned "entire line" , so i assumed mystring is the entire line.

if "token" in mystring:
    print(mystring)

however if you want to just get "token qwerty",

>>> mystring="""
...     qwertyuiop
...     asdfghjkl
...
...     zxcvbnm
...     token qwerty
...
...     asdfghjklñ
... """
>>> for item in mystring.split("\n"):
...  if "token" in item:
...     print (item.strip())
...
token qwerty

How to select last two characters of a string

EDIT: 2020: use string.slice(-2) as others say - see below.

now 2016 just string.substr(-2) should do the trick (not substring(!))

taken from MDN

Syntax

str.substr(start[, length])

Parameters

start

Location at which to begin extracting characters. If a negative number is given, it is treated as strLength + start where strLength is the length of the string (for example, if start is -3 it is treated as strLength - 3.) length Optional. The number of characters to extract.

EDIT 2020

MDN says

Warning: Although String.prototype.substr(…) is not strictly deprecated (as in "removed from the Web standards"), it is considered a legacy function and should be avoided when possible. It is not part of the core JavaScript language and may be removed in the future.

Replace HTML Table with Divs

Please be aware that although tables are discouraged as a primary means of page layout, they still have their place. Tables can and should be used when and where appropriate and until some of the more popular browsers (ahem, IE, ahem) become more standards compliant, tables are sometimes the best route to a solution.

How to convert md5 string to normal text?

I you send passwords to users in an email, you might as well have no passwords at all.

You cannot reverse the MD5 function, so your only option is to generate a new password and send that to the user (preferably over some secure channel).

Action Image MVC3 Razor

You can create an extension method for HtmlHelper to simplify the code in your CSHTML file. You could replace your tags with a method like this:

// Sample usage in CSHTML
@Html.ActionImage("Edit", new { id = MyId }, "~/Content/Images/Image.bmp", "Edit")

Here is a sample extension method for the code above:

// Extension method
public static MvcHtmlString ActionImage(this HtmlHelper html, string action, object routeValues, string imagePath, string alt)
{
    var url = new UrlHelper(html.ViewContext.RequestContext);

    // build the <img> tag
    var imgBuilder = new TagBuilder("img");
    imgBuilder.MergeAttribute("src", url.Content(imagePath));
    imgBuilder.MergeAttribute("alt", alt);
    string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

    // build the <a> tag
    var anchorBuilder = new TagBuilder("a");
    anchorBuilder.MergeAttribute("href", url.Action(action, routeValues));
    anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
    string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);

    return MvcHtmlString.Create(anchorHtml);
}

How to Display Selected Item in Bootstrap Button Dropdown Title

Updated for Bootstrap 3.3.4:

This will allow you to have different display text and data value for each element. It will also persist the caret on selection.

JS:

$(".dropdown-menu li a").click(function(){
  $(this).parents(".dropdown").find('.btn').html($(this).text() + ' <span class="caret"></span>');
  $(this).parents(".dropdown").find('.btn').val($(this).data('value'));
});

HTML:

<div class="dropdown">
  <button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
    Dropdown
    <span class="caret"></span>
  </button>
  <ul class="dropdown-menu" aria-labelledby="dropdownMenu1">
    <li><a href="#" data-value="action">Action</a></li>
    <li><a href="#" data-value="another action">Another action</a></li>
    <li><a href="#" data-value="something else here">Something else here</a></li>
    <li><a href="#" data-value="separated link">Separated link</a></li>
  </ul>
</div>

JS Fiddle Example

Print all key/value pairs in a Java ConcurrentHashMap

Work 100% sure try this code for the get all hashmap key and value

static HashMap<String, String> map = new HashMap<>();

map.put("one"  " a " );
map.put("two"  " b " );
map.put("three"  " c " );
map.put("four"  " d " );

just call this method whenever you want to show the HashMap value

 private void ShowHashMapValue() {

        /**
         * get the Set Of keys from HashMap
         */
        Set setOfKeys = map.keySet();

/**
 * get the Iterator instance from Set
 */
        Iterator iterator = setOfKeys.iterator();

/**
 * Loop the iterator until we reach the last element of the HashMap
 */
        while (iterator.hasNext()) {
/**
 * next() method returns the next key from Iterator instance.
 * return type of next() method is Object so we need to do DownCasting to String
 */
            String key = (String) iterator.next();

/**
 * once we know the 'key', we can get the value from the HashMap
 * by calling get() method
 */
            String value = map.get(key);

            System.out.println("Key: " + key + ", Value: " + value);
        }
    } 

Setting environment variables in Linux using Bash

Set a local and environment variable using Bash on Linux

Check for a local or environment variables for a variable called LOL in Bash:

el@server /home/el $ set | grep LOL
el@server /home/el $
el@server /home/el $ env | grep LOL
el@server /home/el $

Sanity check, no local or environment variable called LOL.

Set a local variable called LOL in local, but not environment. So set it:

el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ env | grep LOL
el@server /home/el $

Variable 'LOL' exists in local variables, but not environment variables. LOL will disappear if you restart the terminal, logout/login or run exec bash.

Set a local variable, and then clear out all local variables in Bash

el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ exec bash
el@server /home/el $ set | grep LOL
el@server /home/el $

You could also just unset the one variable:

el@server /home/el $ LOL="so wow much code"
el@server /home/el $ set | grep LOL
LOL='so wow much code'
el@server /home/el $ unset LOL
el@server /home/el $ set | grep LOL
el@server /home/el $

Local variable LOL is gone.

Promote a local variable to an environment variable:

el@server /home/el $ DOGE="such variable"
el@server /home/el $ export DOGE
el@server /home/el $ set | grep DOGE
DOGE='such variable'
el@server /home/el $ env | grep DOGE
DOGE=such variable

Note that exporting makes it show up as both a local variable and an environment variable.

Exported variable DOGE above survives a Bash reset:

el@server /home/el $ exec bash
el@server /home/el $ env | grep DOGE
DOGE=such variable
el@server /home/el $ set | grep DOGE
DOGE='such variable'

Unset all environment variables:

You have to pull out a can of Chuck Norris to reset all environment variables without a logout/login:

el@server /home/el $ export CAN="chuck norris"
el@server /home/el $ env | grep CAN
CAN=chuck norris
el@server /home/el $ set | grep CAN
CAN='chuck norris'
el@server /home/el $ env -i bash
el@server /home/el $ set | grep CAN
el@server /home/el $ env | grep CAN

You created an environment variable, and then reset the terminal to get rid of them.

Or you could set and unset an environment variable manually like this:

el@server /home/el $ export FOO="bar"
el@server /home/el $ env | grep FOO
FOO=bar
el@server /home/el $ unset FOO
el@server /home/el $ env | grep FOO
el@server /home/el $

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

I was facing same problem when I installed JRE by Oracle and solved this problem after my research.

I moved the environment path C:\Program Files (x86)\Common Files\Oracle\Java\javapath below H:\Program Files\Java\jdk-13.0.1\bin

Like this:

Path

H:\Program Files\Java\jdk-13.0.1\bin
C:\Program Files (x86)\Common Files\Oracle\Java\javapath

OR

Path

%JAVA_HOME%
%JRE_HOME%

Uses of Action delegate in C#

MSDN says:

This delegate is used by the Array.ForEach method and the List.ForEach method to perform an action on each element of the array or list.

Except that, you can use it as a generic delegate that takes 1-3 parameters without returning any value.

PreparedStatement setNull(..)

but watch out for this....

Long nullLong = null;

preparedStatement.setLong( nullLong );

-thows null pointer exception-

because the protype is

setLong( long )   

NOT

setLong( Long )

nice one to catch you out eh.

Generating random strings with T-SQL

There are a lot of good answers but so far none of them allow a customizable character pool and work as a default value for a column. I wanted to be able to do something like this:

alter table MY_TABLE add MY_COLUMN char(20) not null
  default dbo.GenerateToken(crypt_gen_random(20))

So I came up with this. Beware of the hard-coded number 32 if you modify it.

-- Converts a varbinary of length N into a varchar of length N.
-- Recommend passing in the result of CRYPT_GEN_RANDOM(N).
create function GenerateToken(@randomBytes varbinary(max))
returns varchar(max) as begin

-- Limit to 32 chars to get an even distribution (because 32 divides 256) with easy math.
declare @allowedChars char(32);
set @allowedChars = 'abcdefghijklmnopqrstuvwxyz012345';

declare @oneByte tinyint;
declare @oneChar char(1);
declare @index int;
declare @token varchar(max);

set @index = 0;
set @token = '';

while @index < datalength(@randomBytes)
begin
    -- Get next byte, use it to index into @allowedChars, and append to @token.
    -- Note: substring is 1-based.
    set @index = @index + 1;
    select @oneByte = convert(tinyint, substring(@randomBytes, @index, 1));
    select @oneChar = substring(@allowedChars, 1 + (@oneByte % 32), 1); -- 32 is the number of @allowedChars
    select @token = @token + @oneChar;
end

return @token;

end

Pure CSS to make font-size responsive based on dynamic amount of characters

As many mentioned in comments to @DMTinter's post, the OP was asking about the number ("amount") of characters changing. He was also asking about CSS, but as @Alexander indicated, "it is not possible with only CSS". As far as I can tell, that seems to be true at this time, so it also seems logical that people would want to know the next best thing.

I'm not particularly proud of this, but it does work. Seems like an excessive amount of code to accomplish it. This is the core:

function fitText(el){
  var text = el.text();
  var fsize = parseInt(el.css('font-size'));
  var measured = measureText(text, fsize);

  if (measured.width > el.width()){
    console.log('reducing');
    while(true){
      fsize = parseInt(el.css('font-size'));
      var m = measureText(text, fsize );
      if(m.width > el.width()){
        el.css('font-size', --fsize + 'px');
      }
      else{
        break;
      }
    }
  }
  else if (measured.width < el.width()){
    console.log('increasing');
    while(true){
      fsize = parseInt(el.css('font-size'));
      var m = measureText(text, fsize);
      if(m.width < el.width()-4){ // not sure why -4 is needed (often)
        el.css('font-size', ++fsize + 'px');
      }
      else{
        break;
      }
    }
  }
}

Here's a JS Bin: http://jsbin.com/pidavon/edit?html,css,js,console,output
Please suggest possible improvements to it (I'm not really interested in using canvas to measure the text...seems like too much overhead(?)).

Thanks to @Pete for measureText function: https://stackoverflow.com/a/4032497/442665

vertical & horizontal lines in matplotlib

The pyplot functions you are calling, axhline() and axvline() draw lines that span a portion of the axis range, regardless of coordinates. The parameters xmin or ymin use value 0.0 as the minimum of the axis and 1.0 as the maximum of the axis.

Instead, use plt.plot((x1, x2), (y1, y2), 'k-') to draw a line from the point (x1, y1) to the point (x2, y2) in color k. See pyplot.plot.

OAuth2 and Google API: access token expiration time?

The default expiry_date for google oauth2 access token is 1 hour. The expiry_date is in the Unix epoch time in milliseconds. If you want to read this in human readable format then you can simply check it here..Unix timestamp to human readable time

Location of GlassFish Server Logs

In general the logs are in /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/.

In NetBeans go to the "Services" tab open "Servers", right-click on your Glassfish instance and click "View Domain Server Log".

If this doesn't work right-click on the Glassfish instance and click "Properties", you can see the folder with the domains under "Domains folder". Go to this folder -> your-domain -> logs

If the server is already running you should see an Output tab in NetBeans which is named similar to GlassFish Server x.x.x

You can also use cat or tail -F on /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/server.log. If you are using a different domain then domain1 you have to adjust the path for that.

CSS Child vs Descendant selectors

div > p matches ps that have a div parent - <div><p> in your question

div p matches ps that have a div ancestor (parent, grandparent, great grandparent, etc.) - <div><p> and <div><div><p> in your question

How to dismiss the dialog with click on outside of the dialog?

Another solution, this code was taken from android source code of Window You should just add these Two methods to your dialog source code.

@Override
public boolean onTouchEvent(MotionEvent event) {        
    if (isShowing() && (event.getAction() == MotionEvent.ACTION_DOWN
            && isOutOfBounds(getContext(), event) && getWindow().peekDecorView() != null)) {
        hide();
    }
    return false;
}

private boolean isOutOfBounds(Context context, MotionEvent event) {
    final int x = (int) event.getX();
    final int y = (int) event.getY();
    final int slop = ViewConfiguration.get(context).getScaledWindowTouchSlop();
    final View decorView = getWindow().getDecorView();
    return (x < -slop) || (y < -slop)
            || (x > (decorView.getWidth()+slop))
            || (y > (decorView.getHeight()+slop));
}

This solution doesnt have this problem :

This works great except that the activity underneath also reacts to the touch event. Is there some way to prevent this? – howettl

How to call an action after click() in Jquery?

setTimeout may help out here

$("#message_link").click(function(){
   setTimeout(function() {
       if (some_conditions...){
           $("#header").append("<div><img alt=\"Loader\"src=\"/images/ajax-loader.gif\"  /></div>");
       }
   }, 100);
});

That will cause the div to be appended ~100ms after the click event occurs, if some_conditions are met.

What is the difference between a 'closure' and a 'lambda'?

Not all closures are lambdas and not all lambdas are closures. Both are functions, but not necessarily in the manner we're used to knowing.

A lambda is essentially a function that is defined inline rather than the standard method of declaring functions. Lambdas can frequently be passed around as objects.

A closure is a function that encloses its surrounding state by referencing fields external to its body. The enclosed state remains across invocations of the closure.

In an object-oriented language, closures are normally provided through objects. However, some OO languages (e.g. C#) implement special functionality that is closer to the definition of closures provided by purely functional languages (such as lisp) that do not have objects to enclose state.

What's interesting is that the introduction of Lambdas and Closures in C# brings functional programming closer to mainstream usage.

What is limiting the # of simultaneous connections my ASP.NET application can make to a web service?

If it is not defined in the web service or application or server (apache or IIS) that is hosting the web service consumable then you could create infinite connections until failure

Sort array of objects by single key with date value

  • Use Array.sort() to sort an array
  • Clone array using spread operator () to make the function pure
  • Sort by desired key (updated_at)
  • Convert date string to date object
  • Array.sort() works by subtracting two properties from current and next item if it is a number / object on which you can perform arrhythmic operations
const input = [
  {
    updated_at: '2012-01-01T06:25:24Z',
    foo: 'bar',
  },
  {
    updated_at: '2012-01-09T11:25:13Z',
    foo: 'bar',
  },
  {
    updated_at: '2012-01-05T04:13:24Z',
    foo: 'bar',
  }
];

const sortByUpdatedAt = (items) => [...items].sort((itemA, itemB) => new Date(itemA.updated_at) - new Date(itemB.updated_at));

const output = sortByUpdatedAt(input);

console.log(input);
/*
[ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-09T11:25:13Z', foo: 'bar' }, 
  { updated_at: '2012-01-05T04:13:24Z', foo: 'bar' } ]
*/
console.log(output)
/*
[ { updated_at: '2012-01-01T06:25:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-05T04:13:24Z', foo: 'bar' }, 
  { updated_at: '2012-01-09T11:25:13Z', foo: 'bar' } ]
*/

How to get .pem file from .key and .crt files?

I was trying to go from godaddy to app engine. What did the trick was using this line:

openssl req -new -newkey rsa:2048 -nodes -keyout name.unencrypted.priv.key -out name.csr

Exactly as is, but replacing name with my domain name (not that it really even mattered)

And I answered all the questions pertaining to common name / organization as www.name.com

Then I opened the csr, copied it, pasted it in go daddy, then downloaded it, unzipped it, navigated to the unzipped folder with the terminal and entered:

cat otherfilegodaddygivesyou.crt gd_bundle-g2-g1.crt > name.crt

Then I used these instructions from Trouble with Google Apps Custom Domain SSL, which were:

openssl rsa -in privateKey.key -text > private.pem
openssl x509 -inform PEM -in www_mydomain_com.crt > public.pem

exactly as is, except instead of privateKey.key I used name.unencrypted.priv.key, and instead of www_mydomain_com.crt, I used name.crt

Then I uploaded the public.pem to the admin console for the "PEM encoded X.509 certificate", and uploaded the private.pem for the "Unencrypted PEM encoded RSA private key"..

.. And that finally worked.

Custom Drawable for ProgressBar/ProgressDialog

Your style should look like this:

<style parent="@android:style/Widget.ProgressBar" name="customProgressBar">
    <item name="android:indeterminateDrawable">@anim/mp3</item>
</style>

JQuery Ajax Post results in 500 Internal Server Error

I had this issue, and found out that the server side C# method should be static.

Client Side:

$.ajax({
            type: "POST",
            url: "Default.aspx/ListItem_Selected",
            data: "{}",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: ListItemElectionSuccess,
            error: ListItemElectionError
        });

        function ListItemElectionSuccess(data) {
            alert([data.d]);
        }
        function ListItemElectionError(data) {

        }

Server Side:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    [WebMethod]
    [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
    public static String ListItem_Selected()
    {
        return "server responce";
    }
}

Mongoose.js: Find user by username LIKE value

You should use a regex for that.

db.users.find({name: /peter/i});

Be wary, though, that this query doesn't use index.

Windows Explorer "Command Prompt Here"

If that's so bothering, you could try to switch to windows explorer alternative like freecommander which has a toolbar button for that purpose.

document .click function for touch device

To trigger the function with click or touch, you could change this:

$(document).click( function () {

To this:

$(document).on('click touchstart', function () {

Or this:

$(document).on('click touch', function () {

The touchstart event fires as soon as an element is touched, the touch event is more like a "tap", i.e. a single contact on the surface. You should really try each of these to see what works best for you. On some devices, touch can be a little harder to trigger (which may be a good or bad thing - it prevents a drag being counted, but an accidental small drag may cause it to not be fired).

How to increase space between dotted border dots

Building 4 edges solution basing on @Eagorajose's answer with shorthand syntax:

background: linear-gradient(to right, #000 33%, #fff 0%) top/10px 1px repeat-x, /* top */
linear-gradient(#000 33%, #fff 0%) right/1px 10px repeat-y, /* right */
linear-gradient(to right, #000 33%, #fff 0%) bottom/10px 1px repeat-x, /* bottom */
linear-gradient(#000 33%, #fff 0%) left/1px 10px repeat-y; /* left */

_x000D_
_x000D_
#page {_x000D_
    background: linear-gradient(to right, #000 33%, #fff 0%) top/10px 1px repeat-x, /* top */_x000D_
    linear-gradient(#000 33%, #fff 0%) right/1px 10px repeat-y, /* right */_x000D_
    linear-gradient(to right, #000 33%, #fff 0%) bottom/10px 1px repeat-x, /* bottom */_x000D_
    linear-gradient(#000 33%, #fff 0%) left/1px 10px repeat-y; /* left */_x000D_
    _x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
}
_x000D_
<div id="page"></div>
_x000D_
_x000D_
_x000D_

Using DataContractSerializer to serialize, but can't deserialize back

I ended up doing the following and it works.

public static string Serialize(object obj)
{
    using (MemoryStream memoryStream = new MemoryStream())
    {
        DataContractSerializer serializer = new DataContractSerializer(obj.GetType());
        serializer.WriteObject(memoryStream, obj);
        return Encoding.UTF8.GetString(memoryStream.ToArray());
    }
}

public static object Deserialize(string xml, Type toType)
{
    using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
    {
        XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(memoryStream, Encoding.UTF8, new XmlDictionaryReaderQuotas(), null);
        DataContractSerializer serializer = new DataContractSerializer(toType);
        return serializer.ReadObject(reader);
    }
}

It seems that the major problem was in the Serialize function when calling stream.GetBuffer(). Calling stream.ToArray() appears to work.

How to "comment-out" (add comment) in a batch/cmd?

The :: instead of REM was preferably used in the days that computers weren't very fast. REM'ed line are read and then ingnored. ::'ed line are ignored all the way. This could speed up your code in "the old days". Further more after a REM you need a space, after :: you don't.

And as said in the first comment: you can add info to any line you feel the need to

SET DATETIME=%DTS:~0,8%-%DTS:~8,6% ::Makes YYYYMMDD-HHMMSS

As for the skipping of parts. Putting REM in front of every line can be rather time consuming. As mentioned using GOTO to skip parts is an easy way to skip large pieces of code. Be sure to set a :LABEL at the point you want the code to continue.

SOME CODE

GOTO LABEL  ::REM OUT THIS LINE TO EXECUTE THE CODE BETWEEN THIS GOTO AND :LABEL

SOME CODE TO SKIP
.
LAST LINE OF CODE TO SKIP

:LABEL
CODE TO EXECUTE

org.hibernate.MappingException: Could not determine type for: java.util.Set

I had similar problem I found the issue I was mixing the annotations some of them above the attributes and some of them above public methods. I just put all of them above attributes and it works.

Can linux cat command be used for writing text to file?

Write multi-line text with environment variables using echo:

echo -e "
Home Directory: $HOME \n
hello world 1 \n
hello world 2 \n
line n... \n
" > file.txt 

IndexOf function in T-SQL

You can use either CHARINDEX or PATINDEX to return the starting position of the specified expression in a character string.

CHARINDEX('bar', 'foobar') == 4
PATINDEX('%bar%', 'foobar') == 4

Mind that you need to use the wildcards in PATINDEX on either side.

What does Docker add to lxc-tools (the userspace LXC tools)?

Dockers use images which are build in layers. This adds a lot in terms of portability, sharing, versioning and other features. These images are very easy to port or transfer and since they are in layers, changes in subsequent versions are added in form of layers over previous layers. So, while porting many a times you don't need to port the base layers. Dockers have containers which run these images with execution environment contained, they add changes as new layers providing easy version control.

Apart from that Docker Hub is a good registry with thousands of public images, where you can find images which have OS and other softwares installed. So, you can get a pretty good head start for your application.

The name 'ConfigurationManager' does not exist in the current context

Just install

Install-Package System.Configuration.ConfigurationManager -Version 4.5.0

then use

using System.Configuration;

How can I pad a String in Java?

This took me a little while to figure out. The real key is to read that Formatter documentation.

// Get your data from wherever.
final byte[] data = getData();
// Get the digest engine.
final MessageDigest md5= MessageDigest.getInstance("MD5");
// Send your data through it.
md5.update(data);
// Parse the data as a positive BigInteger.
final BigInteger digest = new BigInteger(1,md5.digest());
// Pad the digest with blanks, 32 wide.
String hex = String.format(
    // See: http://download.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html
    // Format: %[argument_index$][flags][width]conversion
    // Conversion: 'x', 'X'  integral    The result is formatted as a hexadecimal integer
    "%1$32x",
    digest
);
// Replace the blank padding with 0s.
hex = hex.replace(" ","0");
System.out.println(hex);

How to show changed file name only with git log?

If you need just file names like:

dir/subdir/file1.txt
dir/subdir2/file2.sql
dir2/subdir3/file6.php

(which I use as a source for tar command) you will also need to filter out commit messages.

In order to do this I use following command:

git log --name-only --oneline | grep -v '.{7} '

Grep command excludes (-v param) every line which starts with seven symbols (which is the length of my git hash for git log command) followed by space. So it filters out every git hash message line and leave only lines with file names.

One useful improvement is to append uniq to remove duplicate lines so it will looks as follow:

git log --name-only --oneline | grep -v '.{7} ' | uniq

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

This splits the string on any combo of new line characters and joins them with a space, assuming you actually do want the space where the new lines would have been.

var oldString = "the quick brown\rfox jumped over\nthe box\r\nand landed on some rocks.";
var newString = string.Join(" ", Regex.Split(oldString, @"(?:\r\n|\n|\r)"));
Console.Write(newString);

// prints:
// the quick brown fox jumped over the box and landed on some rocks.

Pass multiple complex objects to a post/put Web API method

Create one complex object to combine Content and Config in it as others mentioned, use dynamic and just do a .ToObject(); as:

[HttpPost]
public void StartProcessiong([FromBody] dynamic obj)
{
   var complexObj= obj.ToObject<ComplexObj>();
   var content = complexObj.Content;
   var config = complexObj.Config;
}

Creating java date object from year,month,day

That's my favorite way prior to Java 8:

Date date = new GregorianCalendar(year, month - 1, day).getTime();

I'd say this is a cleaner approach than:

calendar.set(year, month - 1, day, 0, 0);

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

I'm compiling gcc 4.6 from source, and apparently

sudo make install 

didn't catch this one. I dug around and found

gcc/trunk/x86_64-unknown-linux-gnu/libstdc++-v3/src/.libs/libstdc++.so.6.0.15

I copied it in to /usr/lib and redirected libstdc++.so.6 to point to the new one, and now everything works.

Git - push current branch shortcut

With the help of ceztko's answer I wrote this little helper function to make my life easier:

function gpu()
{
    if git rev-parse --abbrev-ref --symbolic-full-name @{u} > /dev/null 2>&1; then
        git push origin HEAD
    else
        git push -u origin HEAD
    fi
}

It pushes the current branch to origin and also sets the remote tracking branch if it hasn't been setup yet.

Passing on command line arguments to runnable JAR

You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.

The command line would be done this way:

c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt

and the java code accesses the value like this:

String context = System.getProperty("myvar"); 

See this question about argument passing in Java.

JavaScript closure inside loops – simple practical example

This question really shows the history of JavaScript! Now we can avoid block scoping with arrow functions and handle loops directly from DOM nodes using Object methods.

_x000D_
_x000D_
const funcs = [1, 2, 3].map(i => () => console.log(i));_x000D_
funcs.map(fn => fn())
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
const buttons = document.getElementsByTagName("button");_x000D_
Object_x000D_
  .keys(buttons)_x000D_
  .map(i => buttons[i].addEventListener('click', () => console.log(i)));
_x000D_
<button>0</button><br>_x000D_
<button>1</button><br>_x000D_
<button>2</button>
_x000D_
_x000D_
_x000D_

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

If it's the first time for you to save your datatable

Do this (using bulk copy). Assure there are no PK/FK constraint

SqlBulkCopy bulkcopy = new SqlBulkCopy(myConnection);
//I assume you have created the table previously
//Someone else here already showed how  
bulkcopy.DestinationTableName = table.TableName;
try                             
{                                 
    bulkcopy.WriteToServer(table);                            
}     
    catch(Exception e)
{
    messagebox.show(e.message);
} 

Now since you already have a basic record. And you just want to check new record with the existing one. You can simply do this.

This will basically take existing table from database

DataTable Table = new DataTable();

SqlConnection Connection = new SqlConnection("ConnectionString");
//I assume you know better what is your connection string

SqlDataAdapter adapter = new SqlDataAdapter("Select * from " + TableName, Connection);

adapter.Fill(Table);

Then pass this table to this function

public DataTable CompareDataTables(DataTable first, DataTable second)
{
    first.TableName = "FirstTable";
    second.TableName = "SecondTable";

    DataTable table = new DataTable("Difference");

    try
    {
        using (DataSet ds = new DataSet())
        {
            ds.Tables.AddRange(new DataTable[] { first.Copy(), second.Copy() });

            DataColumn[] firstcolumns = new DataColumn[ds.Tables[0].Columns.Count];

            for (int i = 0; i < firstcolumns.Length; i++)
            {
                firstcolumns[i] = ds.Tables[0].Columns[i];
            }

            DataColumn[] secondcolumns = new DataColumn[ds.Table[1].Columns.Count];

            for (int i = 0; i < secondcolumns.Length; i++)
            {
                secondcolumns[i] = ds.Tables[1].Columns[i];
            }

            DataRelation r = new DataRelation(string.Empty, firstcolumns, secondcolumns, false);

            ds.Relations.Add(r);

            for (int i = 0; i < first.Columns.Count; i++)
            {
                table.Columns.Add(first.Columns[i].ColumnName, first.Columns[i].DataType);
            }

            table.BeginLoadData();

            foreach (DataRow parentrow in ds.Tables[0].Rows)
            {
                DataRow[] childrows = parentrow.GetChildRows(r);
                if (childrows == null || childrows.Length == 0)
                    table.LoadDataRow(parentrow.ItemArray, true);
            }

            table.EndLoadData();

        }
    }

    catch (Exception ex)
    {
        throw ex;
    }

    return table;
}

This will return a new DataTable with the changed rows updated. Please ensure you call the function correctly. The DataTable first is supposed to be the latest.

Then repeat the bulkcopy function all over again with this fresh datatable.

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

Go to SVG to Script with your SVG the default output is the map in SVG Code which adds events is also added but is easily identified and can be altered as required.

PDF Blob - Pop up window not showing content

// I used this code with the fpdf library.
// Este código lo usé con la libreria fpdf.

var datas = json1;
var xhr = new XMLHttpRequest();
xhr.open("POST", "carpeta/archivo.php");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.responseType = "blob";
xhr.onload = function () {
    if (this.status === 200) {
        var blob = new Blob([xhr.response], {type: 'application/pdf'});
        const url = window.URL.createObjectURL(blob);
        window.open(url,"_blank");
        setTimeout(function () {
            // For Firefox it is necessary to delay revoking the ObjectURL
            window.URL.revokeObjectURL(datas)
                , 100
        })
    }
};
xhr.send("men="+datas);

Expanding tuples into arguments

Similar to @Dominykas's answer, this is a decorator that converts multiargument-accepting functions into tuple-accepting functions:

apply_tuple = lambda f: lambda args: f(*args)

Example 1:

def add(a, b):
    return a + b

three = apply_tuple(add)((1, 2))

Example 2:

@apply_tuple
def add(a, b):
    return a + b

three = add((1, 2))

Session TimeOut in web.xml

You can see many options as answer for your question, however you can use "-1" where the session never expires. Since you do not know how much time it will take for the thread to complete. E.g.:

   <session-config>
        <session-timeout>-1</session-timeout>
    </session-config>

Or if you don't want a timeout happening for some purpose:

<session-config>
    <session-timeout>0</session-timeout>
</session-config>

Another option could be increase the number to 1000, etc, etc, bla, bla, bla.

But if you really want to stop and you consider that is unnecessary for your application to force the user to logout, just add a logout button and the user will decide when to leave.

Here is what you can do to solve the problem if you do not need to force to logout, and in you are loading files that could take time base on server and your computer speed and the size of the file.

<!-- sets the default session timeout to 60 minutes. -->
   <!-- <session-config>
     <session-timeout>60</session-timeout>
   </session-config> -->

Just comment it or deleted that's it! Tan tararantan, tan tan!

Can't find bundle for base name

java.util.MissingResourceException: Can't find bundle for base name
    org.jfree.chart.LocalizationBundle, locale en_US

To the point, the exception message tells in detail that you need to have either of the following files in the classpath:

/org/jfree/chart/LocalizationBundle.properties

or

/org/jfree/chart/LocalizationBundle_en.properties

or

/org/jfree/chart/LocalizationBundle_en_US.properties

Also see the official Java tutorial about resourcebundles for more information.

But as this is actually a 3rd party managed properties file, you shouldn't create one yourself. It should be already available in the JFreeChart JAR file. So ensure that you have it available in the classpath during runtime. Also ensure that you're using the right version, the location of the propertiesfile inside the package tree might have changed per JFreeChart version.

When executing a JAR file, you can use the -cp argument to specify the classpath. E.g.:

java -jar -cp c:/path/to/jfreechart.jar yourfile.jar

Alternatively you can specify the classpath as class-path entry in the JAR's manifest file. You can use in there relative paths which are relative to the JAR file itself. Do not use the %CLASSPATH% environment variable, it's ignored by JAR's and everything else which aren't executed with java.exe without -cp, -classpath and -jar arguments.

How do I disable right click on my web page?

I know I am late, but I want to create some assumptions and explainations for the answer I am going to provide.

Can I disable right-click

Can I disable right click on my web page without using Javascript?

Yes, by using JavaScript you can disable any event that happens and you can do that mostly only by javaScript. How, all you need is:

  1. A working hardware

  2. A website or somewhere from which you can learn about the keycodes. Because you're gonna need them.

Now lets say you wanna block the enter key press here is the code:

function prevententer () {
 if(event.keyCode == 13) {
  return false;
 }
}

For the right click use this:

event.button == 2

in the place of event.keyCode. And you'll block it.

I want to ask this because most browsers allow users to disable it by Javascript.

You're right, browsers allow you to use JavaScript and javascript does the whole job for you. You donot need to setup anything, just need the script attribute in the head.

Why you should not disable it?

The main and the fast answer to that would be, users won't like it. Everyone needs freedom, no-one I mean no-one wants to be blocked or disabled, a few minutes ago I was at a site, which had blocked me from right clicking and I felt why? Do you need to secure your source code? Then here ctrl+shift+J I have opened the Console and now I can go to HTML-code tab. Go ahead and stop me. This won't add any of the security layer to your app.

There are alot of userful menus in the Right Click, like Copy, Paste, Search Google for 'text' (In Chrome) and many more. So user would like to get ease of access instead of remembering alot of keyboard shortcuts. Anyone can still copy the context, save the image or do whatever he wants.

Browsers use Mouse Navigation: Some browsers such as Opera uses mouse navigation, so if you disable it, user would definitely hate your User Interface and the scripts.

So that was the basic, I was going to write some more about saving the source code hehehe but, let it be the answer to your question.

Reference to the keycodes:

Key and mouse button code:

http://www.w3schools.com/jsref/event_button.asp

https://developer.mozilla.org/en-US/docs/Web/API/event.button (would be appreciated by the users too).

Why not to disable right click:

http://www.sitepoint.com/dont-disable-right-click/

Difference between jQuery’s .hide() and setting CSS to display: none

To use both is a nice answer; it's not a question of either or.

The advantage of using both is that the CSS will hide the element immediately when the page loads. The jQuery .hide will flash the element for a quarter of a second then hide it.

In the case when we want to have the element not shown when the page loads we can use CSS and set display:none & use the jQuery .hide(). If we plan to toggle the element we can use jQuery toggle.

Javascript Print iframe contents only

If you are setting the contents of IFrame using javascript document.write() then you must close the document by newWin.document.close(); otherwise the following code will not work and print will print the contents of whole page instead of only the IFrame contents.

var frm = document.getElementById(id).contentWindow;
frm.focus();// focus on contentWindow is needed on some ie versions
frm.print();

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

I encountered the same problem, beat my head up and found that I had changed the directory in the represotory from "/" to "/trunk" and forgot to do the "Switch" command, in TortoiseSVN!

invalid use of non-static member function

You must make Foo::comparator static or wrap it in a std::mem_fun class object. This is because lower_bounds() expects the comparer to be a class of object that has a call operator, like a function pointer or a functor object. Also, if you are using C++11 or later, you can also do as dwcanillas suggests and use a lambda function. C++11 also has std::bind too.

Examples:

// Binding:
std::lower_bounds(first, last, value, std::bind(&Foo::comparitor, this, _1, _2));
// Lambda:
std::lower_bounds(first, last, value, [](const Bar & first, const Bar & second) { return ...; });

Right align text in android TextView

try to add android:gravity="center" into TextView

Skipping Incompatible Libraries at compile

Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.

So, you need to look to see whether /dvlpmnt/libPI-Http.a is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32 option. Then you need to establish whether there is an alternative libPI-Http.a or libPI-Http.so file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.

To establish what is in that library, you may need to do:

mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk

The 'file' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.

How to tag docker image with docker-compose

If you specify image as well as build, then Compose names the built image with the webapp and optional tag specified in image:

build: ./dir
image: webapp:tag

This results in an image named webapp and tagged tag, built from ./dir.

https://docs.docker.com/compose/compose-file/#build

How to get address of a pointer in c/c++?

you can use this

in C

int a =10;
int *p = &a;     
int **pp = &p;
printf("%u",&p);

in C++

cout<<p;

How to pause for specific amount of time? (Excel/VBA)

Just a cleaned up version of clemo's code - works in Access, which doesn't have the Application.Wait function.

Public Sub Pause(sngSecs As Single)
    Dim sngEnd As Single
    sngEnd = Timer + sngSecs
    While Timer < sngEnd
        DoEvents
    Wend
End Sub

Public Sub TestPause()
    Pause 1
    MsgBox "done"
End Sub

select certain columns of a data table

First store the table in a view, then select columns from that view into a new table.

// Create a table with abitrary columns for use with the example
System.Data.DataTable table = new System.Data.DataTable();
for (int i = 1; i <= 11; i++)
    table.Columns.Add("col" + i.ToString());

// Load the table with contrived data
for (int i = 0; i < 100; i++)
{
    System.Data.DataRow row = table.NewRow();
    for (int j = 0; j < 11; j++)
        row[j] = i.ToString() + ", " + j.ToString();
    table.Rows.Add(row);
}

// Create the DataView of the DataTable
System.Data.DataView view = new System.Data.DataView(table);
// Create a new DataTable from the DataView with just the columns desired - and in the order desired
System.Data.DataTable selected = view.ToTable("Selected", false, "col1", "col2", "col6", "col7", "col3");

Used the sample data to test this method I found: Create ADO.NET DataView showing only selected Columns

Jquery Chosen plugin - dynamically populate list by Ajax

If you have two or more selects and use Steve McLenithan's answer, try to replace the first line with:

$('#CHOSENINPUTFIELDID_chosen > div > div input').autocomplete({

not remove suffix: _chosen

Finding the average of a list

I want to add just another approach

import itertools,operator
list(itertools.accumulate(l,operator.add)).pop(-1) / len(l)

What is JSONP, and why was it created?

A simple example for the usage of JSONP.

client.html

    <html>
    <head>
   </head>
     body>


    <input type="button" id="001" onclick=gO("getCompany") value="Company"  />
    <input type="button" id="002" onclick=gO("getPosition") value="Position"/>
    <h3>
    <div id="101">

    </div>
    </h3>

    <script type="text/javascript">

    var elem=document.getElementById("101");

    function gO(callback){

    script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'http://localhost/test/server.php?callback='+callback;
    elem.appendChild(script);
    elem.removeChild(script);


    }

    function getCompany(data){

    var message="The company you work for is "+data.company +"<img src='"+data.image+"'/   >";
    elem.innerHTML=message;
}

    function getPosition(data){
    var message="The position you are offered is "+data.position;
    elem.innerHTML=message;
    }
    </script>
    </body>
    </html>

server.php

  <?php

    $callback=$_GET["callback"];
    echo $callback;

    if($callback=='getCompany')
    $response="({\"company\":\"Google\",\"image\":\"xyz.jpg\"})";

    else
    $response="({\"position\":\"Development Intern\"})";
    echo $response;

    ?>    

Exit codes in Python

For the record, you can use POSIX standard exit codes defined here.

Example:

import sys, os

try:
    config()
except:
    sys.exit(os.EX_CONFIG) 
try:
    do_stuff()
except:
    sys.exit(os.EX_SOFTWARE)
sys.exit(os.EX_OK) # code 0, all ok

HTML 5 input type="number" element for floating point numbers on Chrome

Try <input type="number" step="any" />

It won't have validation problems and the arrows will have step of "1"

Constraint validation: When the element has an allowed value step, and the result of applying the algorithm to convert a string to a number to the string given by the element's value is a number, and that number subtracted from the step base is not an integral multiple of the allowed value step, the element is suffering from a step mismatch.

The following range control only accepts values in the range 0..1, and allows 256 steps in that range:

<input name=opacity type=range min=0 max=1 step=0.00392156863>

The following control allows any time in the day to be selected, with any accuracy (e.g. thousandth-of-a-second accuracy or more):

<input name=favtime type=time step=any>

Normally, time controls are limited to an accuracy of one minute.

http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-attributes.html#attr-input-step

How to set ID using javascript?

Do you mean like this?

var hello1 = document.getElementById('hello1');
hello1.id = btoa(hello1.id);

To further the example, say you wanted to get all elements with the class 'abc'. We can use querySelectorAll() to accomplish this:

HTML

<div class="abc"></div>
<div class="abc"></div>

JS

var abcElements = document.querySelectorAll('.abc');

// Set their ids
for (var i = 0; i < abcElements.length; i++)
    abcElements[i].id = 'abc-' + i;

This will assign the ID 'abc-<index number>' to each element. So it would come out like this:

<div class="abc" id="abc-0"></div>
<div class="abc" id="abc-1"></div>

To create an element and assign an id we can use document.createElement() and then appendChild().

var div = document.createElement('div');
div.id = 'hello1';

var body = document.querySelector('body');
body.appendChild(div);

Update

You can set the id on your element like this if your script is in your HTML file.

<input id="{{str(product["avt"]["fto"])}}" >
<span>New price :</span>
<span class="assign-me">

<script type="text/javascript">
    var s = document.getElementsByClassName('assign-me')[0];
    s.id = btoa({{str(produit["avt"]["fto"])}});
</script>

Your requirements still aren't 100% clear though.

Why is list initialization (using curly braces) better than the alternatives?

Basically copying and pasting from Bjarne Stroustrup's "The C++ Programming Language 4th Edition":

List initialization does not allow narrowing (§iso.8.5.4). That is:

  • An integer cannot be converted to another integer that cannot hold its value. For example, char to int is allowed, but not int to char.
  • A floating-point value cannot be converted to another floating-point type that cannot hold its value. For example, float to double is allowed, but not double to float.
  • A floating-point value cannot be converted to an integer type.
  • An integer value cannot be converted to a floating-point type.

Example:

void fun(double val, int val2) {

    int x2 = val;    // if val == 7.9, x2 becomes 7 (bad)

    char c2 = val2;  // if val2 == 1025, c2 becomes 1 (bad)

    int x3 {val};    // error: possible truncation (good)

    char c3 {val2};  // error: possible narrowing (good)

    char c4 {24};    // OK: 24 can be represented exactly as a char (good)

    char c5 {264};   // error (assuming 8-bit chars): 264 cannot be 
                     // represented as a char (good)

    int x4 {2.0};    // error: no double to int value conversion (good)

}

The only situation where = is preferred over {} is when using auto keyword to get the type determined by the initializer.

Example:

auto z1 {99};   // z1 is an int
auto z2 = {99}; // z2 is std::initializer_list<int>
auto z3 = 99;   // z3 is an int

Conclusion

Prefer {} initialization over alternatives unless you have a strong reason not to.

Explicit Return Type of Lambda

You can explicitly specify the return type of a lambda by using -> Type after the arguments list:

[]() -> Type { }

However, if a lambda has one statement and that statement is a return statement (and it returns an expression), the compiler can deduce the return type from the type of that one returned expression. You have multiple statements in your lambda, so it doesn't deduce the type.

How to hide TabPage from TabControl

Code Snippet for Hiding a TabPage

private void HideTab1_Click(object sender, EventArgs e)
{
    tabControl1.TabPages.Remove(tabPage1);
}

Code Snippet for Showing a TabPage

private void ShowTab1_Click(object sender, EventArgs e)
{
    tabControl1.TabPages.Add(tabPage1);
}

Getting a Request.Headers value

if ((Request.Headers["XYZComponent"] ?? "") == "true")
{
    // header is present and set to "true"
}

Kill python interpeter in linux from the terminal

pkill -9 python

should kill any running python process.

Global Angular CLI version greater than local version

npm uninstall --save-dev angular-cli
npm install --save-dev @angular/cli@latest

Your existing configuration can be updated automatically by running the following command:

ng update @angular/cli

or:

npm install

Compare two Timestamp in java

Use the before and after methods: Javadoc

if (mytime.after(fromtime) && mytime.before(totime))

Bind TextBox on Enter-key press

This is not an answer to the original question, but rather an extension of the accepted answer by @Samuel Jack. I did the following in my own application, and was in awe of the elegance of Samuel's solution. It is very clean, and very reusable, as it can be used on any control, not just the TextBox. I thought this should be shared with the community.

If you have a Window with a thousand TextBoxes that all require to update the Binding Source on Enter, you can attach this behaviour to all of them by including the XAML below into your Window Resources rather than attaching it to each TextBox. First you must implement the attached behaviour as per Samuel's post, of course.

<Window.Resources>
    <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
        <Style.Setters>
            <Setter Property="b:InputBindingsManager.UpdatePropertySourceWhenEnterPressed" Value="TextBox.Text"/>
        </Style.Setters>
    </Style>
</Window.Resources>

You can always limit the scope, if needed, by putting the Style into the Resources of one of the Window's child elements (i.e. a Grid) that contains the target TextBoxes.

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

In case this help out anyone else, in my case, I was using a CMK (it worked fine using the default aws/s3 key)

I had to go into my encryption key definition in IAM and add the programmatic user logged into boto3 to the list of users that "can use this key to encrypt and decrypt data from within applications and when using AWS services integrated with KMS.".

AngularJS Error: $injector:unpr Unknown Provider

In my case, I added a new service (file) to my app. That new service is injected in an existing controller. I did not miss new service dependency injection into that existing controller and did not declare my app module no more than one place. The same exception is thrown when I re-run my web app and my browser cache is not reset with a new service file codes. I simply refreshed my browser to get that new service file for browser cache, and the problem was gone.

Deleting all files in a directory with Python

you can create a function. Add maxdepth as you like for traversing subdirectories.

def findNremove(path,pattern,maxdepth=1):
    cpath=path.count(os.sep)
    for r,d,f in os.walk(path):
        if r.count(os.sep) - cpath <maxdepth:
            for files in f:
                if files.endswith(pattern):
                    try:
                        print "Removing %s" % (os.path.join(r,files))
                        #os.remove(os.path.join(r,files))
                    except Exception,e:
                        print e
                    else:
                        print "%s removed" % (os.path.join(r,files))

path=os.path.join("/home","dir1","dir2")
findNremove(path,".bak")

Border Radius of Table is not working

border-collapse: separate !important; worked.

Thanks.

HTML

<table class="bordered">
    <thead>
        <tr>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
            <th><label>Labels</label></th>
        </tr>
    </thead>

    <tbody>
        <tr>
            <td><label>Value</label></td>
            <td><label>Value</label></td>
            <td><label>Value</label></td>
            <td><label>Value</label></td>
            <td><label>Value</label></td>                            
        </tr>
    </tbody>                    
</table>

CSS

table {
    border-collapse: separate !important;
    border-spacing: 0;
    width: 600px;
    margin: 30px;
}
.bordered {
    border: solid #ccc 1px;
    -moz-border-radius: 6px;
    -webkit-border-radius: 6px;
    border-radius: 6px;
    -webkit-box-shadow: 0 1px 1px #ccc;
    -moz-box-shadow: 0 1px 1px #ccc;
    box-shadow: 0 1px 1px #ccc;
}
.bordered tr:hover {
    background: #ECECEC;    
    -webkit-transition: all 0.1s ease-in-out;
    -moz-transition: all 0.1s ease-in-out;
    transition: all 0.1s ease-in-out;
}
.bordered td, .bordered th {
    border-left: 1px solid #ccc;
    border-top: 1px solid #ccc;
    padding: 10px;
    text-align: left;
}
.bordered th {
    background-color: #ECECEC;
    background-image: -webkit-gradient(linear, left top, left bottom, from(#F8F8F8), to(#ECECEC));
    background-image: -webkit-linear-gradient(top, #F8F8F8, #ECECEC);
    background-image: -moz-linear-gradient(top, #F8F8F8, #ECECEC);    
    background-image: linear-gradient(top, #F8F8F8, #ECECEC);
    -webkit-box-shadow: 0 1px 0 rgba(255,255,255,.8) inset;
    -moz-box-shadow:0 1px 0 rgba(255,255,255,.8) inset;
    box-shadow: 0 1px 0 rgba(255,255,255,.8) inset;
    border-top: none;
    text-shadow: 0 1px 0 rgba(255,255,255,.5);
}
.bordered td:first-child, .bordered th:first-child {
    border-left: none;
}
.bordered th:first-child {
    -moz-border-radius: 6px 0 0 0;
    -webkit-border-radius: 6px 0 0 0;
    border-radius: 6px 0 0 0;
}
.bordered th:last-child {
    -moz-border-radius: 0 6px 0 0;
    -webkit-border-radius: 0 6px 0 0;
    border-radius: 0 6px 0 0;
}
.bordered th:only-child{
    -moz-border-radius: 6px 6px 0 0;
    -webkit-border-radius: 6px 6px 0 0;
    border-radius: 6px 6px 0 0;
}
.bordered tr:last-child td:first-child {
    -moz-border-radius: 0 0 0 6px;
    -webkit-border-radius: 0 0 0 6px;
    border-radius: 0 0 0 6px;
}
.bordered tr:last-child td:last-child {
    -moz-border-radius: 0 0 6px 0;
    -webkit-border-radius: 0 0 6px 0;
    border-radius: 0 0 6px 0;
} 

jsFiddle

How do I get rid of an element's offset using CSS?

If you're using the IE developer tools, make sure you haven't accidentally left them at an older setting. I was making myself crazy with this same issue until I saw that it was set to Internet Explorer 7 Standards. Changed it to Internet Explorer 9 Standards and everything snapped right into place.

adding css class to multiple elements

try this:

.button input, .button a {
//css here
}

That will apply the style to all a tags nested inside of <p class="button"></p>

How to find Google's IP address?

Here is a bash script that returns the IP (v4 and v6) ranges using @WorkWise's answer:

domainsToDig=$(dig @8.8.8.8 _spf.google.com TXT +short | \
    sed \
        -e 's/"v=spf1//' \
        -e 's/ ~all"//' \
        -e 's/ include:/\n/g' | \
    tail -n+2)
for domain in $domainsToDig ; do
    dig @8.8.8.8 $domain TXT +short | \
        sed \
            -e 's/"v=spf1//' \
            -e 's/ ~all"//' \
            -e 's/ ip.:/\n/g' | \
        tail -n+2
done

datetime to string with series in python pandas

There is no str accessor for datetimes and you can't do dates.astype(str) either, you can call apply and use datetime.strftime:

In [73]:

dates = pd.to_datetime(pd.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.apply(lambda x: x.strftime('%Y-%m-%d'))
Out[73]:
0    2001-01-01
1    2001-03-31
dtype: object

You can change the format of your date strings using whatever you like: strftime() and strptime() Behavior.

Update

As of version 0.17.0 you can do this using dt.strftime

dates.dt.strftime('%Y-%m-%d')

will now work

How to solve Object reference not set to an instance of an object.?

You need to initialize the list first:

protected List<string> list = new List<string>();

Save file/open file dialog box, using Swing & Netbeans GUI editor

Here is an example

private void doOpenFile() {
    int result = myFileChooser.showOpenDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
        Path path = myFileChooser.getSelectedFile().toPath();

        try {
            String contentString = "";

            for (String s : Files.readAllLines(path, StandardCharsets.UTF_8)) {
                contentString += s;
            }

            jText.setText(contentString);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

private void doSaveFile() {
    int result = myFileChooser.showSaveDialog(this);

    if (result == JFileChooser.APPROVE_OPTION) {
        // We'll be making a mytmp.txt file, write in there, then move it to
        // the selected
        // file. This takes care of clearing that file, should there be
        // content in it.
        File targetFile = myFileChooser.getSelectedFile();

        try {
            if (!targetFile.exists()) {
                targetFile.createNewFile();
            }

            FileWriter fw = new FileWriter(targetFile);

            fw.write(jText.getText());
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

How to get 30 days prior to current date?

Get next 30 days from today

_x000D_
_x000D_
let now = new Date()_x000D_
console.log('Today: ' + now.toUTCString())_x000D_
let next30days = new Date(now.setDate(now.getDate() + 30))_x000D_
console.log('Next 30th day: ' + next30days.toUTCString())
_x000D_
_x000D_
_x000D_

Get last 30 days form today

_x000D_
_x000D_
let now = new Date()_x000D_
console.log('Today: ' + now.toUTCString())_x000D_
let last30days = new Date(now.setDate(now.getDate() - 30))_x000D_
console.log('Last 30th day: ' + last30days.toUTCString())
_x000D_
_x000D_
_x000D_

How to redirect siteA to siteB with A or CNAME records

You can do this a number of non-DNS ways. The landing page at subdomain.hostone.com can have an HTTP redirect. The webserver at hostone.com can be configured to redirect (easy in Apache, not sure about IIS), etc.

Anaconda export Environment file

I find exporting the packages in string format only is more portable than exporting the whole conda environment. As the previous answer already suggested:

$ conda list -e > requirements.txt

However, this requirements.txt contains build numbers which are not portable between operating systems, e.g. between Mac and Ubuntu. In conda env export we have the option --no-builds but not with conda list -e, so we can remove the build number by issuing the following command:

$ sed -i -E "s/^(.*\=.*)(\=.*)/\1/" requirements.txt 

And recreate the environment on another computer:

conda create -n recreated_env --file requirements.txt 

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

It's an old question but the solution below (without a for loop) might be helpful:

def new_fun(df):
    prev_value = df.iloc[0]["C"]
    def func2(row):
        # non local variable ==> will use pre_value from the new_fun function
        nonlocal prev_value
        new_value =  prev_value * row['A'] + row['B']
        prev_value = row['C']
        return new_value
    # This line might throw a SettingWithCopyWarning warning
    df.iloc[1:]["C"] = df.iloc[1:].apply(func2, axis=1)
    return df

df = new_fun(df)

How to convert string to boolean php

You can use boolval($strValue)

Examples:

<?php
echo '0:        '.(boolval(0) ? 'true' : 'false')."\n";
echo '42:       '.(boolval(42) ? 'true' : 'false')."\n";
echo '0.0:      '.(boolval(0.0) ? 'true' : 'false')."\n";
echo '4.2:      '.(boolval(4.2) ? 'true' : 'false')."\n";
echo '"":       '.(boolval("") ? 'true' : 'false')."\n";
echo '"string": '.(boolval("string") ? 'true' : 'false')."\n";
echo '"0":      '.(boolval("0") ? 'true' : 'false')."\n";
echo '"1":      '.(boolval("1") ? 'true' : 'false')."\n";
echo '[1, 2]:   '.(boolval([1, 2]) ? 'true' : 'false')."\n";
echo '[]:       '.(boolval([]) ? 'true' : 'false')."\n";
echo 'stdClass: '.(boolval(new stdClass) ? 'true' : 'false')."\n";
?>

Documentation http://php.net/manual/es/function.boolval.php

python tuple to dict

Try:

>>> t = ((1, 'a'),(2, 'b'))
>>> dict((y, x) for x, y in t)
{'a': 1, 'b': 2}

How to vertically align text inside a flexbox?

You could change the ul and li displays to table and table-cell. Then, vertical-align would work for you:

ul {
    height: 20%;
    width: 100%;
    display: table;
}

li {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
    background: silver;
    width: 100%; 
}

http://codepen.io/anon/pen/pckvK

What is a StackOverflowError?

StackOverflowError is to the stack as OutOfMemoryError is to the heap.

Unbounded recursive calls result in stack space being used up.

The following example produces StackOverflowError:

class  StackOverflowDemo
{
    public static void unboundedRecursiveCall() {
     unboundedRecursiveCall();
    }

    public static void main(String[] args) 
    {
        unboundedRecursiveCall();
    }
}

StackOverflowError is avoidable if recursive calls are bounded to prevent the aggregate total of incomplete in-memory calls (in bytes) from exceeding the stack size (in bytes).

how to drop database in sqlite?

If you use SQLiteOpenHelper you can do this

        String myPath = DB_PATH + DB_NAME;
        SQLiteDatabase.deleteDatabase(new File(myPath));

for loop in Python

The range() function in python is a way to generate a sequence. Sequences are objects that can be indexed, like lists, strings, and tuples. An easy way to check for a sequence is to try retrieve indexed elements from them. It can also be checked using the Sequence Abstract Base Class(ABC) from the collections module.

from collections import Sequence as sq
isinstance(foo, sq)

The range() takes three arguments start, stop and step.

  1. start : The staring element of the required sequence
  2. stop : (n+1)th element of the required sequence
  3. step : The required gap between the elements of the sequence. It is an optional parameter that defaults to 1.

To get your desired result you can make use of the below syntax.

range(1,c+1,2)

How to start mongodb shell?

In the terminal, use "mongo" command to switch the terminal into the MongoDB shell:

$ mongo
MongoDB shell version: 2.6.10
connecting to: admin
>

Once you get > symbol in the terminal, you have entered into the MongoDB shell.

How to merge many PDF files into a single one?

There are lots of free tools that can do this.

I use PDFTK (a open source cross-platform command-line tool) for things like that.

Handle spring security authentication exceptions with @ExceptionHandler

I'm using the objectMapper. Every Rest Service is mostly working with json, and in one of your configs you have already configured an object mapper.

Code is written in Kotlin, hopefully it will be ok.

@Bean
fun objectMapper(): ObjectMapper {
    val objectMapper = ObjectMapper()
    objectMapper.registerModule(JodaModule())
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)

    return objectMapper
}

class UnauthorizedAuthenticationEntryPoint : BasicAuthenticationEntryPoint() {

    @Autowired
    lateinit var objectMapper: ObjectMapper

    @Throws(IOException::class, ServletException::class)
    override fun commence(request: HttpServletRequest, response: HttpServletResponse, authException: AuthenticationException) {
        response.addHeader("Content-Type", "application/json")
        response.status = HttpServletResponse.SC_UNAUTHORIZED

        val responseError = ResponseError(
            message = "${authException.message}",
        )

        objectMapper.writeValue(response.writer, responseError)
     }}

How can I delete one element from an array by value

I'm not sure if anyone has stated this, but Array.delete() and -= value will delete every instance of the value passed to it within the Array. In order to delete the first instance of the particular element you could do something like

arr = [1,3,2,44,5]
arr.delete_at(arr.index(44))

#=> [1,3,2,5]

There could be a simpler way. I'm not saying this is best practice, but it is something that should be recognized.

Convert a python dict to a string and back

Use the pickle module to save it to disk and load later on.

How to get exception message in Python properly

If you look at the documentation for the built-in errors, you'll see that most Exception classes assign their first argument as a message attribute. Not all of them do though.

Notably,EnvironmentError (with subclasses IOError and OSError) has a first argument of errno, second of strerror. There is no message... strerror is roughly analogous to what would normally be a message.

More generally, subclasses of Exception can do whatever they want. They may or may not have a message attribute. Future built-in Exceptions may not have a message attribute. Any Exception subclass imported from third-party libraries or user code may not have a message attribute.

I think the proper way of handling this is to identify the specific Exception subclasses you want to catch, and then catch only those instead of everything with an except Exception, then utilize whatever attributes that specific subclass defines however you want.

If you must print something, I think that printing the caught Exception itself is most likely to do what you want, whether it has a message attribute or not.

You could also check for the message attribute if you wanted, like this, but I wouldn't really suggest it as it just seems messy:

try:
    pass
except Exception as e:
    # Just print(e) is cleaner and more likely what you want,
    # but if you insist on printing message specifically whenever possible...
    if hasattr(e, 'message'):
        print(e.message)
    else:
        print(e)

using "if" and "else" Stored Procedures MySQL

I think that this construct: if exists (select... is specific for MS SQL. In MySQL EXISTS predicate tells you whether the subquery finds any rows and it's used like this: SELECT column1 FROM t1 WHERE EXISTS (SELECT * FROM t2);

You can rewrite the above lines of code like this:

DELIMITER $$

CREATE PROCEDURE `checando`(in nombrecillo varchar(30), in contrilla varchar(30), out resultado int)

BEGIN
    DECLARE count_prim INT;
    DECLARE count_sec INT;

    SELECT COUNT(*) INTO count_prim FROM compas WHERE nombre = nombrecillo AND contrasenia = contrilla;
    SELECT COUNT(*) INTO count_sec FROM FROM compas WHERE nombre = nombrecillo;

    if (count_prim > 0) then
        set resultado = 0;
    elseif (count_sec > 0) then
        set resultado = -1;
    else 
        set resultado = -2;
    end if;
    SELECT resultado;
END

PHP: Return all dates between two dates in an array

$report_starting_date=date('2014-09-16');
$report_ending_date=date('2014-09-26');
$report_starting_date1=date('Y-m-d',strtotime($report_starting_date.'-1 day'));
while (strtotime($report_starting_date1)<strtotime($report_ending_date))
{

    $report_starting_date1=date('Y-m-d',strtotime($report_starting_date1.'+1 day'));
    $dates[]=$report_starting_date1;
  } 
  print_r($dates);

 // dates    ('2014-09-16', '2014-09-26')


 //print result    Array
(
[0] => 2014-09-16
[1] => 2014-09-17
[2] => 2014-09-18
[3] => 2014-09-19
[4] => 2014-09-20
[5] => 2014-09-21
[6] => 2014-09-22
[7] => 2014-09-23
[8] => 2014-09-24
[9] => 2014-09-25
[10] => 2014-09-26
)

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

You could get a JavaScript object containing the parameters with something like this:

var regex = /[?&]([^=#]+)=([^&#]*)/g,
    url = window.location.href,
    params = {},
    match;
while(match = regex.exec(url)) {
    params[match[1]] = match[2];
}

The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by = characters, and pairs themselves separated by & characters (or an = character for the first one). For your example, the above would result in:

{v: "123", p: "hello"}

Here's a working example.

How can I set the opacity or transparency of a Panel in WinForms?

Yes, opacity can only work on top-level windows. It uses a hardware feature of the video adapter, that doesn't support child windows, like Panel. The only top-level Control derived class in Winforms is Form.

Several of the 'pure' Winform controls, the ones that do their own painting instead of letting a native Windows control do the job, do however support a transparent BackColor. Panel is one of them. It uses a trick, it asks the Parent to draw itself to produce the background pixels. One side-effect of this trick is that overlapping controls doesn't work, you only see the parent pixels, not the overlapped controls.

This sample form shows it at work:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        this.BackColor = Color.White;
        panel1.BackColor = Color.FromArgb(25, Color.Black);
    }
    protected override void OnPaint(PaintEventArgs e) {
        e.Graphics.DrawLine(Pens.Yellow, 0, 0, 100, 100);
    }
}

If that's not good enough then you need to consider stacking forms on top of each other. Like this.

Notable perhaps is that this restriction is lifted in Windows 8. It no longer uses the video adapter overlay feature and DWM (aka Aero) cannot be turned off anymore. Which makes opacity/transparency on child windows easy to implement. Relying on this is of course future-music for a while to come. Windows 7 will be the next XP :)

How can I test that a variable is more than eight characters in PowerShell?

You can also use -match against a Regular expression. Ex:

if ($dbUserName -match ".{8}" )
{
    Write-Output " Please enter more than 8 characters "
    $dbUserName=read-host " Re-enter database user name"
}

Also if you're like me and like your curly braces to be in the same horizontal position for your code blocks, you can put that on a new line, since it's expecting a code block it will look on next line. In some commands where the first curly brace has to be in-line with your command, you can use a grave accent marker (`) to tell powershell to treat the next line as a continuation.

How to compare two columns in Excel and if match, then copy the cell next to it

try this formula in column E:

=IF( AND( ISNUMBER(D2), D2=G2), H2, "")

your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )

you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.

I hope you understand my explanation.

what is the use of Eval() in asp.net

IrishChieftain didn't really address the question, so here's my take:

eval() is supposed to be used for data that is not known at run time. Whether that be user input (dangerous) or other sources.

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

Top guy is probably right that you downloaded instead of cloning the repo at start. Here is a easy solution without getting too technical.

  • In a new editor window, clone your repo in another directory.
  • Make a new branch.
  • Then copy from your your edited editor window into your new repo by copy paste.

Make sure that all your edits are copied over by looking at your older github branch.

How to change legend size with matplotlib.pyplot

you can reduce the legend size setting:

plt.legend(labelspacing=y, handletextpad=x,fontsize)  

labelspacing is the vertical space between each label.

handletextpad is the distance between the actual legend and your label.

And fontsize is self-explanatory

What is the difference between rb and r+b modes in file objects

My understanding is that adding r+ opens for both read and write (just like w+, though as pointed out in the comment, will truncate the file). The b just opens it in binary mode, which is supposed to be less aware of things like line separators (at least in C++).

How to lock orientation of one view controller to portrait mode only in Swift

Thanks to @bmjohn's answer above. Here is a working Xamarin / C# version of the that answer's code, to save others the time of transcription:

AppDelegate.cs

 public UIInterfaceOrientationMask OrientationLock = UIInterfaceOrientationMask.All;
 public override UIInterfaceOrientationMask GetSupportedInterfaceOrientations(UIApplication application, UIWindow forWindow)
 {
     return this.OrientationLock;
 }

Static OrientationUtility.cs class:

public static class OrientationUtility
{
    public static void LockOrientation(UIInterfaceOrientationMask orientation)
    {
        var appdelegate = (AppDelegate) UIApplication.SharedApplication.Delegate;
        if(appdelegate != null)
        {
            appdelegate.OrientationLock = orientation;
        }
    }

    public static void LockOrientation(UIInterfaceOrientationMask orientation, UIInterfaceOrientation RotateToOrientation)
    {
        LockOrientation(orientation);

        UIDevice.CurrentDevice.SetValueForKey(new NSNumber((int)RotateToOrientation), new NSString("orientation"));
    }
}

View Controller:

    public override void ViewDidAppear(bool animated)
    {
       base.ViewWillAppear(animated);
       OrientationUtility.LockOrientation(UIInterfaceOrientationMask.Portrait, UIInterfaceOrientation.Portrait);
    }

    public override void ViewWillDisappear(bool animated)
    {
        base.ViewWillDisappear(animated);
        OrientationUtility.LockOrientation(UIInterfaceOrientationMask.All);
    }

How to check command line parameter in ".bat" file?

Look at http://ss64.com/nt/if.html for an answer; the command is IF [%1]==[] GOTO NO_ARGUMENT or similar.

Doing a join across two databases with different collations on SQL Server and getting an error

A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.

It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)

select
    sone_field collate DATABASE_DEFAULT
from
    table_1
    inner join
    table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever

Convert regular Python string to raw string

With a little bit correcting @Jolly1234's Answer: here is the code:

raw_string=path.encode('unicode_escape').decode()

Drop shadow on a div container?

This works for me on all my browsers:

.shadow {
-moz-box-shadow: 0 0 30px 5px #999;
-webkit-box-shadow: 0 0 30px 5px #999;
}

then just give any div the shadow class, no jQuery required.

What is the use of adding a null key or value to a HashMap in Java?

Another example : I use it to group Data by date. But some data don't have date. I can group it with the header "NoDate"

Powershell script to see currently logged in users (domain and machine) + status (active, idle, away)

Since we're in the PowerShell area, it's extra useful if we can return a proper PowerShell object ...

I personally like this method of parsing, for the terseness:

((quser) -replace '^>', '') -replace '\s{2,}', ',' | ConvertFrom-Csv

Note: this doesn't account for disconnected ("disc") users, but works well if you just want to get a quick list of users and don't care about the rest of the information. I just wanted a list and didn't care if they were currently disconnected.

If you do care about the rest of the data it's just a little more complex:

(((quser) -replace '^>', '') -replace '\s{2,}', ',').Trim() | ForEach-Object {
    if ($_.Split(',').Count -eq 5) {
        Write-Output ($_ -replace '(^[^,]+)', '$1,')
    } else {
        Write-Output $_
    }
} | ConvertFrom-Csv

I take it a step farther and give you a very clean object on my blog.

I ended up making this into a module.

Switch case on type c#

The simplest thing to do could be to use dynamics, i.e. you define the simple methods like in Yuval Peled answer:

void Test(WebControl c)
{
...
}

void Test(ComboBox c)
{
...
}

Then you cannot call directly Test(obj), because overload resolution is done at compile time. You have to assign your object to a dynamic and then call the Test method:

dynamic dynObj = obj;
Test(dynObj);

matplotlib: plot multiple columns of pandas data frame on the bar chart

Although the accepted answer works fine, since v0.21.0rc1 it gives a warning

UserWarning: Pandas doesn't allow columns to be created via a new attribute name

Instead, one can do

df[["X", "A", "B", "C"]].plot(x="X", kind="bar")

Understanding repr( ) function in Python

When you say

foo = 'bar'
baz(foo)

you are not passing foo to the baz function. foo is just a name used to represent a value, in this case 'bar', and that value is passed to the baz function.

Why use #ifndef CLASS_H and #define CLASS_H in .h file but not in .cpp?

That's done for header files so that the contents only appear once in each preprocessed source file, even if it's included more than once (usually because it's included from other header files). The first time it's included, the symbol CLASS_H (known as an include guard) hasn't been defined yet, so all the contents of the file are included. Doing this defines the symbol, so if it's included again, the contents of the file (inside the #ifndef/#endif block) are skipped.

There's no need to do this for the source file itself since (normally) that's not included by any other files.

For your last question, class.h should contain the definition of the class, and declarations of all its members, associated functions, and whatever else, so that any file that includes it has enough information to use the class. The implementations of the functions can go in a separate source file; you only need the declarations to call them.

How do I move to end of line in Vim?

I can't see hotkey for macbook for use vim in standard terminal. Hope it will help someone. For macOS users (tested on macbook pro 2018):

fn + ? - move to beginning line

fn + ? - move to end line

fn + ? - move page up

fn + ? - move page down

fn + g - move the cursor to the beginning of the document

fn + shift + g - move the cursor to the end of the document

For the last two commands sometime needs to tap twice.

box-shadow on bootstrap 3 container

Add an additional div around all container divs you want the drop shadow to encapsulate. Add the classes drop-shadow and container to the additional div. The class .container will keep the fluidity. Use the class .drop-shadow (or whatever you like) to add the box-shadow property. Then target the .drop-shadow div and negate the unwanted styles .container adds--such as left & right padding.

Example: http://jsfiddle.net/SHLu4/2/

It'll be something like:

<div class="container drop-shadow">
    <div class="container">
        <div class="row">
            <div class="col-md-8">Main Area</div>
            <div class="col-md-4">Side Area</div>
        </div>
    </div>
</div>

And your CSS:

<style>
    .drop-shadow {
        -webkit-box-shadow: 0 0 5px 2px rgba(0, 0, 0, .5);
        box-shadow: 0 0 5px 2px rgba(0, 0, 0, .5);
    }
    .container.drop-shadow {
        padding-left:0;
        padding-right:0;
    }
</style>

How do I find which program is using port 80 in Windows?

Start menu → Accessories → right click on "Command prompt". In the menu, click "Run as Administrator" (on Windows XP you can just run it as usual), run netstat -anb, and then look through output for your program.

BTW, Skype by default tries to use ports 80 and 443 for incoming connections.

You can also run netstat -anb >%USERPROFILE%\ports.txt followed by start %USERPROFILE%\ports.txt to open the port and process list in a text editor, where you can search for the information you want.

You can also use PowerShell to parse netstat output and present it in a better way (or process it any way you want):

$proc = @{};
Get-Process | ForEach-Object { $proc.Add($_.Id, $_) };
netstat -aon | Select-String "\s*([^\s]+)\s+([^\s]+):([^\s]+)\s+([^\s]+):([^\s]+)\s+([^\s]+)?\s+([^\s]+)" | ForEach-Object {
    $g = $_.Matches[0].Groups;
    New-Object PSObject |
        Add-Member @{ Protocol =           $g[1].Value  } -PassThru |
        Add-Member @{ LocalAddress =       $g[2].Value  } -PassThru |
        Add-Member @{ LocalPort =     [int]$g[3].Value  } -PassThru |
        Add-Member @{ RemoteAddress =      $g[4].Value  } -PassThru |
        Add-Member @{ RemotePort =         $g[5].Value  } -PassThru |
        Add-Member @{ State =              $g[6].Value  } -PassThru |
        Add-Member @{ PID =           [int]$g[7].Value  } -PassThru |
        Add-Member @{ Process = $proc[[int]$g[7].Value] } -PassThru;
#} | Format-Table Protocol,LocalAddress,LocalPort,RemoteAddress,RemotePort,State -GroupBy @{Name='Process';Expression={$p=$_.Process;@{$True=$p.ProcessName; $False=$p.MainModule.FileName}[$p.MainModule -eq $Null] + ' PID: ' + $p.Id}} -AutoSize
} | Sort-Object PID | Out-GridView

Also it does not require elevation to run.

Laravel - Form Input - Multiple select for a one to many relationship

A multiple select is really just a select with a multiple attribute. With that in mind, it should be as easy as...

Form::select('sports[]', $sports, null, array('multiple'))

The first parameter is just the name, but post-fixing it with the [] will return it as an array when you use Input::get('sports').

The second parameter is an array of selectable options.

The third parameter is an array of options you want pre-selected.

The fourth parameter is actually setting this up as a multiple select dropdown by adding the multiple property to the actual select element..

Swipe ListView item From right to left show delete button

An app is available that demonstrates a listview that combines both swiping-to-delete and dragging to reorder items. The code is based on Chet Haase's code for swiping-to-delete and Daniel Olshansky's code for dragging-to-reorder.

Chet's code deletes an item immediately. I improved on this by making it function more like Gmail where swiping reveals a bottom view that indicates that the item is deleted but provides an Undo button where the user has the possibility to undo the deletion. Chet's code also has a bug in it. If you have less items in the listview than the height of the listview is and you delete the last item, the last item appears to not be deleted. This was fixed in my code.

Daniel's code requires pressing long on an item. Many users find this unintuitive as it tends to be a hidden function. Instead, I modified the code to allow for a "Move" button. You simply press on the button and drag the item. This is more in line with the way the Google News app works when you reorder news topics.

The source code along with a demo app is available at: https://github.com/JohannBlake/ListViewOrderAndSwipe

Chet and Daniel are both from Google.

Chet's video on deleting items can be viewed at: https://www.youtube.com/watch?v=YCHNAi9kJI4

Daniel's video on reordering items can be viewed at: https://www.youtube.com/watch?v=_BZIvjMgH-Q

A considerable amount of work went into gluing all this together to provide a seemless UI experience, so I'd appreciate a Like or Up Vote. Please also star the project in Github.

Return back to MainActivity from another activity

This usually works as well :)

navigateUpTo(new Intent(getBaseContext(), MainActivity.class));

Error QApplication: no such file or directory

I suggest you to update your SDK and start new project and recompile everything you have. It seems you have some inner program errors. Or you are missing package.

And ofc do what Abdijeek said.

Angular2 QuickStart npm start is not working correctly

Change the start field in package.json from

"start": "tsc && concurrently \"npm run tsc:w\" \"npm run lite\" "

to

"start": "concurrently \"npm run tsc:w\" \"npm run lite\" "

Add ArrayList to another ArrayList in java

Your Problem

Mainly, you've got 2 major problems:

You are using adding a List of Strings. You want a List containing Lists of Strings.

Note as well that when you invoke this:

NodeList.addAll(nodes);

... all you say is to add all elements of nodes (which is a list of Strings) to the (badly named) NodeList, which is using Objects and thus adds only the strings inside. Which leads me to the next point.

You seem to be confused between your nodes and NodeList. Your NodeList keeps growing over time, and that's what you add to your list.

So, even if doing things right, if we were to look at the end of each iteration at your nodes, nodeList and list, we'd see:

  • i = 0

    nodes: [PropertyStart,a,b,c,PropertyEnd]
    nodeList: [PropertyStart,a,b,c,PropertyEnd]
    list: [[PropertyStart,a,b,c,PropertyEnd]]
    
  • i = 1

    nodes: [PropertyStart,d,e,f,PropertyEnd]
    nodeList: [PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd]
    list: [[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd]]
    
  • i = 2

    nodes: [PropertyStart,g,h,i,PropertyEnd]
    nodeList: [PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,g,h,i,PropertyEnd]
    list: [[PropertyStart,a,b,c,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd, PropertyStart,d,e,f,PropertyEnd],[PropertyStart,a,b,c,PropertyEnd,PropertyStart,d,e,f,PropertyEnd,PropertyStart,g,h,i,PropertyEnd]]
    
  • and so on...

Some Other Corrections

Follow the Java Naming Conventions

Don't use variable names starting with uppercase letters. So here, replace NodeList with nodeList).

Learn a Bit More About Types

You say "I want the "list" array [...]". This is confusing for whoever you will be communicating with: It's not an array. It's an implementation of List backed by an array.

There's a difference between a type, an interface, and an implementation.

Use Generics for Stronger Typing in Collections

Use generic types, because static typing really helps with these errors. Also, use interfaces where possible, except if you have a good reason to use the concrete type.

So your code becomes:

List<String> nodes = new ArrayList<String>();
List<String> nodeList = new ArrayList<String>();
List<List<String>> list = new ArrayList<List<String>>();

Remove Unnecessary Code

You could do away with the nodeList entirely, and write the following once you've fixed your types:

list.add(nodes);

Use the Right Scope

Except if you have a very strong reason to do so, prefer to use the inner-most scope to declare variables and limit both their lifespan for their references and facilitate the separation of concerns in your code.

Here you could then move List<String> nodes to be declared within the loop (and then forget the nodes.clear() invocation).

A reason not to do this could be performance, as you might want to avoid recreating an ArrayList on each iteration of the loop, but it's very unlikely that's a concern to you (and clean, readable and maintainable code has priority over pre-optimized code).

SSCCE

Last but not least, if you want help give us the exact reproducible case with a short, self-Contained, correct example.

Here you give us your program's outputs, but don't mention how you got them, so we're left to assume you did a System.out.println(list). And you confused a lot of people, as I think the output you give us is not what you actually got.

How do I tell Maven to use the latest version of a dependency?

The truth is even in 3.x it still works, surprisingly the projects builds and deploys. But the LATEST/RELEASE keyword causing problems in m2e and eclipse all over the place, ALSO projects depends on the dependency which deployed through the LATEST/RELEASE fail to recognize the version.

It will also causing problem if you are try to define the version as property, and reference it else where.

So the conclusion is use the versions-maven-plugin if you can.

Find common substring between two strings

**Return the comman longest substring** 
def longestSubString(str1, str2):
    longestString = ""
    maxLength = 0
    for i in range(0, len(str1)):
        if str1[i] in str2:
            for j in range(i + 1, len(str1)):
                if str1[i:j] in str2:
                    if(len(str1[i:j]) > maxLength):
                        maxLength = len(str1[i:j])
                        longestString =  str1[i:j]
return longestString

AngularJS ng-if with multiple conditions

Sure you can. Something like:

HTML

<div ng-controller="fessCntrl">    
     <label ng-repeat="(key,val) in list">
       <input type="radio" name="localityTypeRadio" ng-model="$parent.localityTypeRadio" ng-value="key" />{{key}}
         <div ng-if="key == 'City' || key == 'County'">
             <pre>City or County !!! {{$parent.localityTypeRadio}}</pre>
         </div>
         <div ng-if="key == 'Town'">
             <pre>Town!!! {{$parent.localityTypeRadio}}</pre>
         </div>        
      </label>
</div>

JS

var fessmodule = angular.module('myModule', []);

fessmodule.controller('fessCntrl', function ($scope) {

    $scope.list = {
        City: [{name: "cityA"}, {name: "cityB"}],
        County: [{ name: "countyA"}, {name: "countyB"}],
        Town: [{ name: "townA"}, {name: "townB"}]
      };

    $scope.localityTypeRadio = 'City';
});

fessmodule.$inject = ['$scope'];

Demo Fiddle

How to convert an address into a Google Maps Link (NOT MAP)

Feb, 2016:

I needed to do this based on client entered database values and without a lat/long generator. Google really likes lat/long these days. Here is what I learned:

1 The beginning of the link looks like this: https://www.google.com/maps/place/

2 Then you put your address:

  • Use a + instead of any space.
  • Put a comma , in front and behind the city.
  • Include the postal/zip and the province/state.
  • Replace any # with nothing.
  • Replace any ++ or ++++ with single +

3 Put the address after the place/

4 Then put a slash at the end.

NOTE: The slash at the end was important. After the user clicks the link, Google goes ahead and appends more to the URL and they do it after this slash.

Working example for this question:

https://www.google.ca/maps/place/1200+Pennsylvania+Ave+SE,+Washington,+DC+20003/

I hope that helps.

How can I replace newline or \r\n with <br/>?

This will work for sure:

str_replace("\\r", "<br />", $description); 
str_replace("\\n", "<br />", $description); 

How does "cat << EOF" work in bash?

Worth noting that here docs work in bash loops too. This example shows how-to get the column list of table:

export postgres_db_name='my_db'
export table_name='my_table_name'

# start copy 
while read -r c; do test -z "$c" || echo $table_name.$c , ; done < <(cat << EOF | psql -t -q -d $postgres_db_name -v table_name="${table_name:-}"
SELECT column_name
FROM information_schema.columns
WHERE 1=1
AND table_schema = 'public'
AND table_name   =:'table_name'  ;
EOF
)
# stop copy , now paste straight into the bash shell ...

output: 
my_table_name.guid ,
my_table_name.id ,
my_table_name.level ,
my_table_name.seq ,

or even without the new line

while read -r c; do test -z "$c" || echo $table_name.$c , | perl -ne 
's/\n//gm;print' ; done < <(cat << EOF | psql -t -q -d $postgres_db_name -v table_name="${table_name:-}"
 SELECT column_name
 FROM information_schema.columns
 WHERE 1=1
 AND table_schema = 'public'
 AND table_name   =:'table_name'  ;
 EOF
 )

 # output: daily_issues.guid ,daily_issues.id ,daily_issues.level ,daily_issues.seq ,daily_issues.prio ,daily_issues.weight ,daily_issues.status ,daily_issues.category ,daily_issues.name ,daily_issues.description ,daily_issues.type ,daily_issues.owner

Print the contents of a DIV

Slight changes over earlier version - tested on CHROME

function PrintElem(elem)
{
    var mywindow = window.open('', 'PRINT', 'height=400,width=600');

    mywindow.document.write('<html><head><title>' + document.title  + '</title>');
    mywindow.document.write('</head><body >');
    mywindow.document.write('<h1>' + document.title  + '</h1>');
    mywindow.document.write(document.getElementById(elem).innerHTML);
    mywindow.document.write('</body></html>');

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

    mywindow.print();
    mywindow.close();

    return true;
}

How do I count the number of rows and columns in a file using bash?

awk 'BEGIN{FS=","}END{print "COLUMN NO: "NF " ROWS NO: "NR}' file

You can use any delimiter as field separator and can find numbers of ROWS and columns

Create an array with random values

var myArray = [];
var arrayMax = 40;
var limit = arrayMax + 1;
for (var i = 0; i < arrayMax; i++) {
  myArray.push(Math.floor(Math.random()*limit));
}

This above is the traditional way of doing it but I second @Pointy and @Phrogz if you want to avoid duplicates in your array without having to do expensive computation

Using Jquery Datatable with AngularJs

After many hours of experimenting with using jQueryDataTables with Angular, I found what I needed was available with a native Angular directive called ng-table. It provides sorting, pagination, and ajax reloads (sort of lazy loading capable with a few tweaks).

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

Please be aware that the accepted answer is a bit incomplete. Yes, at the most basic level Collation handles sorting. BUT, the comparison rules defined by the chosen Collation are used in many places outside of user queries against user data.

If "What does COLLATE SQL_Latin1_General_CP1_CI_AS do?" means "What does the COLLATE clause of CREATE DATABASE do?", then:

The COLLATE {collation_name} clause of the CREATE DATABASE statement specifies the default Collation of the Database, and not the Server; Database-level and Server-level default Collations control different things.

Server (i.e. Instance)-level controls:

  • Database-level Collation for system Databases: master, model, msdb, and tempdb.
  • Due to controlling the DB-level Collation of tempdb, it is then the default Collation for string columns in temporary tables (global and local), but not table variables.
  • Due to controlling the DB-level Collation of master, it is then the Collation used for Server-level data, such as Database names (i.e. name column in sys.databases), Login names, etc.
  • Handling of parameter / variable names
  • Handling of cursor names
  • Handling of GOTO labels
  • Default Collation used for newly created Databases when the COLLATE clause is missing

Database-level controls:

  • Default Collation used for newly created string columns (CHAR, VARCHAR, NCHAR, NVARCHAR, TEXT, and NTEXT -- but don't use TEXT or NTEXT) when the COLLATE clause is missing from the column definition. This goes for both CREATE TABLE and ALTER TABLE ... ADD statements.
  • Default Collation used for string literals (i.e. 'some text') and string variables (i.e. @StringVariable). This Collation is only ever used when comparing strings and variables to other strings and variables. When comparing strings / variables to columns, then the Collation of the column will be used.
  • The Collation used for Database-level meta-data, such as object names (i.e. sys.objects), column names (i.e. sys.columns), index names (i.e. sys.indexes), etc.
  • The Collation used for Database-level objects: tables, columns, indexes, etc.

Also:

  • ASCII is an encoding which is 8-bit (for common usage; technically "ASCII" is 7-bit with character values 0 - 127, and "ASCII Extended" is 8-bit with character values 0 - 255). This group is the same across cultures.
  • The Code Page is the "extended" part of Extended ASCII, and controls which characters are used for values 128 - 255. This group varies between each culture.
  • Latin1 does not mean "ASCII" since standard ASCII only covers values 0 - 127, and all code pages (that can be represented in SQL Server, and even NVARCHAR) map those same 128 values to the same characters.

If "What does COLLATE SQL_Latin1_General_CP1_CI_AS do?" means "What does this particular collation do?", then:

  • Because the name start with SQL_, this is a SQL Server collation, not a Windows collation. These are definitely obsolete, even if not officially deprecated, and are mainly for pre-SQL Server 2000 compatibility. Although, quite unfortunately SQL_Latin1_General_CP1_CI_AS is very common due to it being the default when installing on an OS using US English as its language. These collations should be avoided if at all possible.

    Windows collations (those with names not starting with SQL_) are newer, more functional, have consistent sorting between VARCHAR and NVARCHAR for the same values, and are being updated with additional / corrected sort weights and uppercase/lowercase mappings. These collations also don't have the potential performance problem that the SQL Server collations have: Impact on Indexes When Mixing VARCHAR and NVARCHAR Types.

  • Latin1_General is the culture / locale.
    • For NCHAR, NVARCHAR, and NTEXT data this determines the linguistic rules used for sorting and comparison.
    • For CHAR, VARCHAR, and TEXT data (columns, literals, and variables) this determines the:
      • linguistic rules used for sorting and comparison.
      • code page used to encode the characters. For example, Latin1_General collations use code page 1252, Hebrew collations use code page 1255, and so on.
  • CP{code_page} or {version}

    • For SQL Server collations: CP{code_page}, is the 8-bit code page that determines what characters map to values 128 - 255. While there are four code pages for Double-Byte Character Sets (DBCS) that can use 2-byte combinations to create more than 256 characters, these are not available for the SQL Server collations.
    • For Windows collations: {version}, while not present in all collation names, refers to the SQL Server version in which the collation was introduced (for the most part). Windows collations with no version number in the name are version 80 (meaning SQL Server 2000 as that is version 8.0). Not all versions of SQL Server come with new collations, so there are gaps in the version numbers. There are some that are 90 (for SQL Server 2005, which is version 9.0), most are 100 (for SQL Server 2008, version 10.0), and a small set has 140 (for SQL Server 2017, version 14.0).

      I said "for the most part" because the collations ending in _SC were introduced in SQL Server 2012 (version 11.0), but the underlying data wasn't new, they merely added support for supplementary characters for the built-in functions. So, those endings exist for version 90 and 100 collations, but only starting in SQL Server 2012.

  • Next you have the sensitivities, that can be in any combination of the following, but always specified in this order:
    • CS = case-sensitive or CI = case-insensitive
    • AS = accent-sensitive or AI = accent-insensitive
    • KS = Kana type-sensitive or missing = Kana type-insensitive
    • WS = width-sensitive or missing = width insensitive
    • VSS = variation selector sensitive (only available in the version 140 collations) or missing = variation selector insensitive
  • Optional last piece:

    • _SC at the end means "Supplementary Character support". The "support" only affects how the built-in functions interpret surrogate pairs (which are how supplementary characters are encoded in UTF-16). Without _SC at the end (or _140_ in the middle), built-in functions don't see a single supplementary character, but instead see two meaningless code points that make up the surrogate pair. This ending can be added to any non-binary, version 90 or 100 collation.
    • _BIN or _BIN2 at the end means "binary" sorting and comparison. Data is still stored the same, but there are no linguistic rules. This ending is never combined with any of the 5 sensitivities or _SC. _BIN is the older style, and _BIN2 is the newer, more accurate style. If using SQL Server 2005 or newer, use _BIN2. For details on the differences between _BIN and _BIN2, please see: Differences Between the Various Binary Collations (Cultures, Versions, and BIN vs BIN2).
    • _UTF8 is a new option as of SQL Server 2019. It's an 8-bit encoding that allows for Unicode data to be stored in VARCHAR and CHAR datatypes (but not the deprecated TEXT datatype). This option can only be used on collations that support supplementary characters (i.e. version 90 or 100 collations with _SC in their name, and version 140 collations). There is also a single binary _UTF8 collation (_BIN2, not _BIN).

      PLEASE NOTE: UTF-8 was designed / created for compatibility with environments / code that are set up for 8-bit encodings yet want to support Unicode. Even though there are a few scenarios where UTF-8 can provide up to 50% space savings as compared to NVARCHAR, that is a side-effect and has a cost of a slight hit to performance in many / most operations. If you need this for compatibility, then the cost is acceptable. If you want this for space-savings, you had better test, and TEST AGAIN. Testing includes all functionality, and more than just a few rows of data. Be warned that UTF-8 collations work best when ALL columns, and the database itself, are using VARCHAR data (columns, variables, string literals) with a _UTF8 collation. This is the natural state for anyone using this for compatibility, but not for those hoping to use it for space-savings. Be careful when mixing VARCHAR data using a _UTF8 collation with either VARCHAR data using non-_UTF8 collations or NVARCHAR data, as you might experience odd behavior / data loss. For more details on the new UTF-8 collations, please see: Native UTF-8 Support in SQL Server 2019: Savior or False Prophet?

Rollback a Git merge

git revert -m 1 88113a64a21bf8a51409ee2a1321442fd08db705

But may have unexpected side-effects. See --mainline parent-number option in git-scm.com/docs/git-revert

Perhaps a brute but effective way would be to check out the left parent of that commit, make a copy of all the files, checkout HEAD again, and replace all the contents with the old files. Then git will tell you what is being rolled back and you create your own revert commit :) !

Tomcat is not deploying my web project from Eclipse

I have the same problem, my solution is:

  • Install WTP Maven integration (don't know if this is necessary)
  • Project -> Run Configurations (Select your tomcat server) -> Run

For a few hours I tried to deploy and start application using Servers window but it didn't worked. My war was not placed in wptwebapps folder, manually deplying war to webapps worked.

Using Run Configurations made my app finally deployable...

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

I am finally able to solve this error after researching some things I thought is causing the error for 24 errors. I visited all the pages across the web. And I am happy to say that I have found the solution. If you are using NGINX, then set gzip to off and add proxy_max_temp_file_size 0; in the server block like I have shown below.

 server {
  ...
  ...
  gzip off;
  proxy_max_temp_file_size 0;
  location / {
    proxy_pass http://127.0.0.1:3000/;
  ....

Why? Because what actually happening was all the contents were being compressed twice and we don't want that, right?!

How to switch activity without animation in Android?

create your own style overriding android:Theme

<style name="noAnimationStyle" parent="android:Theme">
    <item name="android:windowAnimationStyle">@null</item>
</style>

Then use it in manifest like this:

<activity android:name=".MainActivity"
    android:theme="@style/noAnimationStyle">
</activity>

Make body have 100% of the browser height

If you don't want the work of editing your own CSS file and define the height rules by yourself, the most typical CSS frameworks also solve this issue with the body element filling the entirety of the page, among other issues, at ease with multiple sizes of viewports.

For example, Tacit CSS framework solves this issue out of the box, where you don't need to define any CSS rules and classes and you just include the CSS file in your HTML.

random.seed(): What does it do?

# Simple Python program to understand random.seed() importance

import random

random.seed(10)

for i in range(5):    
    print(random.randint(1, 100))

Execute the above program multiple times...

1st attempt: prints 5 random integers in the range of 1 - 100

2nd attempt: prints same 5 random numbers appeared in the above execution.

3rd attempt: same

.....So on

Explanation: Every time we are running the above program we are setting seed to 10, then random generator takes this as a reference variable. And then by doing some predefined formula, it generates a random number.

Hence setting seed to 10 in the next execution again sets reference number to 10 and again the same behavior starts...

As soon as we reset the seed value it gives the same plants.

Note: Change the seed value and run the program, you'll see a different random sequence than the previous one.

Spring Bean Scopes

Detailed explanation for each scope can be found here in Spring bean scopes. Below is the summary

Singleton - (Default) Scopes a single bean definition to a single object instance per Spring IoC container.

prototype - Scopes a single bean definition to any number of object instances.

request - Scopes a single bean definition to the lifecycle of a single HTTP request; that is, each HTTP request has its own instance of a bean created off the back of a single bean definition. Only valid in the context of a web-aware Spring ApplicationContext.

session - Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in the context of a web-aware Spring ApplicationContext.

global session - Scopes a single bean definition to the lifecycle of a global HTTP Session. Typically only valid when used in a portlet context. Only valid in the context of a web-aware Spring ApplicationContext.

How to extract the decision rules from scikit-learn decision-tree?

Modified Zelazny7's code to fetch SQL from the decision tree.

# SQL from decision tree

def get_lineage(tree, feature_names):
     left      = tree.tree_.children_left
     right     = tree.tree_.children_right
     threshold = tree.tree_.threshold
     features  = [feature_names[i] for i in tree.tree_.feature]
     le='<='               
     g ='>'
     # get ids of child nodes
     idx = np.argwhere(left == -1)[:,0]     

     def recurse(left, right, child, lineage=None):          
          if lineage is None:
               lineage = [child]
          if child in left:
               parent = np.where(left == child)[0].item()
               split = 'l'
          else:
               parent = np.where(right == child)[0].item()
               split = 'r'
          lineage.append((parent, split, threshold[parent], features[parent]))
          if parent == 0:
               lineage.reverse()
               return lineage
          else:
               return recurse(left, right, parent, lineage)
     print 'case '
     for j,child in enumerate(idx):
        clause=' when '
        for node in recurse(left, right, child):
            if len(str(node))<3:
                continue
            i=node
            if i[1]=='l':  sign=le 
            else: sign=g
            clause=clause+i[3]+sign+str(i[2])+' and '
        clause=clause[:-4]+' then '+str(j)
        print clause
     print 'else 99 end as clusters'

Get current controller in view

Just use:

ViewContext.Controller.GetType().Name

This will give you the whole Controller's Name

Why should Java 8's Optional not be used in arguments

Accepting Optional as parameters causes unnecessary wrapping at caller level.

For example in the case of:

public int calculateSomething(Optional<String> p1, Optional<BigDecimal> p2 {}

Suppose you have two not-null strings (ie. returned from some other method):

String p1 = "p1"; 
String p2 = "p2";

You're forced to wrap them in Optional even if you know they are not Empty.

This get even worse when you have to compose with other "mappable" structures, ie. Eithers:

Either<Error, String> value = compute().right().map((s) -> calculateSomething(
< here you have to wrap the parameter in a Optional even if you know it's a 
  string >));

ref:

methods shouldn't expect Option as parameters, this is almost always a code smell that indicated a leakage of control flow from the caller to the callee, it should be responsibility of the caller to check the content of an Option

ref. https://github.com/teamdigitale/digital-citizenship-functions/pull/148#discussion_r170862749

How to disable horizontal scrolling of UIScrollView?

I struggled with this for some time trying unsuccessfully the various suggestions in this and other threads.

However, in another thread (not sure where) someone suggested that using a negative constraint on the UIScrollView worked for him.

So I tried various combinations of constraints with inconsistent results. What eventually worked for me was to add leading and trailing constraints of -32 to the scrollview and add an (invisible) textview with a width of 320 (and centered).

startForeground fail after upgrade to Android 8.1

In my case, it's because we tried to post a notification without specifying the NotificationChannel:

public static final String NOTIFICATION_CHANNEL_ID_SERVICE = "com.mypackage.service";
public static final String NOTIFICATION_CHANNEL_ID_TASK = "com.mypackage.download_info";

public void initChannel(){
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_SERVICE, "App Service", NotificationManager.IMPORTANCE_DEFAULT));
        nm.createNotificationChannel(new NotificationChannel(NOTIFICATION_CHANNEL_ID_INFO, "Download Info", NotificationManager.IMPORTANCE_DEFAULT));
    }
}

The best place to put above code is in onCreate() method in the Application class, so that we just need to declare it once for all:

public class App extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        initChannel();
    }
}

After we set this up, we can use notification with the channelId we just specified:

Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID_INFO);
            .setContentIntent(pi)
            .setWhen(System.currentTimeMillis())
            .setContentTitle("VirtualBox.exe")
            .setContentText("Download completed")
            .setSmallIcon(R.mipmap.ic_launcher);

Then, we can use it to post a notification:

int notifId = 45;
NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.notify(notifId, builder.build());

If you want to use it as foreground service's notification:

startForeground(notifId, builder.build());

check null,empty or undefined angularjs

You can use angular's function called angular.isUndefined(value) returns boolean.

You may read more about angular's functions here: AngularJS Functions (isUndefined)

jquery find closest previous sibling with class

You can follow this code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
    $(document).ready(function () {
        $(".add").on("click", function () {
            var v = $(this).closest(".division").find("input[name='roll']").val();
            alert(v);
        });
    });
</script>
<?php

for ($i = 1; $i <= 5; $i++) {
    echo'<div class = "division">'
        . '<form method="POST" action="">'
        . '<p><input type="number" name="roll" placeholder="Enter Roll"></p>'
        . '<p><input type="button" class="add" name = "submit" value = "Click"></p>'
        . '</form></div>';
}
?>

You can get idea from this.

How to test if a file is a directory in a batch script?

A variation of @batchman61's approach (checking the Directory attribute).

This time I use an external 'find' command.

(Oh, and note the && trick. This is to avoid the long boring IF ERRORLEVEL syntax.)

@ECHO OFF
SETLOCAL EnableExtensions
ECHO.%~a1 | find "d" >NUL 2>NUL && (
    ECHO %1 is a directory
)

Outputs yes on:

  • Directories.
  • Directory symbolic links or junctions.
  • Broken directory symbolic links or junctions. (Doesn't try to resolve links.)
  • Directories which you have no read permission on (e.g. "C:\System Volume Information")

Python: Get the first character of the first string in a list?

You almost had it right. The simplest way is

mylist[0][0]   # get the first character from the first item in the list

but

mylist[0][:1]  # get up to the first character in the first item in the list

would also work.

You want to end after the first character (character zero), not start after the first character (character zero), which is what the code in your question means.

html <input type="text" /> onchange event not working

onkeyup worked for me. onkeypress doesn't trigger when pressing back space.

UEFA/FIFA scores API

http://api.football-data.org/index is free and useful. The API is in active development, stable and recently the first versioned release called alpha was put online. Check the blog section to follow updates and changes.

Converting a year from 4 digit to 2 digit and back again in C#

This should work for you:

public int Get4LetterYear(int twoLetterYear)
{
    int firstTwoDigits =
        Convert.ToInt32(DateTime.Now.Year.ToString().Substring(2, 2));
    return Get4LetterYear(twoLetterYear, firstTwoDigits);
}

public int Get4LetterYear(int twoLetterYear, int firstTwoDigits)
{
    return Convert.ToInt32(firstTwoDigits.ToString() + twoLetterYear.ToString());
}

public int Get2LetterYear(int fourLetterYear)
{
    return Convert.ToInt32(fourLetterYear.ToString().Substring(2, 2));
}

I don't think there are any special built-in stuff in .NET.

Update: It's missing some validation that you maybe should do. Validate length of inputted variables, and so on.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

The answer is not efficiency. Non-reentrant mutexes lead to better code.

Example: A::foo() acquires the lock. It then calls B::bar(). This worked fine when you wrote it. But sometime later someone changes B::bar() to call A::baz(), which also acquires the lock.

Well, if you don't have recursive mutexes, this deadlocks. If you do have them, it runs, but it may break. A::foo() may have left the object in an inconsistent state before calling bar(), on the assumption that baz() couldn't get run because it also acquires the mutex. But it probably shouldn't run! The person who wrote A::foo() assumed that nobody could call A::baz() at the same time - that's the entire reason that both of those methods acquired the lock.

The right mental model for using mutexes: The mutex protects an invariant. When the mutex is held, the invariant may change, but before releasing the mutex, the invariant is re-established. Reentrant locks are dangerous because the second time you acquire the lock you can't be sure the invariant is true any more.

If you are happy with reentrant locks, it is only because you have not had to debug a problem like this before. Java has non-reentrant locks these days in java.util.concurrent.locks, by the way.

android View not attached to window manager

Another option is not to start the async task until the dialog is attached to the window by overriding onAttachedToWindow() on the dialog, that way it is always dismissible.

How to check if an object implements an interface?

Use

if (gor instanceof Monster) {
    //...
}

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

Try to use
for today:

SELECT * FROM `tbl_name` where DATE(column_name) = CURDATE()


for selected date:

SELECT * FROM `tbl_name` where DATE(column_name) = DATE('2016-01-14')

Copy rows from one Datatable to another DataTable?

Copy Specified Rows from Table to another

// here dttablenew is a new Table  and dttableOld is table Which having the data 

dttableNew  = dttableOld.Clone();  

foreach (DataRow drtableOld in dttableOld.Rows)
{
   if (/*put some Condition */)
   {
      dtTableNew.ImportRow(drtableOld);
   }
}

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

I did a small benchmark on this topic. While many of the other posters have made good points about compatibility, my experience has been that PyPy isn't that much faster for just moving around bits. For many uses of Python, it really only exists to translate bits between two or more services. For example, not many web applications are performing CPU intensive analysis of datasets. Instead, they take some bytes from a client, store them in some sort of database, and later return them to other clients. Sometimes the format of the data is changed.

The BDFL and the CPython developers are a remarkably intelligent group of people and have a managed to help CPython perform excellent in such a scenario. Here's a shameless blog plug: http://www.hydrogen18.com/blog/unpickling-buffers.html . I'm using Stackless, which is derived from CPython and retains the full C module interface. I didn't find any advantage to using PyPy in that case.

html tables & inline styles

This should do the trick:

<table width="400" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="50" height="40" valign="top" rowspan="3">
      <img alt="" src="" width="40" height="40" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
    <td width="350" height="40" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">LAST FIRST</a><br>
REALTOR | P 123.456.789
    </td>
  </tr>
  <tr>
    <td width="350" height="70" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="" src="" width="200" height="60" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
  </tr>
  <tr>
    <td width="350" height="20" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
    </td>
  </tr>
</table>

UPDATE: Adjusted code per the comments:

After viewing your jsFiddle, an important thing to note about tables is that table cell widths in each additional row all have to be the same width as the first, and all cells must add to the total width of your table.

Here is an example that will NOT WORK:

<table width="600" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" bgcolor="#252525">&nbsp;
    </td>
    <td width="400" bgcolor="#454545">&nbsp;
    </td>
  </tr>
  <tr>
    <td width="300" bgcolor="#252525">&nbsp;
    </td>
    <td width="300" bgcolor="#454545">&nbsp;
    </td>
  </tr>
</table>

Although the 2nd row does add up to 600, it (and any additional rows) must have the same 200-400 split as the first row, unless you are using colspans. If you use a colspan, you could have one row, but it needs to have the same width as the cells it is spanning, so this works:

<table width="600" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" bgcolor="#252525">&nbsp;
    </td>
    <td width="400" bgcolor="#454545">&nbsp;
    </td>
  </tr>
  <tr>
    <td width="600" colspan="2" bgcolor="#353535">&nbsp;
    </td>
  </tr>
</table>

Not a full tutorial, but I hope that helps steer you in the right direction in the future.

Here is the code you are after:

<table width="900" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="57" height="43" valign="top" rowspan="2">
      <img alt="Rashel Adragna" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_head.png" width="47" height="43" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
    <td width="843" height="43" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">RASHEL ADRAGNA</a><br>
REALTOR | P 855.900.24KW
    </td>
  </tr>
  <tr>
    <td width="843" height="64" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="Zopa Realty Group logo" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_logo.png" width="177" height="54" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
  </tr>
  <tr>
    <td width="843" colspan="2" height="20" valign="bottom" align="center" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
    </td>
  </tr>
</table>

You'll note that I've added an extra 10px to some of your table cells. This in combination with align/valigns act as padding between your cells. It is a clever way to aviod actually having to add padding, margins or empty padding cells.

Difference between wait and sleep

From oracle documentation page on wait() method of Object:

public final void wait()
  1. Causes the current thread to wait until another thread invokes the notify() method or the notifyAll() method for this object. In other words, this method behaves exactly as if it simply performs the call wait(0).
  2. The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up
  3. interrupts and spurious wakeups are possible
  4. This method should only be called by a thread that is the owner of this object's monitor

This method throws

  1. IllegalMonitorStateException - if the current thread is not the owner of the object's monitor.

  2. InterruptedException - if any thread interrupted the current thread before or while the current thread was waiting for a notification. The interrupted status of the current thread is cleared when this exception is thrown.

From oracle documentation page on sleep() method of Thread class:

public static void sleep(long millis)
  1. Causes the currently executing thread to sleep (temporarily cease execution) for the specified number of milliseconds, subject to the precision and accuracy of system timers and schedulers.
  2. The thread does not lose ownership of any monitors.

This method throws:

  1. IllegalArgumentException - if the value of millis is negative

  2. InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

Other key difference:

wait() is a non-static method (instance method) unlike static method sleep() (class method).

How to sort two lists (which reference each other) in the exact same way

I would like to expand open jfs's answer, which worked great for my problem: sorting two lists by a third, decorated list:

We can create our decorated list in any way, but in this case we will create it from the elements of one of the two original lists, that we want to sort:

# say we have the following list and we want to sort both by the algorithms name 
# (if we were to sort by the string_list, it would sort by the numerical 
# value in the strings)
string_list = ["0.123 Algo. XYZ", "0.345 Algo. BCD", "0.987 Algo. ABC"]
dict_list = [{"dict_xyz": "XYZ"}, {"dict_bcd": "BCD"}, {"dict_abc": "ABC"}]

# thus we need to create the decorator list, which we can now use to sort
decorated = [text[6:] for text in string_list]  
# decorated list to sort
>>> decorated
['Algo. XYZ', 'Algo. BCD', 'Algo. ABC']

Now we can apply jfs's solution to sort our two lists by the third

# create and sort the list of indices
sorted_indices = list(range(len(string_list)))
sorted_indices.sort(key=decorated.__getitem__)

# map sorted indices to the two, original lists
sorted_stringList = list(map(string_list.__getitem__, sorted_indices))
sorted_dictList = list(map(dict_list.__getitem__, sorted_indices))

# output
>>> sorted_stringList
['0.987 Algo. ABC', '0.345 Algo. BCD', '0.123 Algo. XYZ']
>>> sorted_dictList
[{'dict_abc': 'ABC'}, {'dict_bcd': 'BCD'}, {'dict_xyz': 'XYZ'}]

Software Design vs. Software Architecture

I'd say you are right, in my own words;

Architecture is the allocation of system requirements to system elements. Four statements about an architecture:

  1. It can introduce non-functional requirements like language or patterns.
  2. It defines the interaction between components, interfaces, timing, etc.
  3. It shall not introduce new functionality,
  4. It allocates the (designed) functions that the system is intended to perform to elements.

Architecture is an essential engineering step when a complexity of the system is subdivided.

Example: Think about your house, you don't need an architect for your kitchen (only one element involved) but the complete building needs some interaction definitions, like doors, and a roof.

Design is a informative representation of the (proposed) implementation of the function. It is intended to elicit feedback and to discuss with stakeholders. It might be good practice but is not an essential engineering step.

It would be nice to see the kitchen design see before the kitchen is installed but it is not essential for the cooking requirement:

If I think about it you can state:

  • architecture is for a public/engineers on a more detailed abstraction level
  • design is intended for public on a less detailed abstraction level

Deleting all records in a database table

If you mean delete every instance of all models, I would use

ActiveRecord::Base.connection.tables.map(&:classify)
  .map{|name| name.constantize if Object.const_defined?(name)}
  .compact.each(&:delete_all)

How to change font size in Eclipse for Java text editors?

If you are using STS, then goto STS/Contents/Eclipse directory and open the STS.ini file.

From the STS.ini file, remove the flooring line:

-Dorg.eclipse.swt.internal.carbon.smallFonts

And restart the STS.

JQuery wait for page to finish loading before starting the slideshow?

you can try

$(function()
{

$(window).bind('load', function()
{

// INSERT YOUR CODE THAT WILL BE EXECUTED AFTER THE PAGE COMPLETELY LOADED...

});
});

i had the same problem and this code worked for me. how it works for you too!

heroku - how to see all the logs

for WAR files:

I did not use github, instead I uploaded directly, a WAR file ( which I found to be much easier and faster ).

So the following helped me:

heroku logs --app appname

Hope it will help someone.

Change/Get check state of CheckBox

var val = $("#checkboxId").is(":checked");

Style input element to fill remaining width of its container

I suggest using Flexbox:

Be sure to add the proper vendor prefixes though!

_x000D_
_x000D_
form {_x000D_
  width: 400px;_x000D_
  border: 1px solid black;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
input {_x000D_
  flex: 2;_x000D_
}_x000D_
_x000D_
input, label {_x000D_
  margin: 5px;_x000D_
}
_x000D_
<form method="post">_x000D_
  <label for="myInput">Sample label</label>_x000D_
  <input type="text" id="myInput" placeholder="Sample Input"/>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Converting ArrayList to HashMap

Using a supposed name property as the map key:

for (Product p: productList) { s.put(p.getName(), p); }

How do I integrate Ajax with Django applications?

I have tried to use AjaxableResponseMixin in my project, but had ended up with the following error message:

ImproperlyConfigured: No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model.

That is because the CreateView will return a redirect response instead of returning a HttpResponse when you to send JSON request to the browser. So I have made some changes to the AjaxableResponseMixin. If the request is an ajax request, it will not call the super.form_valid method, just call the form.save() directly.

from django.http import JsonResponse
from django import forms
from django.db import models

class AjaxableResponseMixin(object):
    success_return_code = 1
    error_return_code = 0
    """
    Mixin to add AJAX support to a form.
    Must be used with an object-based FormView (e.g. CreateView)
    """
    def form_invalid(self, form):
        response = super(AjaxableResponseMixin, self).form_invalid(form)
        if self.request.is_ajax():
            form.errors.update({'result': self.error_return_code})
            return JsonResponse(form.errors, status=400)
        else:
            return response

    def form_valid(self, form):
        # We make sure to call the parent's form_valid() method because
        # it might do some processing (in the case of CreateView, it will
        # call form.save() for example).
        if self.request.is_ajax():
            self.object = form.save()
            data = {
                'result': self.success_return_code
            }
            return JsonResponse(data)
        else:
            response = super(AjaxableResponseMixin, self).form_valid(form)
            return response

class Product(models.Model):
    name = models.CharField('product name', max_length=255)

class ProductAddForm(forms.ModelForm):
    '''
    Product add form
    '''
    class Meta:
        model = Product
        exclude = ['id']


class PriceUnitAddView(AjaxableResponseMixin, CreateView):
    '''
    Product add view
    '''
    model = Product
    form_class = ProductAddForm

How to add LocalDB to Visual Studio 2015 Community's SQL Server Object Explorer?

I tried to install only LocalDB, which was missed in my VS 2015 installation. Followed below URL & selectively download the LocalDB (2012) installer which is only 33mb in size :)

https://www.microsoft.com/en-us/download/details.aspx?id=29062

If you are looking for the SQL Server Data Tool for Visual Studio 2015 Integration, then Please download that from :

https://msdn.microsoft.com/en-us/mt186501

How do I capture response of form.submit

This is my code for this problem:

<form id="formoid" action="./demoText.php" title="" method="post">
    <div>
        <label class="title">First Name</label>
        <input type="text" id="name" name="name" >
    </div>
    <div>
        <input type="submit" id="submitButton"  name="submitButton" value="Submit">
    </div>
</form>

<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* get the action attribute from the <form action=""> element */
  var $form = $( this ), url = $form.attr( 'action' );

  /* Send the data using post with element id name and name2*/
  var posting = $.post( url, { name: $('#name').val()} );

  /* Alerts the results */
  posting.done(function( data ) {
    alert('success');
  });
});
</script>

How to print variable addresses in C?

To print the address of a variable, you need to use the %p format. %d is for signed integers. For example:

#include<stdio.h>

void main(void)
{
  int a;

  printf("Address is %p:",&a);
}

how to remove multiple columns in r dataframe?

Basic subsetting:

album2 <- album2[, -5] #delete column 5
album2 <- album2[, -c(5:7)] # delete columns 5 through 7

ASP.NET MVC3 - textarea with @Html.EditorFor

@Html.TextAreaFor(model => model.Text)