Programs & Examples On #Msmqbinding

CSS to make table 100% of max-width

I had to use:

table, tbody {
    width: 100%;
}

The table alone wasn't enough, the tbody was also needed for it to work for me.

Decoding base64 in batch

Here's a batch file, called base64encode.bat, that encodes base64.

@echo off
if not "%1" == "" goto :arg1exists
echo usage: base64encode input-file [output-file]
goto :eof
:arg1exists
set base64out=%2
if "%base64out%" == "" set base64out=con 
(
  set base64tmp=base64.tmp
  certutil -encode "%1" %base64tmp% > nul
  findstr /v /c:- %base64tmp%
  erase %base64tmp%
) > %base64out%

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

Assign empty value:

document.getElementById('numquest').value=null;

or, if want to clear all form fields. Just call form reset method as:

document.forms['form_name'].reset()

urllib and "SSL: CERTIFICATE_VERIFY_FAILED" Error

If you have private certs to deal with, like your orgs own CA root and intermediates part of the chain, then better to add the certs to the ca file viz. cacert.pem than bypassing the entire security apparatus (verify=False). Below code gets you going in both 2.7+ and 3+

Consider adding the whole cert chain and off course you need to do this only once.

import certifi

cafile=certifi.where() # cacert file
with open ('rootca.pem','rb') as infile:
    customca=infile.read()
    with open(cafile,'ab') as outfile:
        outfile.write(customca)
with open ('interca.pem','rb') as infile:
    customca=infile.read()
    with open(cafile,'ab') as outfile:
        outfile.write(customca)
with open ('issueca.pem','rb') as infile:
    customca=infile.read()
    with open(cafile,'ab') as outfile:
        outfile.write(customca)

Then this should get you going

import requests
response = requests.request("GET", 'https://yoursecuresite.com',  data = {})
print(response.text.encode('utf8'))

Hope this helps

How to clear cache of Eclipse Indigo

Clear improperly cached compile errors. All Projects Locations in Eclipse
workspace\.metadata\.plugins\org.eclipse.core.resources\.projects\<project>\

What is the difference between Task.Run() and Task.Factory.StartNew()

According to this post by Stephen Cleary, Task.Factory.StartNew() is dangerous:

I see a lot of code on blogs and in SO questions that use Task.Factory.StartNew to spin up work on a background thread. Stephen Toub has an excellent blog article that explains why Task.Run is better than Task.Factory.StartNew, but I think a lot of people just haven’t read it (or don’t understand it). So, I’ve taken the same arguments, added some more forceful language, and we’ll see how this goes. :) StartNew does offer many more options than Task.Run, but it is quite dangerous, as we’ll see. You should prefer Task.Run over Task.Factory.StartNew in async code.

Here are the actual reasons:

  1. Does not understand async delegates. This is actually the same as point 1 in the reasons why you would want to use StartNew. The problem is that when you pass an async delegate to StartNew, it’s natural to assume that the returned task represents that delegate. However, since StartNew does not understand async delegates, what that task actually represents is just the beginning of that delegate. This is one of the first pitfalls that coders encounter when using StartNew in async code.
  2. Confusing default scheduler. OK, trick question time: in the code below, what thread does the method “A” run on?
Task.Factory.StartNew(A);

private static void A() { }

Well, you know it’s a trick question, eh? If you answered “a thread pool thread”, I’m sorry, but that’s not correct. “A” will run on whatever TaskScheduler is currently executing!

So that means it could potentially run on the UI thread if an operation completes and it marshals back to the UI thread due to a continuation as Stephen Cleary explains more fully in his post.

In my case, I was trying to run tasks in the background when loading a datagrid for a view while also displaying a busy animation. The busy animation didn't display when using Task.Factory.StartNew() but the animation displayed properly when I switched to Task.Run().

For details, please see https://blog.stephencleary.com/2013/08/startnew-is-dangerous.html

What is an alternative to execfile in Python 3?

You could write your own function:

def xfile(afile, globalz=None, localz=None):
    with open(afile, "r") as fh:
        exec(fh.read(), globalz, localz)

If you really needed to...

How to create and handle composite primary key in JPA

The MyKey class must implement Serializable if you are using @IdClass

Multiple WHERE clause in Linq

Well, you can just put multiple "where" clauses in directly, but I don't think you want to. Multiple "where" clauses ends up with a more restrictive filter - I think you want a less restrictive one. I think you really want:

DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
            where r.Field<string>("UserName") != "XXXX" &&
                  r.Field<string>("UserName") != "YYYY"
            select r;

DataTable newDT = query.CopyToDataTable();

Note the && instead of ||. You want to select the row if the username isn't XXXX and the username isn't YYYY.

EDIT: If you have a whole collection, it's even easier. Suppose the collection is called ignoredUserNames:

DataTable tempData = (DataTable)grdUsageRecords.DataSource;
var query = from r in tempData.AsEnumerable()
            where !ignoredUserNames.Contains(r.Field<string>("UserName"))
            select r;

DataTable newDT = query.CopyToDataTable();

Ideally you'd want to make this a HashSet<string> to avoid the Contains call taking a long time, but if the collection is small enough it won't make much odds.

Multipart File Upload Using Spring Rest Template + Spring Web MVC

For most use cases, it's not correct to register MultipartFilter in web.xml because Spring MVC already does the work of processing your multipart request. It's even written in the filter's javadoc.

On the server side, define a multipartResolver bean in your app context:

@Bean
public CommonsMultipartResolver multipartResolver(){
    CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
    commonsMultipartResolver.setDefaultEncoding("utf-8");
    commonsMultipartResolver.setMaxUploadSize(50000000);
    return commonsMultipartResolver;
}

On the client side, here's how to prepare the request for use with Spring RestTemplate API:

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);

    LinkedMultiValueMap<String, String> pdfHeaderMap = new LinkedMultiValueMap<>();
    pdfHeaderMap.add("Content-disposition", "form-data; name=filex; filename=" + file.getOriginalFilename());
    pdfHeaderMap.add("Content-type", "application/pdf");
    HttpEntity<byte[]> doc = new HttpEntity<byte[]>(file.getBytes(), pdfHeaderMap);

    LinkedMultiValueMap<String, Object> multipartReqMap = new LinkedMultiValueMap<>();
    multipartReqMap.add("filex", doc);

    HttpEntity<LinkedMultiValueMap<String, Object>> reqEntity = new HttpEntity<>(multipartReqMap, headers);
    ResponseEntity<MyResponse> resE = restTemplate.exchange(uri, HttpMethod.POST, reqEntity, MyResponse.class);

The important thing is really to provide a Content-disposition header using the exact case, and adding name and filename specifiers, otherwise your part will be discarded by the multipart resolver.

Then, your controller method can handle the uploaded file with the following argument:

@RequestParam("filex") MultipartFile file

Hope this helps.

XAMPP Apache won't start

First of all, after installation restart windows. As strange as it may be, this does matter. Also, check all apps occupying port 80 (e.g. Skype).

Finally, what resolved my situation - port 443. VMWare have been using this port. AFter killing the VMWare process, Apache worked just fine.

How do I get the calling method name and type using reflection?

public class SomeClass
{
    public void SomeMethod()
    {
        StackFrame frame = new StackFrame(1);
        var method = frame.GetMethod();
        var type = method.DeclaringType;
        var name = method.Name;
    }
}

Now let's say you have another class like this:

public class Caller
{
   public void Call()
   {
      SomeClass s = new SomeClass();
      s.SomeMethod();
   }
}

name will be "Call" and type will be "Caller"

UPDATE Two years later since I'm still getting upvotes on this

In .Net 4.5 there is now a much easier way to do this. You can take advantage of the CallerMemberNameAttribute

Going with the previous example:

public class SomeClass
{
    public void SomeMethod([CallerMemberName]string memberName = "")
    {
        Console.WriteLine(memberName); //output will be name of calling method
    }
}

arranging div one below the other

Try a clear: left on #inner2. Because they are both being set to float it should cause a line return.

_x000D_
_x000D_
#inner1 {_x000D_
   float:left; _x000D_
}_x000D_
_x000D_
#inner2{_x000D_
   float:left; _x000D_
   clear: left;_x000D_
}
_x000D_
<div id="wrapper">_x000D_
    <div id="inner1">This is inner div 1</div>_x000D_
    <div id="inner2">This is inner div 2</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What are the differences between "git commit" and "git push"?

git commit is to commit the files that is staged in the local repo. git push is to fast-forward merge the master branch of local side with the remote master branch. But the merge won't always success. If rejection appears, you have to pull so that you can make a successful git push.

How to get a pixel's x,y coordinate color from an image?

Canvas would be a great way to do this, as @pst said above. Check out this answer for a good example:

getPixel from HTML Canvas?

Some code that would serve you specifically as well:

var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;

for (var i = 0, n = pix.length; i < n; i += 4) {
  console.log pix[i+3]
}

This will go row by row, so you'd need to convert that into an x,y and either convert the for loop to a direct check or run a conditional inside.

Reading your question again, it looks like you want to be able to get the point that the person clicks on. This can be done pretty easily with jquery's click event. Just run the above code inside a click handler as such:

$('el').click(function(e){
   console.log(e.clientX, e.clientY)
}

Those should grab your x and y values.

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

I didn't want to unstack or over-complicate this issue, since I just wanted to drop some highly correlated features as part of a feature selection phase.

So I ended up with the following simplified solution:

# map features to their absolute correlation values
corr = features.corr().abs()

# set equality (self correlation) as zero
corr[corr == 1] = 0

# of each feature, find the max correlation
# and sort the resulting array in ascending order
corr_cols = corr.max().sort_values(ascending=False)

# display the highly correlated features
display(corr_cols[corr_cols > 0.8])

In this case, if you want to drop correlated features, you may map through the filtered corr_cols array and remove the odd-indexed (or even-indexed) ones.

Dynamically create and submit form

Its My version without jQuery, simple function can be used on fly

Function:

function post_to_url(path, params, method) {
    method = method || "post";

    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

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

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

Usage:

post_to_url('fullurlpath', {
    field1:'value1',
    field2:'value2'
}, 'post');

Python - 'ascii' codec can't decode byte

In case you're dealing with Unicode, sometimes instead of encode('utf-8'), you can also try to ignore the special characters, e.g.

"??".encode('ascii','ignore')

or as something.decode('unicode_escape').encode('ascii','ignore') as suggested here.

Not particularly useful in this example, but can work better in other scenarios when it's not possible to convert some special characters.

Alternatively you can consider replacing particular character using replace().

How do I change the font size and color in an Excel Drop Down List?

Try making the whole sheet font size smaller. Then zoom and save. Make a practice sheet first because it really screws everything up.

How to get class object's name as a string in Javascript?

Shog9 is right that this doesn't make all that much sense to ask, since an object could be referred to by multiple variables. If you don't really care about that, and all you want is to find the name of one of the global variables that refers to that object, you could do the following hack:

function myClass() { 
  this.myName = function () { 
    // search through the global object for a name that resolves to this object
    for (var name in this.global) 
      if (this.global[name] == this) 
        return name 
  } 
}
// store the global object, which can be referred to as this at the top level, in a
// property on our prototype, so we can refer to it in our object's methods
myClass.prototype.global = this
// create a global variable referring to an object
var myVar = new myClass()
myVar.myName() // returns "myVar"

Note that this is an ugly hack, and should not be used in production code. If there is more than one variable referring to an object, you can't tell which one you'll get. It will only search the global variables, so it won't work if a variable is local to a function. In general, if you need to name something, you should pass the name in to the constructor when you create it.

edit: To respond to your clarification, if you need to be able to refer to something from an event handler, you shouldn't be referring to it by name, but instead add a function that refers to the object directly. Here's a quick example that I whipped up that shows something similar, I think, to what you're trying to do:

function myConstructor () {
  this.count = 0
  this.clickme = function () {
    this.count += 1
    alert(this.count)
  }

  var newDiv = document.createElement("div")
  var contents = document.createTextNode("Click me!")

  // This is the crucial part. We don't construct an onclick handler by creating a
  // string, but instead we pass in a function that does what we want. In order to
  // refer to the object, we can't use this directly (since that will refer to the 
  // div when running event handler), but we create an anonymous function with an 
  // argument and pass this in as that argument.
  newDiv.onclick = (function (obj) { 
    return function () {
      obj.clickme()
    }
  })(this)

  newDiv.appendChild(contents)
  document.getElementById("frobnozzle").appendChild(newDiv)

}
window.onload = function () {
  var myVar = new myConstructor()
}

With CSS, use "..." for overflowed block of multi-lines

Great question... I wish there was an answer, but this is the closest you can get with CSS these days. No ellipsis, but still pretty usable.

overflow: hidden;
line-height: 1.2em;
height: 3.6em;      // 3 lines * line-height

Convert DataTable to List<T>

There are Linq extension methods for DataTable.

Add reference to: System.Data.DataSetExtensions.dll

Then include the namespace: using System.Data.DataSetExtensions

Finally you can use Linq extensions on DataSet and DataTables:

var matches = myDataSet.Tables.First().Where(dr=>dr.Field<int>("id") == 1);

On .Net 2.0 you can still add generic method:

public static List<T> ConvertRowsToList<T>( DataTable input, Convert<DataRow, T> conversion) {
    List<T> retval = new List<T>()
    foreach(DataRow dr in input.Rows)
        retval.Add( conversion(dr) );

    return retval;
}

The ResourceConfig instance does not contain any root resource classes

I had the same issue with trying to run the webapp from an eclipse project. As soon I copied the .class files to /WEB-INF/classes it worked perfectly.

PHP String to Float

If you need to handle values that cannot be converted separately, you can use this method:

try {
    $valueToUse = trim($stringThatMightBeNumeric) + 0;
} catch (\Throwable $th) {
    // bail here if you need to
}

iOS 6 apps - how to deal with iPhone 5 screen size?

All apps will continue to work in the vertically stretched screen from what I could tell in today's presentation. They will be letterboxed or basically the extra 88 points in height would simply be black.

If you only plan to support iOS 6+, then definitely consider using Auto Layout. It removes all fixed layout handling and instead uses constraints to lay things out. Nothing will be hard-coded, and your life will become a lot simpler.

However, if you have to support older iOS's, then it really depends on your application. A majority of applications that use a standard navigation bar, and/or tab bar, could simply expand the content in the middle to use up that extra points. Set the autoresizing mask of the center content to expand in both directions.

view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;

It works great out of the box for table views, however, if your app used pixel-perfect layout for displaying content, then your best bet would be to re-imagine the content so that it can accommodate varying heights.

If that's not a possibility, then the only remaining option is to have two UIs (pre iPhone 5, and iPhone 5).

If that sounds ugly, then you could go with the default letterboxed model where the extra points/pixels just show up black.

Edit

To enable your apps to work with iPhone 5, you need to add a retina version of the launcher image. It should be named [email protected]. And it has to be retina quality - there's no backward compatibility here :)

You could also select this image from within Xcode. Go to the target, and under the Summary section, look for Launch Images. The image has to be 640x1136 pixels in size. Here's a screenshot of where to find it, if that helps.

Xcode screenshot

How to remove all options from a dropdown using jQuery / JavaScript

Anyone using JavaScript (as opposed to JQuery), might like to try this solution, where 'models' is the ID of the select field containing the list :-

var DDlist = document.getElementById("models");
while(DDlist.length>0){DDlist.remove(0);}

grep's at sign caught as whitespace

After some time with Google I asked on the ask ubuntu chat room.

A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:

grep -P "(^|\s)abc(\s|$)" gives the result I was looking for. -P is an experimental implementation of perl regexps.

grepping for abc and then using filters like grep -v '@abc' (this is far from perfect...) should also work, but my patch does something similar.

How do I put variables inside javascript strings?

util.format does this.

It will be part of v0.5.3 and can be used like this:

var uri = util.format('http%s://%s%s', 
      (useSSL?'s':''), apiBase, path||'/');

How to convert a UTF-8 string into Unicode?

If you have a UTF-8 string, where every byte is correct ('Ö' -> [195, 0] , [150, 0]), you can use the following:

public static string Utf8ToUtf16(string utf8String)
{
    /***************************************************************
     * Every .NET string will store text with the UTF-16 encoding, *
     * known as Encoding.Unicode. Other encodings may exist as     *
     * Byte-Array or incorrectly stored with the UTF-16 encoding.  *
     *                                                             *
     * UTF-8 = 1 bytes per char                                    *
     *    ["100" for the ansi 'd']                                 *
     *    ["206" and "186" for the russian '?']                    *
     *                                                             *
     * UTF-16 = 2 bytes per char                                   *
     *    ["100, 0" for the ansi 'd']                              *
     *    ["186, 3" for the russian '?']                           *
     *                                                             *
     * UTF-8 inside UTF-16                                         *
     *    ["100, 0" for the ansi 'd']                              *
     *    ["206, 0" and "186, 0" for the russian '?']              *
     *                                                             *
     * First we need to get the UTF-8 Byte-Array and remove all    *
     * 0 byte (binary 0) while doing so.                           *
     *                                                             *
     * Binary 0 means end of string on UTF-8 encoding while on     *
     * UTF-16 one binary 0 does not end the string. Only if there  *
     * are 2 binary 0, than the UTF-16 encoding will end the       *
     * string. Because of .NET we don't have to handle this.       *
     *                                                             *
     * After removing binary 0 and receiving the Byte-Array, we    *
     * can use the UTF-8 encoding to string method now to get a    *
     * UTF-16 string.                                              *
     *                                                             *
     ***************************************************************/

    // Get UTF-8 bytes and remove binary 0 bytes (filler)
    List<byte> utf8Bytes = new List<byte>(utf8String.Length);
    foreach (byte utf8Byte in utf8String)
    {
        // Remove binary 0 bytes (filler)
        if (utf8Byte > 0) {
            utf8Bytes.Add(utf8Byte);
        }
    }

    // Convert UTF-8 bytes to UTF-16 string
    return Encoding.UTF8.GetString(utf8Bytes.ToArray());
}

In my case the DLL result is a UTF-8 string too, but unfortunately the UTF-8 string is interpreted with UTF-16 encoding ('Ö' -> [195, 0], [19, 32]). So the ANSI '–' which is 150 was converted to the UTF-16 '–' which is 8211. If you have this case too, you can use the following instead:

public static string Utf8ToUtf16(string utf8String)
{
    // Get UTF-8 bytes by reading each byte with ANSI encoding
    byte[] utf8Bytes = Encoding.Default.GetBytes(utf8String);

    // Convert UTF-8 bytes to UTF-16 bytes
    byte[] utf16Bytes = Encoding.Convert(Encoding.UTF8, Encoding.Unicode, utf8Bytes);

    // Return UTF-16 bytes as UTF-16 string
    return Encoding.Unicode.GetString(utf16Bytes);
}

Or the Native-Method:

[DllImport("kernel32.dll")]
private static extern Int32 MultiByteToWideChar(UInt32 CodePage, UInt32 dwFlags, [MarshalAs(UnmanagedType.LPStr)] String lpMultiByteStr, Int32 cbMultiByte, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder lpWideCharStr, Int32 cchWideChar);

public static string Utf8ToUtf16(string utf8String)
{
    Int32 iNewDataLen = MultiByteToWideChar(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf8String, -1, null, 0);
    if (iNewDataLen > 1)
    {
        StringBuilder utf16String = new StringBuilder(iNewDataLen);
        MultiByteToWideChar(Convert.ToUInt32(Encoding.UTF8.CodePage), 0, utf8String, -1, utf16String, utf16String.Capacity);

        return utf16String.ToString();
    }
    else
    {
        return String.Empty;
    }
}

If you need it the other way around, see Utf16ToUtf8. Hope I could be of help.

Converting unix timestamp string to readable date

>>> import time
>>> time.ctime(int("1284101485"))
'Fri Sep 10 16:51:25 2010'
>>> time.strftime("%D %H:%M", time.localtime(int("1284101485")))
'09/10/10 16:51'

Mosaic Grid gallery with dynamic sized images

I think you can try "Google Grid Gallery", it based on aforementioned Masonry with some additions, like styles and viewer.

Best practice multi language website

Database work:

Create Language Table ‘languages’:

Fields:

language_id(primary and auto increamented)

language_name

created_at

created_by

updated_at

updated_by

Create a table in database ‘content’:

Fields:

content_id(primary and auto incremented)

main_content

header_content

footer_content

leftsidebar_content

rightsidebar_content

language_id(foreign key: referenced to languages table)

created_at

created_by

updated_at

updated_by

Front End Work:

When user selects any language from dropdown or any area then save selected language id in session like,

$_SESSION['language']=1;

Now fetch data from database table ‘content’ based on language id stored in session.

Detail may found here http://skillrow.com/multilingual-website-in-php-2/

Zookeeper connection error

leave only one entry for your host IP in /etc/hosts file, it resolved.

using BETWEEN in WHERE condition

$this->db->where('accommodation BETWEEN '' . $sdate . '' AND '' . $edate . ''');

this is my solution

How to trigger a click on a link using jQuery

Well you have to setup the click event first then you can trigger it and see what happens:

//good habits first let's cache our selector
var $myLink = $('#titleee').find('a');
$myLink.click(function (evt) {
  evt.preventDefault();
  alert($(this).attr('href'));
});

// now the manual trigger
$myLink.trigger('click');

Disable Transaction Log

There is a third recovery mode not mentioned above. The recovery mode ultimately determines how large the LDF files become and how ofter they are written to. In cases where you are going to be doing any type of bulk inserts, you should set the DB to be in "BULK/LOGGED". This makes bulk inserts move speedily along and can be changed on the fly.

To do so,

USE master ;
ALTER DATABASE model SET RECOVERY BULK_LOGGED ;

To change it back:

USE master ;
ALTER DATABASE model SET RECOVERY FULL ;

In the spirit of adding to the conversation about why someone would not want an LDF, I add this: We do multi-dimensional modelling. Essentially we use the DB as a large store of variables that are processed in bulk using external programs. We do not EVER require rollbacks. If we could get a performance boost by turning of ALL logging, we'd take it in a heart beat.

SELECT using 'CASE' in SQL

Try this.

SELECT 
  CASE 
     WHEN FRUIT = 'A' THEN 'APPLE'
     WHEN FRUIT = 'B' THEN 'BANANA'
     ELSE 'UNKNOWN FRUIT'
  END AS FRUIT
FROM FRUIT_TABLE;

Asynchronous Function Call in PHP

I think if the HTML and other UI stuff needs the data returned then there is not going to be a way to async it.

I believe the only way to do this in PHP would be to log a request in a database and have a cron check every minute, or use something like Gearman queue processing, or maybe exec() a command line process

In the meantime you php page would have to generate some html or js that makes it reload every few seconds to check on progress, not ideal.

To sidestep the issue, how many different requests are you expecting? Could you download them all automatically every hour or so and save to a database?

What is the cleanest way to ssh and run multiple commands in Bash?

Not sure if the cleanest for long commands but certainly the easiest:

ssh user@host "cmd1; cmd2; cmd3"

Procedure or function !!! has too many arguments specified

In addition to all the answers provided so far, another reason for causing this exception can happen when you are saving data from list to database using ADO.Net.

Many developers will mistakenly use for loop or foreach and leave the SqlCommand to execute outside the loop, to avoid that make sure that you have like this code sample for example:

public static void Save(List<myClass> listMyClass)
    {
        using (var Scope = new System.Transactions.TransactionScope())
        {
            if (listMyClass.Count > 0)
            {
                for (int i = 0; i < listMyClass.Count; i++)
                {
                    SqlCommand cmd = new SqlCommand("dbo.SP_SaveChanges", myConnection);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Clear();

                    cmd.Parameters.AddWithValue("@ID", listMyClass[i].ID);
                    cmd.Parameters.AddWithValue("@FirstName", listMyClass[i].FirstName);
                    cmd.Parameters.AddWithValue("@LastName", listMyClass[i].LastName);

                    try
                    {
                        myConnection.Open();
                        cmd.ExecuteNonQuery();
                    }
                    catch (SqlException sqe)
                    {
                        throw new Exception(sqe.Message);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        myConnection.Close();
                    }
                }
            }
            else
            {
                throw new Exception("List is empty");
            }

            Scope.Complete();
        }
    }

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

Arrow functions which is denoted by symbol (=>) helps you to create anonymous functions and methods. That leads to more shorter syntax. For example, below is a simple “Add” function which returns addition of two numbers.

function Add(num1 , num2 ){
return num1 + num2;
}

The above function becomes shorter by using “Arrow” syntax as shown below.

enter image description here

Above code has two parts as shown in the above diagram: -

Input: — This section specifies the input parameters to the anonymous function.

Logic: — This section comes after the symbol “=>”. This section has the logic of the actual function.

Many developers think that arrow function makes your syntax shorter, simpler and thus makes your code readable.

If you believe the above sentence, then let me assure you it’s a myth. If you think for a moment a properly written function with name is much readable than cryptic functions created in one line using an arrow symbol.

The main use of arrow function is to ensure that code runs in the callers context.

See the below code in which have a global variable "context" defined , this global variable is accessed inside a function "SomeOtherMethod" which is called from other method "SomeMethod".

This "SomeMethod" has local "context" variable. Now because "SomeOtherMethod" is called from ""SomeMethod" we expect it to display "local context" , but it displays "global context".

var context = “global context”;

function SomeOtherMethod(){
alert(this.context);
}

function SomeMethod(){
this.context = “local context”;
SomeOtherMethod();
}

var instance = new SomeMethod();

But if replace the call by using Arrow function it will display "local context".

var context = "global context";

    function SomeMethod(){
        this.context = "local context";
        SomeOtherMethod = () => {
            alert(this.context);
        }
        SomeOtherMethod();
    }
    var instance = new SomeMethod();

I would encourage you to read this link ( Arrow function in JavaScript ) which explain all the scenarios of javascript context and in which scenarios the callers context is not respected.

You can also see the demonstration of Arrow function with javascript in this youtube video which demonstrates practically the term Context.

Is it possible to specify a different ssh port when using rsync?

Another option, in the host you run rsync from, set the port in the ssh config file, ie:

cat ~/.ssh/config
Host host
    Port 2222

Then rsync over ssh will talk to port 2222:

rsync -rvz --progress --remove-sent-files ./dir user@host:/path

How to create a directory and give permission in single command

You could write a simple shell script, for example:

#!/bin/bash
mkdir "$1"
chmod 777 "$1"

Once saved, and the executable flag enabled, you could run it instead of mkdir and chmod:

./scriptname path/foldername

However, alex's answer is much better because it spawns one process instead of three. I didn't know about the -m option.

Python, remove all non-alphabet chars from string

You can use the re.sub() function to remove these characters:

>>> import re
>>> re.sub("[^a-zA-Z]+", "", "ABC12abc345def")
'ABCabcdef'

re.sub(MATCH PATTERN, REPLACE STRING, STRING TO SEARCH)

  • "[^a-zA-Z]+" - look for any group of characters that are NOT a-zA-z.
  • "" - Replace the matched characters with ""

How to easily duplicate a Windows Form in Visual Studio?

Its Really Easy. "In Design mode FORM" (form1.cs[Design]) copy the whole Form "ctrl A" then ctrl C. All objects at once. Then add a new windows form to the project. Change the size of the form to the size that you want then paste ctrl V all of the new objects will be copied to the new form. When they are all still picked double click on any of the objects. NOT THE FORM!!!..... This will create the code on the Form side matching the objects you just pasted. if it doesn't you can double click on each object and it will create the code one at a time. I use a text box area to double click in and it works almost every time. I use this method everyday WORKS GREAT.

TypeError: tuple indices must be integers, not str

SQlite3 has a method named row_factory. This method would allow you to access the values by column name.

https://www.kite.com/python/examples/3884/sqlite3-use-a-row-factory-to-access-values-by-column-name

What does the "map" method do in Ruby?

It "maps" a function to each item in an Enumerable - in this case, a range. So it would call the block passed once for every integer from 0 to param_count (exclusive - you're right about the dots) and return an array containing each return value.

Here's the documentation for Enumerable#map. It also has an alias, collect.

C++ printing spaces or tabs given a user input integer

I just happened to look for something similar and came up with this:

std::cout << std::setfill(' ') << std::setw(n) << ' ';

Is there a way to get rid of accents and convert a whole string to regular letters?

EDIT: If you're not stuck with Java <6 and speed is not critical and/or translation table is too limiting, use answer by David. The point is to use Normalizer (introduced in Java 6) instead of translation table inside the loop.

While this is not "perfect" solution, it works well when you know the range (in our case Latin1,2), worked before Java 6 (not a real issue though) and is much faster than the most suggested version (may or may not be an issue):

    /**
 * Mirror of the unicode table from 00c0 to 017f without diacritics.
 */
private static final String tab00c0 = "AAAAAAACEEEEIIII" +
    "DNOOOOO\u00d7\u00d8UUUUYI\u00df" +
    "aaaaaaaceeeeiiii" +
    "\u00f0nooooo\u00f7\u00f8uuuuy\u00fey" +
    "AaAaAaCcCcCcCcDd" +
    "DdEeEeEeEeEeGgGg" +
    "GgGgHhHhIiIiIiIi" +
    "IiJjJjKkkLlLlLlL" +
    "lLlNnNnNnnNnOoOo" +
    "OoOoRrRrRrSsSsSs" +
    "SsTtTtTtUuUuUuUu" +
    "UuUuWwYyYZzZzZzF";

/**
 * Returns string without diacritics - 7 bit approximation.
 *
 * @param source string to convert
 * @return corresponding string without diacritics
 */
public static String removeDiacritic(String source) {
    char[] vysl = new char[source.length()];
    char one;
    for (int i = 0; i < source.length(); i++) {
        one = source.charAt(i);
        if (one >= '\u00c0' && one <= '\u017f') {
            one = tab00c0.charAt((int) one - '\u00c0');
        }
        vysl[i] = one;
    }
    return new String(vysl);
}

Tests on my HW with 32bit JDK show that this performs conversion from àèélštc89FDC to aeelstc89FDC 1 million times in ~100ms while Normalizer way makes it in 3.7s (37x slower). In case your needs are around performance and you know the input range, this may be for you.

Enjoy :-)

how to get session id of socket.io client in Client

On socket.io >=1.0, after the connect event has triggered:

var socket = io('localhost');
var id = socket.io.engine.id

How do I use jQuery to redirect?

You forgot the HTTP part:

window.location.href = "http://example.com/Registration/Success/";

Breaking a list into multiple columns in Latex

Another option to avoid nesting two different environments (like multicols and enumerate).

The environment called tasks from the package with the same name seems to me very easy to customize thanks to a variety of options (pdf guide here).

This code:

\documentclass{article}
\usepackage{tasks}

%\settasks{style=itemize}

\begin{document}
Text text text text text text text text text text text text 
text text text text text text text text text text text text 
text text text text text text text text text text text text.

\begin{tasks}(2)
\task[*] a
\task[*] b
\task[*] c
\task[*] d
\task[*] e
\task[*] f
\end{tasks}    

Text text text text text text text text text text text text 
text text text text text text text text text text text text 
text text text text text text text text text text text text.
\end{document}

produces this output

tasks

The package tasks was updated in August 2020 and it was originally created specifically for horizontally columned lists (see the screenshot just above here), the motivations behind this are resumed in the guide. If such arrangement of the items/tasks is acceptable, then this may be a good choice since it keeps - IMHO - the code tidy and flexible.

Reference member variables as class members

C++ provides a good mechanism to manage the life time of an object though class/struct constructs. This is one of the best features of C++ over other languages.

When you have member variables exposed through ref or pointer it violates the encapsulation in principle. This idiom enables the consumer of the class to change the state of an object of A without it(A) having any knowledge or control of it. It also enables the consumer to hold on to a ref/pointer to A's internal state, beyond the life time of the object of A. This is bad design. Instead the class could be refactored to hold a ref/pointer to the shared object (not own it) and these could be set using the constructor (Mandate the life time rules). The shared object's class may be designed to support multithreading/concurrency as the case may apply.

Passing an array to a query using a WHERE clause

More an example:

$galleryIds = [1, '2', 'Vitruvian Man'];
$ids = array_filter($galleryIds, function($n){return (is_numeric($n));});
$ids = implode(', ', $ids);

$sql = "SELECT * FROM galleries WHERE id IN ({$ids})";
// output: 'SELECT * FROM galleries WHERE id IN (1, 2)'

$statement = $pdo->prepare($sql);
$statement->execute();

How can I verify if an AD account is locked?

The LockedOut property is what you are looking for among all the properties you returned. You are only seeing incomplete output in TechNet. The information is still there. You can isolate that one property using Select-Object

Get-ADUser matt -Properties * | Select-Object LockedOut

LockedOut
---------
False

The link you referenced doesn't contain this information which is obviously misleading. Test the command with your own account and you will see much more information.

Note: Try to avoid -Properties *. While it is great for simple testing it can make queries, especially ones with multiple accounts, unnecessarily slow. So, in this case, since you only need lockedout:

Get-ADUser matt -Properties LockedOut | Select-Object LockedOut

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

I just went through this. If you want to manually move your Eclipse installation you need to find and edit relative references in the following files.

Relative to Eclipse install dir:

  • configuration/org.eclipse.equinox.source/source.info
  • configuration/org.eclipse.equinox.simpleconfigurator/bundles.info
  • configuration/config.ini
  • eclipse.ini

For me in all these files there was a ../ reference to a .p2 folder in my home directory. Found them all using a simple grep:

grep '../../../../' * -R

Then just hit it with sed or manually go change it. In my case I moved it up one folder so easy fix:

grep -rl '../../../../' * -R | xargs sed -i 's/..\/..\/..\/..\//..\/..\/..\//g'

Now Eclipse runs fine again.

Get the current user, within an ApiController action, without passing the userID as a parameter

Karan Bhandari's answer is good, but the AccountController added in a project is very likely a Mvc.Controller. To convert his answer for use in an ApiController change HttpContext.Current.GetOwinContext() to Request.GetOwinContext() and make sure you have added the following 2 using statements:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

Print directly from browser without print popup window

IE9 no longer supports triggering the Print() VBScript by calling window.print() like IE7 and IE8 do, and thus window.print() will now always trigger the print dialog in IE9.

The fix is pretty simple. You just need to call Print() itself, instead of window.print() in the onclick event.

I've described the fix in more detail in an answer to another question, with a working code example sporting slightly updated HTML syntax (as much as possible while still tested as working code).

You can find that sample code here:

Bypass Printdialog in IE9

Printing PDFs from Windows Command Line

I had two problems with using Acrobat Reader for this task.

  1. The command line API is not officially supported, so it could change or be removed without warning.
  2. Send a print command to Reader loads up the GUI, with seemingly no way to prevent it. I needed the process to be transparent to the user.

I stumbled across this blog, that suggests using Foxit Reader. Foxit Reader is free, the API is almost identical to Acrobat Reader, but crucially is documented and does not load the GUI for print jobs.

A word of warning, don't just click through the install process without paying attention, it tries to install unrelated software as well. Why are software vendors still doing this???

Getting attribute of element in ng-click function in angularjs

Even more simple, pass the $event object to ng-click to access the event properties. As an example:

<a ng-click="clickEvent($event)" class="exampleClass" id="exampleID" data="exampleData" href="">Click Me</a>

Within your clickEvent() = function(obj) {} function you can access the data value like this:

var dataValue = obj.target.attributes.data.value;

Which would return exampleData.

Here's a full jsFiddle.

Submit HTML form on self page

You can do it using the same page on the action attribute: action='<yourpage>'

Checking to see if a DateTime variable has had a value assigned

put this somewhere:

public static class DateTimeUtil //or whatever name
{
    public static bool IsEmpty(this DateTime dateTime)
    {
        return dateTime == default(DateTime);
    }
}

then:

DateTime datetime = ...;

if (datetime.IsEmpty())
{
    //unassigned
}

push() a two-dimensional array

The solution below uses a double loop to add data to the bottom of a 2x2 array in the Case 3. The inner loop pushes selected elements' values into a new row array. The outerloop then pushes the new row array to the bottom of an existing array (see Newbie: Add values to two-dimensional array with for loops, Google Apps Script).

In this example, I created a function that extracts a section from an existing array. The extracted section can be a row (full or partial), a column (full or partial), or a 2x2 section of the existing array. A new blank array (newArr) is filled by pushing the relevant section from the existing array (arr) into the new array.

 function arraySection(arr, r1, c1, rLength, cLength) {      
   rowMax = arr.length;
    if(isNaN(rowMax)){rowMax = 1};
   colMax = arr[0].length;
   if(isNaN(colMax)){colMax = 1};
   var r2 = r1 + rLength - 1;
   var c2 = c1 + cLength - 1;

   if ((r1< 0 || r1 > r2 || r1 > rowMax || (r1 | 0) != r1) || (r2 < 0 || 
     r2 > rowMax || (r2 | 0) != r2)|| (c1< 0 || c1 > c2 || c1 > colMax || 
   (c1 | 0) != c1) ||(c2 < 0 || c2 > colMax || (c2 | 0) != c2)){
        throw new Error(
        'arraySection: invalid input')       
        return;
     };
   var newArr = [];

// Case 1: extracted section is a column array, 
//          all elements are in the same column
 if (c1 == c2){
   for (var i = r1; i <= r2; i++){ 
         // Logger.log("arr[i][c1] for i = " + i);
         // Logger.log(arr[i][c1]);
     newArr.push([arr[i][c1]]); 
     };
    };  

// Case 2: extracted section is a row array, 
//          all elements are in the same row
  if (r1 == r2 && c1 != c2){
    for (var j = c1; j <= c2; j++){ 
      newArr.push(arr[r1][j]); 
      };
   };  

// Case 3: extracted section is a 2x2 section 
    if (r1 != r2 && c1 != c2){     
     for (var i = r1; i <= r2; i++) {
          rowi = [];
       for (var j = c1; j <= c2; j++) {
          rowi.push(arr[i][j]);
        }
       newArr.push(rowi)
      };
    };
   return(newArr);
  };

How can I show a message box with two buttons?

msgbox ("Message goes here",0+16,"Title goes here")

if the user is supposed to make a decision the variable can be added like this.

variable=msgbox ("Message goes here",0+16,"Title goes here")

The numbers in the middle vary what the message box looks like. Here is the list

0 - ok button only

1 - ok and cancel

2 - abort, retry and ignore

3 - yes no and cancel

4 - yes and no

5 - retry and cancel

TO CHANGE THE SYMBOL (RIGHT NUMBER)

16 - critical message icon

32 - warning icon

48 - warning message

64 - info message

DEFAULT BUTTON

0 = vbDefaultButton1 - First button is default

256 = vbDefaultButton2 - Second button is default

512 = vbDefaultButton3 - Third button is default

768 = vbDefaultButton4 - Fourth button is default

SYSTEM MODAL

4096 = System modal, alert will be on top of all applications

Note: There are some extra numbers. You just have to add them to the numbers already there like

msgbox("Hello World", 0+16+0+4096)

from https://www.instructables.com/id/The-Ultimate-VBS-Tutorial/

Remove old Fragment from fragment manager

If you want to replace a fragment with another, you should have added them dynamically, first of all. Fragments that are hard coded in XML, cannot be replaced.

// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit();

Refer this post: Replacing a fragment with another fragment inside activity group

Refer1: Replace a fragment programmatically

Swap two items in List<T>

Check the answer from Marc from C#: Good/best implementation of Swap method.

public static void Swap<T>(IList<T> list, int indexA, int indexB)
{
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
}

which can be linq-i-fied like

public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB)
{
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
    return list;
}

var lst = new List<int>() { 8, 3, 2, 4 };
lst = lst.Swap(1, 2);

Pressing Ctrl + A in Selenium WebDriver

Java

The Robot class will work much more efficiently than sending the keys through Selenium sendkeys. Please try:

Example:

Robot rb = new Robot();
rb.keyPress(KeyEvent.VK_CONTROL);
rb.keyPress(KeyEvent.VK_A);

To use the above Robot class, you need to import java.awt.Robot;'.

javax.naming.NameNotFoundException

I am getting the error (...) javax.naming.NameNotFoundException: greetJndi not bound

This means that nothing is bound to the jndi name greetJndi, very likely because of a deployment problem given the incredibly low quality of this tutorial (check the server logs). I'll come back on this.

Is there any specific directory structure to deploy in JBoss?

The internal structure of the ejb-jar is supposed to be like this (using the poor naming conventions and the default package as in the mentioned link):

.
+-- greetBean.java
+-- greetHome.java
+-- greetRemote.java
+-- META-INF
    +-- ejb-jar.xml
    +-- jboss.xml

But as already mentioned, this tutorial is full of mistakes:

  • there is an extra character (<enterprise-beans>] <-- HERE) in the ejb-jar.xml (!)
  • a space is missing after PUBLIC in the ejb-jar.xml and jboss.xml (!!)
  • the jboss.xml is incorrect, it should contain a session element instead of entity (!!!)

Here is a "fixed" version of the ejb-jar.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
<ejb-jar>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <home>greetHome</home>
      <remote>greetRemote</remote>
      <ejb-class>greetBean</ejb-class>
      <session-type>Stateless</session-type>
      <transaction-type>Container</transaction-type>
    </session>
  </enterprise-beans>
</ejb-jar>

And of the jboss.xml:

<?xml version="1.0"?>
<!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS 3.2//EN" "http://www.jboss.org/j2ee/dtd/jboss_3_2.dtd">
<jboss>
  <enterprise-beans>
    <session>
      <ejb-name>greetBean</ejb-name>
      <jndi-name>greetJndi</jndi-name>
    </session>
  </enterprise-beans>
</jboss>

After doing these changes and repackaging the ejb-jar, I was able to successfully deploy it:

21:48:06,512 INFO  [Ejb3DependenciesDeployer] Encountered deployment AbstractVFSDeploymentContext@5060868{vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/}
21:48:06,534 INFO  [EjbDeployer] installing bean: ejb/#greetBean,uid19981448
21:48:06,534 INFO  [EjbDeployer]   with dependencies:
21:48:06,534 INFO  [EjbDeployer]   and supplies:
21:48:06,534 INFO  [EjbDeployer]    jndi:greetJndi
21:48:06,624 INFO  [EjbModule] Deploying greetBean
21:48:06,661 WARN  [EjbModule] EJB configured to bypass security. Please verify if this is intended. Bean=greetBean Deployment=vfszip:/home/pascal/opt/jboss-5.1.0.GA/server/default/deploy/greet.jar/
21:48:06,805 INFO  [ProxyFactory] Bound EJB Home 'greetBean' to jndi 'greetJndi'

That tutorial needs significant improvement; I'd advise from staying away from roseindia.net.

SQL Query to find missing rows between two related tables

SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS 
   (SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)

or

SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN 
    (SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)

or

SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B 
    ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL

Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.

Regular expression - starting and ending with a character string

This should do it for you ^wp.*php$

Matches

wp-comments-post.php
wp.something.php
wp.php

Doesn't match

something-wp.php
wp.php.txt

Twitter Bootstrap 3: How to center a block

A few answers here seem incomplete. Here are several variations:

<style>
.box {
    height: 200px;
    width: 200px;
    border: 4px solid gray;
}
</style>    

<!-- This works: .container>.row>.center-block.box -->
<div class="container">
        <div class="row">
            <div class="center-block bg-primary box">This div is centered with .center-block</div>
        </div>
    </div>

<!-- This does not work -->    
<div class="container">
        <div class="row">
            <div class="center-block bg-primary box col-xs-4">This div is centered with .center-block</div>
        </div>
    </div>

<!-- This is the hybrid solution from other answers:
     .container>.row>.col-xs-6>.center-block.box
 -->   
<div class="container">
        <div class="row">
            <div class="col-xs-6 bg-info">
                <div class="center-block bg-primary box">This div is centered with .center-block</div>
            </div>
        </div>
    </div>

To make it work with col-* classes, you need to wrap the .center-block inside a .col-* class, but remember to either add another class that sets the width (.box in this case), or to alter the .center-block itself by giving it a width.

Check it out on bootply.

WAITING at sun.misc.Unsafe.park(Native Method)

From the stack trace it's clear that, the ThreadPoolExecutor > Worker thread started and it's waiting for the task to be available on the BlockingQueue(DelayedWorkQueue) to pick the task and execute.So this thread will be in WAIT status only as long as get a SIGNAL from the publisher thread.

What is default session timeout in ASP.NET?

The Default Expiration Period for Session is 20 Minutes.

You can update sessionstate and configure the minutes under timeout

<sessionState 
timeout="30">
</sessionState>

jQuery event for images loaded

window.load = function(){}

Its fully supported by all browsers, and it will fire an event when all images are fully loaded.

https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload

Origin <origin> is not allowed by Access-Control-Allow-Origin

Hi This is the way to solve CORS problem in node Just add these lines on server "api" side in Node.js(or what ever your server File), befor that make sure to install "cors"

    const express = require('express');
    const app = express();
    app.use(express.json());
    var cors = require('cors');
    app.use(cors());

including parameters in OPENQUERY

I figured out a way that works for me. It does require the use of a scratch table that a linked server has access to though.

I created a table and populated it with the values I need then I reference that table through a linked server.

SELECT * 
FROM OPENQUERY(KHSSQLODSPRD,'SELECT *
  FROM ABC.dbo.CLAIM A WITH (NOLOCK)
  WHERE A.DOS >= (SELECT MAX(DATE) FROM KHSDASQL01.DA_MAIN.[dbo].[ALLFILENAMES]) ')

DB2 SQL error sqlcode=-104 sqlstate=42601

You miss the from clause

SELECT *  from TCCAWZTXD.TCC_COIL_DEMODATA WHERE CURRENT_INSERTTIME  BETWEEN(CURRENT_TIMESTAMP)-5 minutes AND CURRENT_TIMESTAMP

JQuery: Change value of hidden input field

Seems to work

$(".selector").change(function() {

    var $value = $(this).val();

    var $title = $(this).children('option[value='+$value+']').html();

    $('#bacon').val($title);

});

Just check with your firebug. And don't put css on hidden input.

Print array without brackets and commas

the most simple solution for removing the brackets is,

1.convert the arraylist into string with .toString() method.

2.use String.substring(1,strLen-1).(where strLen is the length of string after conversion from arraylist).

3.Hurraaah..the result string is your string with removed brackets.

hope this is useful...:-)

Converting a double to an int in C#

In the provided example your decimal is 8.6. Had it been 8.5 or 9.5, the statement i1 == i2 might have been true. Infact it would have been true for 8.5, and false for 9.5.

Explanation:

Regardless of the decimal part, the second statement, int i2 = (int)score will discard the decimal part and simply return you the integer part. Quite dangerous thing to do, as data loss might occur.

Now, for the first statement, two things can happen. If the decimal part is 5, that is, it is half way through, a decision is to be made. Do we round up or down? In C#, the Convert class implements banker's rounding. See this answer for deeper explanation. Simply put, if the number is even, round down, if the number is odd, round up.

E.g. Consider:

        double score = 8.5;
        int i1 = Convert.ToInt32(score); // 8
        int i2 = (int)score;             // 8

        score += 1;
        i1 = Convert.ToInt32(score);     // 10
        i2 = (int)score;                 // 9

PHP Constants Containing Arrays?

You can store them as static variables of a class:

class Constants {
    public static $array = array('guy', 'development team');
}
# Warning: array can be changed lateron, so this is not a real constant value:
Constants::$array[] = 'newValue';

If you don't like the idea that the array can be changed by others, a getter might help:

class Constants {
    private static $array = array('guy', 'development team');
    public static function getArray() {
        return self::$array;
    }
}
$constantArray = Constants::getArray();

EDIT

Since PHP5.4, it is even possible to access array values without the need for intermediate variables, i.e. the following works:

$x = Constants::getArray()['index'];

jQuery: keyPress Backspace won't fire?

Use keyup instead of keypress. This gets all the key codes when the user presses something

Is there any advantage of using map over unordered_map in case of trivial keys?

Hash tables have higher constants than common map implementations, which become significant for small containers. Max size is 10, 100, or maybe even 1,000 or more? Constants are the same as ever, but O(log n) is close to O(k). (Remember logarithmic complexity is still really good.)

What makes a good hash function depends on your data's characteristics; so if I don't plan on looking at a custom hash function (but can certainly change my mind later, and easily since I typedef damn near everything) and even though defaults are chosen to perform decently for many data sources, I find the ordered nature of map to be enough of a help initially that I still default to map rather than a hash table in that case.

Plus that way you don't have to even think about writing a hash function for other (usually UDT) types, and just write op< (which you want anyway).

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

One of the values you pass on to Ancestors becomes None at some point, it says, so check if otu, tree, tree[otu] or tree[otu][0] are None in the beginning of the function instead of only checking tree[otu][0][0] == None. But perhaps you should reconsider your path of action and the datatype in question to see if you could improve the structure somewhat.

How can I convert string to datetime with format specification in JavaScript?

//Here pdate is the string date time
var date1=GetDate(pdate);
    function GetDate(a){
        var dateString = a.substr(6);
        var currentTime = new Date(parseInt(dateString ));
        var month =("0"+ (currentTime.getMonth() + 1)).slice(-2);
        var day =("0"+ currentTime.getDate()).slice(-2);
        var year = currentTime.getFullYear();
        var date = day + "/" + month + "/" + year;
        return date;
    }

"Bitmap too large to be uploaded into a texture"

NOTE FOR THOSE WHO WANT TO PUT IMAGES OF SMALL SIZE:

Pilot_51's solution (moving your images to drawable-nodpi folder) works, but has another problem: It makes images TOO SMALL on screen unless the images are resized to a very large (like 2000 x 3800) resolution to fit screen -- then it makes your app heavier.

SOLUTION: put your image files in drawable-hdpi -- It worked like a charm for me.

VBA: Conditional - Is Nothing

In my sample code, I was setting my object to nothing, and I couldn't get the "not" part of the if statement to work with the object. I tried if My_Object is not nothing and also if not My_Object is nothing. It may be just a syntax thing I can't figure out but I didn't have time to mess around, so I did a little workaround like this:

if My_Object is Nothing Then
    'do nothing
Else
    'Do something
End if

Installing Bootstrap 3 on Rails App

Actually you don't need gem for this, here is the step to install Bootstrap 3 in RoR

  • Download Bootstrap

  • Copy:

    bootstrap-dist/css/bootstrap.css and bootstrap-dist/css/bootstrap.min.css

    To: vendor/assets/stylesheets

  • Copy:

    bootstrap-dist/js/bootstrap.js and bootstrap-dist/js/bootstrap.min.js

    To: vendor/assets/javascripts

  • Update: app/assets/stylesheets/application.css by adding:

    *= require bootstrap.min
    
  • Update: app/assets/javascripts/application.jsby adding:

    //= require bootstrap.min
    

With this you can update bootstrap any time you want, don't need to wait gem to be updated. Also with this approach assets pipeline will use minified versions in production.

Binding List<T> to DataGridView in WinForm

Yes, it is possible to do with out rebinding by implementing INotifyPropertyChanged Interface.

Pretty Simple example is available here,

http://msdn.microsoft.com/en-us/library/system.componentmodel.inotifypropertychanged.aspx

Project has no default.properties file! Edit the project properties to set one

In my case I went to My Project then to > Properties > Android > and checked Google API box. Clicking 'Okay' caused it to then work for me.

Removing all empty elements from a hash / YAML?

If you're using Ruby 2.4+, you can call compact and compact!

h = { a: 1, b: false, c: nil }
h.compact! #=> { a: 1, b: false }

https://ruby-doc.org/core-2.4.0/Hash.html#method-i-compact-21

fork() child and parent processes

We control fork() process call by if, else statement. See my code below:

int main()
{
   int forkresult, parent_ID;

   forkresult=fork();
   if(forkresult !=0 )
   {
        printf(" I am the parent my ID is = %d" , getpid());
        printf(" and my child ID is = %d\n" , forkresult);
   }
   parent_ID = getpid();

   if(forkresult ==0)
      printf(" I am the  child ID is = %d",getpid());
   else
      printf(" and my parent ID is = %d", parent_ID);
}

How to connect PHP with Microsoft Access database

Are you sure the odbc connector is well created ? if not check the step "Create an ODBC Connection" again

EDIT: Connection without DSN from php.net

// Microsoft Access

$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=$mdbFilename", $user, $password);

in your case it might be if your filename is northwind and your file extension mdb:

$connection = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=northwind", "", "");

Why do we assign a parent reference to the child object in Java?

You declare parent as Parent, so java will provide only methods and attributes of the Parent class.

Child child = new Child();

should work. Or

Parent child = new Child();
((Child)child).salary = 1;

How can I get the values of data attributes in JavaScript code?

You could also grab the attributes with the getAttribute() method which will return the value of a specific HTML attribute.

_x000D_
_x000D_
var elem = document.getElementById('the-span');_x000D_
_x000D_
var typeId = elem.getAttribute('data-typeId');_x000D_
var type   = elem.getAttribute('data-type');_x000D_
var points = elem.getAttribute('data-points');_x000D_
var important = elem.getAttribute('data-important');_x000D_
_x000D_
console.log(`typeId: ${typeId} | type: ${type} | points: ${points} | important: ${important}`_x000D_
);
_x000D_
<span data-typeId="123" data-type="topic" data-points="-1" data-important="true" id="the-span"></span>
_x000D_
_x000D_
_x000D_

restrict edittext to single line

Use android:maxLines="1" and android:inputType="text"

You forgot the android:maxLines attribute. And refer for android:inputType With your example, below will give this result:

<EditText 
    android:id="@+id/searchbox"  
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxLines="1"
    android:inputType="text"
    android:scrollHorizontally="true"
    android:ellipsize="end"
    android:layout_weight="1"
    android:layout_marginTop="2dp"
    android:drawablePadding="10dp"
    android:background="@drawable/edittext"
    android:drawableLeft="@drawable/folder_full"
    android:drawableRight="@drawable/search"
    android:paddingLeft="15dp"
    android:hint="search...">
</EditText>

Is it possible to modify a registry entry via a .bat/.cmd script?

In addition to reg.exe, I highly recommend that you also check out powershell, its vastly more capable in its registry handling.

DirectX SDK (June 2010) Installation Problems: Error Code S1023

I've had the same problem twice already and the easiest and most concise solution that I found is located here (in MSDN Blogs -> Games for Windows and the DirectX SDK). However, just in case that page goes down, here's the method:

  1. Remove the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1) from the system (both x86 and x64 if applicable). This can be easily done via a command-line with administrator rights:

    MsiExec.exe /passive /X{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}
    MsiExec.exe /passive /X{1D8E6291-B0D5-35EC-8441-6616F567A0F7}
    
  2. Install the DirectX SDK (June 2010)

  3. Reinstall the Visual C++ 2010 Redistributable Package version 10.0.40219 (Service Pack 1). On an x64 system, you should install both the x86 and x64 versions of the C++ REDIST. Be sure to install the most current version available, which at this point is the KB 2565063 with a security fix.

Note: This issue does not affect earlier version of the DirectX SDK which deploy the VS 2005 / VS 2008 CRT REDIST and do not deploy the VS 2010 CRT REDIST. This issue does not affect the DirectX End-User Runtime web or stand-alone installer as those packages do not deploy any version of the VC++ CRT.

File Checksum Integrity Verifier: This of course assumes you actually have an uncorrupted copy of the DirectX SDK setup package. The best way to validate this it to run

fciv -sha1 DXSDK_Jun10.exe

and verify you get

8fe98c00fde0f524760bb9021f438bd7d9304a69 dxsdk_jun10.exe

How to count the number of letters in a string without the spaces?

word_display = ""
for letter in word:
    if letter in known:
        word_display = "%s%s " % (word_display, letter)
    else:
        word_display = "%s_ " % word_display
return word_display

Write to file, but overwrite it if it exists

To overwrite one file's content to another file. use cat eg.

echo  "this is foo" > foobar.txt
cat foobar.txt

echo "this is bar" > bar.txt
cat bar.txt

Now to overwrite foobar we can use a cat command as below

cat bar.txt >> foobar.txt
cat foobar.txt

enter image description here

How to kill a child process after a given timeout in Bash?

One way is to run the program in a subshell, and communicate with the subshell through a named pipe with the read command. This way you can check the exit status of the process being run and communicate this back through the pipe.

Here's an example of timing out the yes command after 3 seconds. It gets the PID of the process using pgrep (possibly only works on Linux). There is also some problem with using a pipe in that a process opening a pipe for read will hang until it is also opened for write, and vice versa. So to prevent the read command hanging, I've "wedged" open the pipe for read with a background subshell. (Another way to prevent a freeze to open the pipe read-write, i.e. read -t 5 <>finished.pipe - however, that also may not work except with Linux.)

rm -f finished.pipe
mkfifo finished.pipe

{ yes >/dev/null; echo finished >finished.pipe ; } &
SUBSHELL=$!

# Get command PID
while : ; do
    PID=$( pgrep -P $SUBSHELL yes )
    test "$PID" = "" || break
    sleep 1
done

# Open pipe for writing
{ exec 4>finished.pipe ; while : ; do sleep 1000; done } &  

read -t 3 FINISHED <finished.pipe

if [ "$FINISHED" = finished ] ; then
  echo 'Subprocess finished'
else
  echo 'Subprocess timed out'
  kill $PID
fi

rm finished.pipe

How do I find out what version of WordPress is running?

I know I'm super late regarding this topic but there's this easy to use library where you can easily get the version numbers of Worpress, PHP, Apache, and MySQL, all-in-one.

It is called the Wordpress Environment (W18T) library

<?php
include_once 'W18T.class.php';
$environment = new W18T();
echo $environment;
?>

Output

{
    "platform": {
        "name": "WordPress",
        "version": "4.9.1"
    },
    "interpreter": {
        "name": "PHP",
        "version": "7.2.0"
    },
    "web_server": {
        "name": "Apache",
        "version": "2.4.16"
    },
    "database_server": {
        "name": "MySQL",
        "version": "5.7.20"
    },
    "operating_system": {
        "name": "Darwin",
        "version": "17.0.0"
    }
}

I hope it helps.

How to correctly close a feature branch in Mercurial?

EDIT ouch, too late... I know read your comment stating that you want to keep the feature-x changeset around, so the cloning approach here doesn't work.

I'll still let the answer here for it may help others.

If you want to completely get rid of "feature X", because, for example, it didn't work, you can clone. This is one of the method explained in the article and it does work, and it talks specifically about heads.

As far as I understand you have this and want to get rid of the "feature-x" head once and for all:

@    changeset:   7:00a7f69c8335
|\   tag:         tip
| |  parent:      4:31b6f976956b
| |  parent:      2:0a834fa43688
| |  summary:     merge
| |
| | o  changeset:   5:013a3e954cfd
| |/   summary:     Closed branch feature-x
| |
| o  changeset:   4:31b6f976956b
| |  summary:     Changeset2
| |
| o  changeset:   3:5cb34be9e777
| |  parent:      1:1cc843e7f4b5
| |  summary:     Changeset 1
| |
o |  changeset:   2:0a834fa43688
|/   summary:     Changeset C
|
o  changeset:   1:1cc843e7f4b5
|  summary:     Changeset B
|
o  changeset:   0:a9afb25eaede
   summary:     Changeset A

So you do this:

hg clone . ../cleanedrepo --rev 7

And you'll have the following, and you'll see that feature-x is indeed gone:

@    changeset:   5:00a7f69c8335
|\   tag:         tip
| |  parent:      4:31b6f976956b
| |  parent:      2:0a834fa43688
| |  summary:     merge
| |
| o  changeset:   4:31b6f976956b
| |  summary:     Changeset2
| |
| o  changeset:   3:5cb34be9e777
| |  parent:      1:1cc843e7f4b5
| |  summary:     Changeset 1
| |
o |  changeset:   2:0a834fa43688
|/   summary:     Changeset C
|
o  changeset:   1:1cc843e7f4b5
|  summary:     Changeset B
|
o  changeset:   0:a9afb25eaede
   summary:     Changeset A

I may have misunderstood what you wanted but please don't mod down, I took time reproducing your use case : )

Clear MySQL query cache without restarting server

I believe you can use...

RESET QUERY CACHE;

...if the user you're running as has reload rights. Alternatively, you can defragment the query cache via...

FLUSH QUERY CACHE;

See the Query Cache Status and Maintenance section of the MySQL manual for more information.

Throwing exceptions from constructors

Apart from the fact that you do not need to throw from the constructor in your specific case because pthread_mutex_lock actually returns an EINVAL if your mutex has not been initialized and you can throw after the call to lock as is done in std::mutex:

void
lock()
{
  int __e = __gthread_mutex_lock(&_M_mutex);

  // EINVAL, EAGAIN, EBUSY, EINVAL, EDEADLK(may)
  if (__e)
__throw_system_error(__e);
}

then in general throwing from constructors is ok for acquisition errors during construction, and in compliance with RAII ( Resource-acquisition-is-Initialization ) programming paradigm.

Check this example on RAII

void write_to_file (const std::string & message) {
    // mutex to protect file access (shared across threads)
    static std::mutex mutex;

    // lock mutex before accessing file
    std::lock_guard<std::mutex> lock(mutex);

    // try to open file
    std::ofstream file("example.txt");
    if (!file.is_open())
        throw std::runtime_error("unable to open file");

    // write message to file
    file << message << std::endl;

    // file will be closed 1st when leaving scope (regardless of exception)
    // mutex will be unlocked 2nd (from lock destructor) when leaving
    // scope (regardless of exception)
}

Focus on these statements:

  1. static std::mutex mutex
  2. std::lock_guard<std::mutex> lock(mutex);
  3. std::ofstream file("example.txt");

The first statement is RAII and noexcept. In (2) it is clear that RAII is applied on lock_guard and it actually can throw , whereas in (3) ofstream seems not to be RAII , since the objects state has to be checked by calling is_open() that checks the failbit flag.

At first glance it seems that it is undecided on what it the standard way and in the first case std::mutex does not throw in initialization , *in contrast to OP implementation * . In the second case it will throw whatever is thrown from std::mutex::lock, and in the third there is no throw at all.

Notice the differences:

(1) Can be declared static, and will actually be declared as a member variable (2) Will never actually be expected to be declared as a member variable (3) Is expected to be declared as a member variable, and the underlying resource may not always be available.

All these forms are RAII; to resolve this, one must analyse RAII.

  • Resource : your object
  • Acquisition ( allocation ) : you object being created
  • Initialization : your object is in its invariant state

This does not require you to initialize and connect everything on construction. For example when you would create a network client object you would not actually connect it to the server upon creation, since it is a slow operation with failures. You would instead write a connect function to do just that. On the other hand you could create the buffers or just set its state.

Therefore, your issue boils down to defining your initial state. If in your case your initial state is mutex must be initialized then you should throw from the constructor. In contrast it is just fine not to initialize then ( as is done in std::mutex ), and define your invariant state as mutex is created . At any rate the invariant is not compromized necessarily by the state of its member object, since the mutex_ object mutates between locked and unlocked through the Mutex public methods Mutex::lock() and Mutex::unlock().

class Mutex {
private:
  int e;
  pthread_mutex_t mutex_;

public:
  Mutex(): e(0) {
  e = pthread_mutex_init(&mutex_);
  }

  void lock() {

    e = pthread_mutex_lock(&mutex_);
    if( e == EINVAL ) 
    { 
      throw MutexInitException();
    }
    else (e ) {
      throw MutexLockException();
    }
  }

  // ... the rest of your class
};

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

add these dependecies to your .pom file:

<dependency>
  <groupId>org.hsqldb</groupId>
  <artifactId>hsqldb</artifactId>
  <version>2.5.0</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>com.healthmarketscience.jackcess</groupId>
  <artifactId>jackcess-encrypt</artifactId>
  <version>3.0.0</version>
</dependency>

<dependency>
  <groupId>net.sf.ucanaccess</groupId>
  <artifactId>ucanaccess</artifactId>
  <version>5.0.0</version>
</dependency>

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.9</version>
</dependency>

<dependency>
  <groupId>commons-logging</groupId>
  <artifactId>commons-logging</artifactId>
  <version>1.2</version>
</dependency>

and add to your code to call a driver:

Connection conn = DriverManager.getConnection("jdbc:ucanaccess://{file_location}/{accessdb_file_name.mdb};memory=false");

Sorting object property by values

Thank you and continue answer @Nosredna

Now that we understand object need to be converted to array then sort the array. this is useful for sorting array (or converted object to array) by string:

Object {6: Object, 7: Object, 8: Object, 9: Object, 10: Object, 11: Object, 12: Object}
   6: Object
   id: "6"
   name: "PhD"
   obe_service_type_id: "2"
   __proto__: Object
   7: Object
   id: "7"
   name: "BVC (BPTC)"
   obe_service_type_id: "2"
   __proto__: Object


    //Sort options
    var sortable = [];
    for (var vehicle in options)
    sortable.push([vehicle, options[vehicle]]);
    sortable.sort(function(a, b) {
        return a[1].name < b[1].name ? -1 : 1;
    });


    //sortable => prints  
[Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2]]
    0: Array[2]
    0: "11"
    1: Object
        id: "11"
        name: "AS/A2"
        obe_service_type_id: "2"
        __proto__: Object
        length: 2
        __proto__: Array[0]
    1: Array[2]
    0: "7"
    1: Object
        id: "7"
        name: "BVC (BPTC)"
        obe_service_type_id: "2"
        __proto__: Object
        length: 2

How to check if a String contains only ASCII?

Iterate through the string, and use charAt() to get the char. Then treat it as an int, and see if it has a unicode value (a superset of ASCII) which you like.

Break at the first you don't like.

How do I profile memory usage in Python?

If you only want to look at the memory usage of an object, (answer to other question)

There is a module called Pympler which contains the asizeof module.

Use as follows:

from pympler import asizeof
asizeof.asizeof(my_object)

Unlike sys.getsizeof, it works for your self-created objects.

>>> asizeof.asizeof(tuple('bcd'))
200
>>> asizeof.asizeof({'foo': 'bar', 'baz': 'bar'})
400
>>> asizeof.asizeof({})
280
>>> asizeof.asizeof({'foo':'bar'})
360
>>> asizeof.asizeof('foo')
40
>>> asizeof.asizeof(Bar())
352
>>> asizeof.asizeof(Bar().__dict__)
280
>>> help(asizeof.asizeof)
Help on function asizeof in module pympler.asizeof:

asizeof(*objs, **opts)
    Return the combined size in bytes of all objects passed as positional arguments.

Java AES and using my own Key

MD5, AES, no padding

import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;
import static org.apache.commons.io.Charsets.UTF_8;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

public class PasswordUtils {

    private PasswordUtils() {}

    public static String encrypt(String text, String pass) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            Key key = new SecretKeySpec(messageDigest.digest(pass.getBytes(UTF_8)), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(ENCRYPT_MODE, key);

            byte[] encrypted = cipher.doFinal(text.getBytes(UTF_8));
            byte[] encoded = Base64.getEncoder().encode(encrypted);
            return new String(encoded, UTF_8);

        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException("Cannot encrypt", e);
        }
    }

    public static String decrypt(String text, String pass) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            Key key = new SecretKeySpec(messageDigest.digest(pass.getBytes(UTF_8)), "AES");
            Cipher cipher = Cipher.getInstance("AES");
            cipher.init(DECRYPT_MODE, key);

            byte[] decoded = Base64.getDecoder().decode(text.getBytes(UTF_8));
            byte[] decrypted = cipher.doFinal(decoded);
            return new String(decrypted, UTF_8);

        } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
            throw new RuntimeException("Cannot decrypt", e);
        }
    }
}

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

as you can see on the answer to this question: Conversion of a varchar data type to a datetime data type resulted in an out-of-range value

-- set the dateformat for the current session
set dateformat dmy

-- The conversion of a varchar data type 
-- to a datetime data type resulted in an out-of-range value.
select cast('2017-08-13 16:31:31'  as datetime)

-- get the current session date_format
select date_format
from sys.dm_exec_sessions
where session_id = @@spid

-- set the dateformat for the current session
set dateformat ymd

-- this should work
select cast('2017-08-13 16:31:31'  as datetime)

Python JSON encoding

Try:

import simplejson
data = {'apple': 'cat', 'banana':'dog', 'pear':'fish'}
data_json = "{'apple': 'cat', 'banana':'dog', 'pear':'fish'}"

simplejson.loads(data_json) # outputs data
simplejson.dumps(data) # outputs data_joon

NB: Based on Paolo's answer.

Check difference in seconds between two times

This version always returns the number of seconds difference as a positive number (same result as @freedeveloper's solution):

var seconds = System.Math.Abs((date1 - date2).TotalSeconds);

Remove numbers from string sql server

1st option -

You can nest REPLACE() functions up to 32 levels deep. It runs fast.

REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE
(REPLACE (@str, '0', ''),
'1', ''),
'2', ''),
'3', ''),
'4', ''),
'5', ''),
'6', ''),
'7', ''),
'8', ''),
'9', '')

2nd option -- do the reverse of -

Removing nonnumerical data out of a number + SQL

3rd option - if you want to use regex

then http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=27205

How can I make a button redirect my page to another page?

Just another variation:

    <body>
    <button name="redirect" onClick="redirect()">

    <script type="text/javascript">
    function redirect()
    {
    var url = "http://www.(url).com";
    window.location(url);
    }
    </script>

Use jquery click to handle anchor onClick()

Lets take an anchor tag with an onclick event, that calls a Javascript function.

<a href="#" onClick="showDiv(1);">1</a>

Now in javascript write the below code

function showDiv(pageid)
{
   alert(pageid);
}

This will show you an alert of "1"....

Listing information about all database files in SQL Server

You can use the below:

SP_HELPDB [Master]
GO

execJs: 'Could not find a JavaScript runtime' but execjs AND therubyracer are in Gemfile

when i generate rails g controller i got the same error. After that when do the following changes on Gemfile(in rails 4) everything went smooth.The changes i made was

gem 'execjs'
gem 'therubyracer', "0.11.4"
After that i can able to run the server and able to do all basic operations on the application.

How to launch multiple Internet Explorer windows/tabs from batch file?

Of course it is an old post but just for people how will find it through search engine.

Another solution is to run it like this for IE9 and later

iexplore.exe" -noframemerging http://google.com
iexplore.exe" -noframemerging http://gmail.com

-noframemerging means run IE independently. For example it you want to run 2 browser and login as different username it will not work if you just run 2 IE. but with -noframemerging it will work. -noframemerging works for IE9 and later, for early versions like IE8 it is -nomerge

usually I create 1 but file like this run_ie.bat

"c:\Program Files (x86)\Internet Explorer\iexplore.exe" -noframemerging %1

and I create another bat file like this run_2_ie.bat

start run_ie.bat http://google.com
start run_ie.bat http://yahoo.com

How can I show figures separately in matplotlib?

I think I am a bit late to the party but... In my opinion, what you need is the object oriented API of matplotlib. In matplotlib 1.4.2 and using IPython 2.4.1 with Qt4Agg backend, I can do the following:

import matplotlib.pyplot as plt
fig, ax = plt.subplots(1) # Creates figure fig and add an axes, ax.
fig2, ax2 = plt.subplots(1) # Another figure

ax.plot(range(20)) #Add a straight line to the axes of the first figure.
ax2.plot(range(100)) #Add a straight line to the axes of the first figure.

fig.show() #Only shows figure 1 and removes it from the "current" stack.
fig2.show() #Only shows figure 2 and removes it from the "current" stack.
plt.show() #Does not show anything, because there is nothing in the "current" stack.
fig.show() # Shows figure 1 again. You can show it as many times as you want.

In this case plt.show() shows anything in the "current" stack. You can specify figure.show() ONLY if you are using a GUI backend (e.g. Qt4Agg). Otherwise, I think you will need to really dig down into the guts of matplotlib to monkeypatch a solution.

Remember that most (all?) plt.* functions are just shortcuts and aliases for figure and axes methods. They are very useful for sequential programing, but you will find blocking walls very soon if you plan to use them in a more complex way.

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

Absolute Xpath: It uses Complete path from the Root Element to the desire element.

Relative Xpath: You can simply start by referencing the element you want and go from there.

Relative Xpaths are always preferred as they are not the complete paths from the root element. (//html//body). Because in future, if any webelement is added/removed, then the absolute Xpath changes. So Always use Relative Xpaths in your Automation.

Below are Some Links which you can Refer for more Information on them.

Counting the number of elements with the values of x in a vector

here's one fast and dirty way:

x <- 23
length(subset(numbers, numbers==x))

LaTeX source code listing like in professional books

I am happy with the listings package:

Listing example

Here is how I configure it:

\lstset{
language=C,
basicstyle=\small\sffamily,
numbers=left,
numberstyle=\tiny,
frame=tb,
columns=fullflexible,
showstringspaces=false
}

I use it like this:

\begin{lstlisting}[caption=Caption example.,
  label=a_label,
  float=t]
// Insert the code here
\end{lstlisting}

vb.net get file names in directory?

Try this:

Dim text As String = ""
Dim files() As String = IO.Directory.GetFiles(sFolder)

For Each sFile As String In files
    text &= IO.File.ReadAllText(sFile)
Next

Convert string to variable name in JavaScript

You can do like this

_x000D_
_x000D_
var name = "foo";_x000D_
var value = "Hello foos";_x000D_
eval("var "+name+" = '"+value+"';");_x000D_
alert(foo);
_x000D_
_x000D_
_x000D_

Passing ArrayList from servlet to JSP

request.getAttribute("servletName") method will return Object that you need to cast to ArrayList

ArrayList<Category> list =new ArrayList<Category>();
//storing passed value from jsp
list = (ArrayList<Category>)request.getAttribute("servletName");

Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

Your method (placing script before the closing body tag)

<script>
   myFunction()
</script>
</body>
</html>

is a reliable way to support old and new browsers.

python, sort descending dataframe with pandas

For pandas 0.17 and above, use this :

test = df.sort_values('one', ascending=False)

Since 'one' is a series in the pandas data frame, hence pandas will not accept the arguments in the form of a list.

Github: Can I see the number of downloads for a repo?

As mentioned, GitHub API returns downloads count of binary file releases. I developed a little script to easly get downloads count by command line.

What are the differences between type() and isinstance()?

According to python documentation here is a statement:

8.15. types — Names for built-in types

Starting in Python 2.2, built-in factory functions such as int() and str() are also names for the corresponding types.

So isinstance() should be preferred over type().

Android camera android.hardware.Camera deprecated

 if ( getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {

          CameraManager cameraManager=(CameraManager) getActivity().getSystemService(Context.CAMERA_SERVICE);


           try {
               String cameraId = cameraManager.getCameraIdList()[0];
               cameraManager.setTorchMode(cameraId,true);
           } catch (CameraAccessException e) {
               e.printStackTrace();
           }


 }

Can two applications listen to the same port?

Yes Definitely. As far as i remember From kernel version 3.9 (Not sure on the version) onwards support for the SO_REUSEPORT was introduced. SO_RESUEPORT allows binding to the exact same port and address, As long as the first server sets this option before binding its socket.

It works for both TCP and UDP. Refer to the link for more details: SO_REUSEPORT

Note: Accepted answer no longer holds true as per my opinion.

Use dynamic variable names in `dplyr`

After a lot of trial and error, I found the pattern UQ(rlang::sym("some string here"))) really useful for working with strings and dplyr verbs. It seems to work in a lot of surprising situations.

Here's an example with mutate. We want to create a function that adds together two columns, where you pass the function both column names as strings. We can use this pattern, together with the assignment operator :=, to do this.

## Take column `name1`, add it to column `name2`, and call the result `new_name`
mutate_values <- function(new_name, name1, name2){
  mtcars %>% 
    mutate(UQ(rlang::sym(new_name)) :=  UQ(rlang::sym(name1)) +  UQ(rlang::sym(name2)))
}
mutate_values('test', 'mpg', 'cyl')

The pattern works with other dplyr functions as well. Here's filter:

## filter a column by a value 
filter_values <- function(name, value){
  mtcars %>% 
    filter(UQ(rlang::sym(name)) != value)
}
filter_values('gear', 4)

Or arrange:

## transform a variable and then sort by it 
arrange_values <- function(name, transform){
  mtcars %>% 
    arrange(UQ(rlang::sym(name)) %>%  UQ(rlang::sym(transform)))
}
arrange_values('mpg', 'sin')

For select, you don't need to use the pattern. Instead you can use !!:

## select a column 
select_name <- function(name){
  mtcars %>% 
    select(!!name)
}
select_name('mpg')

Is it possible to view RabbitMQ message contents directly from the command line?

you can use RabbitMQ API to get count or messages :

/api/queues/vhost/name/get

Get messages from a queue. (This is not an HTTP GET as it will alter the state of the queue.) You should post a body looking like:

{"count":5,"requeue":true,"encoding":"auto","truncate":50000}

count controls the maximum number of messages to get. You may get fewer messages than this if the queue cannot immediately provide them.

requeue determines whether the messages will be removed from the queue. If requeue is true they will be requeued - but their redelivered flag will be set. encoding must be either "auto" (in which case the payload will be returned as a string if it is valid UTF-8, and base64 encoded otherwise), or "base64" (in which case the payload will always be base64 encoded). If truncate is present it will truncate the message payload if it is larger than the size given (in bytes). truncate is optional; all other keys are mandatory.

Please note that the publish / get paths in the HTTP API are intended for injecting test messages, diagnostics etc - they do not implement reliable delivery and so should be treated as a sysadmin's tool rather than a general API for messaging.

http://hg.rabbitmq.com/rabbitmq-management/raw-file/rabbitmq_v3_1_3/priv/www/api/index.html

What's the use of ob_start() in php?

Think of ob_start() as saying "Start remembering everything that would normally be outputted, but don't quite do anything with it yet."

For example:

ob_start();
echo("Hello there!"); //would normally get printed to the screen/output to browser
$output = ob_get_contents();
ob_end_clean();

There are two other functions you typically pair it with: ob_get_contents(), which basically gives you whatever has been "saved" to the buffer since it was turned on with ob_start(), and then ob_end_clean() or ob_flush(), which either stops saving things and discards whatever was saved, or stops saving and outputs it all at once, respectively.

C - freeing structs

This way you only need to free the structure because the fields are arrays with static sizes which will be allocated as part of the structure. This is also the reason that the addresses you see match: the array is the first thing in that structure. If you declared the fields as char * you would have to manually malloc and free them as well.

How do I print a double value without scientific notation using Java?

Java prevent E notation in a double:

Five different ways to convert a double to a normal number:

import java.math.BigDecimal;
import java.text.DecimalFormat;

public class Runner {
    public static void main(String[] args) {
        double myvalue = 0.00000021d;

        //Option 1 Print bare double.
        System.out.println(myvalue);

        //Option2, use decimalFormat.
        DecimalFormat df = new DecimalFormat("#");
        df.setMaximumFractionDigits(8);
        System.out.println(df.format(myvalue));

        //Option 3, use printf.
        System.out.printf("%.9f", myvalue);
        System.out.println();

        //Option 4, convert toBigDecimal and ask for toPlainString().
        System.out.print(new BigDecimal(myvalue).toPlainString());
        System.out.println();

        //Option 5, String.format 
        System.out.println(String.format("%.12f", myvalue));
    }
}

This program prints:

2.1E-7
.00000021
0.000000210
0.000000210000000000000001085015324114868562332958390470594167709350585
0.000000210000

Which are all the same value.

Protip: If you are confused as to why those random digits appear beyond a certain threshold in the double value, this video explains: computerphile why does 0.1+0.2 equal 0.30000000000001?

http://youtube.com/watch?v=PZRI1IfStY0

wget: unable to resolve host address `http'

I have this issue too. I suspect there is an issue with DigitalOcean’s nameservers, so this will likely affect a lot of other people too. Here’s what I’ve done to temporarily get around it - but someone else might be able to advise on a better long-term fix:

  1. Make sure your DNS Resolver config file is writable:

    sudo chmod o+r /etc/resolv.conf

  2. Temporarily change your DNS to use Google’s nameservers instead of DigitalOcean’s:

    sudo nano /etc/resolv.conf

Change the IP address in the file to: 8.8.8.8

Press CTRL + X to save the file.

This is only a temporary fix as this file is automatically written/updated by the server, however, I’ve not yet worked out what writes to it so that I can update it permanently.

What is a web service endpoint?

In past projects I worked on, the endpoint was a relative property. That is to say it may or may not have been appended to, but it always contained the protocol://host:port/partOfThePath.

If the service being called had a dynamic part to it, for example a ?param=dynamicValue, then that part would get added to the endpoint. But many times the endpoint could be used as is without having to be amended.

Whats important to understand is what an endpoint is not and how it helps. For example an alternative way to pass the information stored in an endpoint would be to store the different parts of the endpoint in separate properties. For example:

hostForServiceA=someIp
portForServiceA=8080
pathForServiceA=/some/service/path
hostForServiceB=someIp
portForServiceB=8080
pathForServiceB=/some/service/path

Or if the same host and port across multiple services:

host=someIp
port=8080
pathForServiceA=/some/service/path
pathForServiceB=/some/service/path

In those cases the full URL would need to be constructed in your code as such:

String url = "http://" + host + ":" + port + pathForServiceA  + "?" + dynamicParam + "=" + dynamicValue;

In contract this can be stored as an endpoint as such

serviceAEndpoint=http://host:port/some/service/path?dynamicParam=

And yes many times we stored the endpoint up to and including the '='. This lead to code like this:

String url = serviceAEndpoint + dynamicValue;

Hope that sheds some light.

Add leading zeroes/0's to existing Excel values to certain length

The more efficient (less obtrusive) way of doing this is through custom formatting.

  1. Highlight the column/array you want to style.
  2. Click ctrl + 1 or Format -> Format Cells.
  3. In the Number tab, choose Custom.
  4. Set the Custom formatting to 000#. (zero zero zero #)

Note that this does not actually change the value of the cell. It only displays the leading zeroes in the worksheet.

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

My solution:

1) create a temp ArrayList.

2) do your heavy works (sqlite row fetch , ...) in doInBackground method and add items to the temp arraylist.

3) add all items from temp araylist to your listview's arraylist in onPostExecute method.

note: you may want to delete some items from listview and also delete from sqlite database and maybe delete some files related to items from sdcard , just remove items from database and remove their related files and add them to temp arraylist in background thread. then in UI thread delete items existing in temp arraylist from the listview's arraylist.

Hope this helps.

How can I account for period (AM/PM) using strftime?

The Python time.strftime docs say:

When used with the strptime() function, the %p directive only affects the output hour field if the %I directive is used to parse the hour.

Sure enough, changing your %H to %I makes it work.

How to add element into ArrayList in HashMap

First you have to add an ArrayList to the Map

ArrayList<Item> al = new ArrayList<Item>();

Items.add("theKey", al); 

then you can add an item to the ArrayLIst that is inside the Map like this:

Items.get("theKey").add(item);  // item is an object of type Item

How to call a function, PostgreSQL

I had this same issue while trying to test a very similar function that uses a SELECT statement to decide if a INSERT or an UPDATE should be done. This function was a re-write of a T-SQL stored procedure.
When I tested the function from the query window I got the error "query has no destination for result data". I finally figured out that because I used a SELECT statement inside the function that I could not test the function from the query window until I assigned the results of the SELECT to a local variable using an INTO statement. This fixed the problem.

If the original function in this thread was changed to the following it would work when called from the query window,

$BODY$
DECLARE
   v_temp integer;
BEGIN
SELECT 1 INTO v_temp
FROM "USERS"
WHERE "userID" = $1;

Case-insensitive search in Rails model

You'll probably have to be more verbose here

name = "Blue Jeans"
model = Product.where('lower(name) = ?', name.downcase).first 
model ||= Product.create(:name => name)

Android: checkbox listener

You get the error because you imported wrong package.You should import android.widget.CompoundButton.OnCheckedChangeListener;

So the callback should be :

        box.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            // TODO Auto-generated method stub

        }
    });

What is the best way to convert an array to a hash in Ruby

Edit: Saw the responses posted while I was writing, Hash[a.flatten] seems the way to go. Must have missed that bit in the documentation when I was thinking through the response. Thought the solutions that I've written can be used as alternatives if required.

The second form is simpler:

a = [[:apple, 1], [:banana, 2]]
h = a.inject({}) { |r, i| r[i.first] = i.last; r }

a = array, h = hash, r = return-value hash (the one we accumulate in), i = item in the array

The neatest way that I can think of doing the first form is something like this:

a = [:apple, 1, :banana, 2]
h = {}
a.each_slice(2) { |i| h[i.first] = i.last }

How to get first and last element in an array in java?

Getting first and last elements in an array in Java

int[] a = new int[]{1, 8, 5, 9, 4};

First Element: a[0]

Last Element: a[a.length-1]

Border in shape xml

We can add drawable .xml like below

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


    <stroke
        android:width="1dp"
        android:color="@color/color_C4CDD5"/>

    <corners android:radius="8dp"/>

    <solid
        android:color="@color/color_white"/>

</shape>

Difference between array_push() and $array[] =

array_push — Push one or more elements onto the end of array

Take note of the words "one or more elements onto the end" to do that using $arr[] you would have to get the max size of the array

Div width 100% minus fixed amount of pixels

what if your wrapping div was 100% and you used padding for a pixel amount, then if the padding # needs to be dynamic, you can easily use jQuery to modify your padding amount when your events fire.

Python recursive folder read

If you prefer an (almost) Oneliner:

from pathlib import Path

lookuppath = '.' #use your path
filelist = [str(item) for item in Path(lookuppath).glob("**/*") if Path(item).is_file()]

In this case you will get a list with just the paths of all files located recursively under lookuppath. Without str() you will get PosixPath() added to each path.

Unable to find velocity template resources

You can also put your templates folder under src/main/resources instead of src/main/java. Works for me and it's a preferable location since templates are not java source.

Change output format for MySQL command line results to CSV

If you are using mysql client you can set up the resultFormat per session e.g.

mysql -h localhost -u root --resutl-format=json

or

mysql -h localhost -u root --vertical

Check out the full list of arguments here.

What data is stored in Ephemeral Storage of Amazon EC2 instance?

Anything that is not stored on an EBS volume that is mounted to the instance will be lost.

For example, if you mount your EBS volume at /mystuff, then anything not in /mystuff will be lost. If you don't mount an ebs volume and save stuff on it, then I believe everything will be lost.

You can create an AMI from your current machine state, which will contain everything in your ephemeral storage. Then, when you launch a new instance based on that AMI it will contain everything as it is now.

Update: to clarify based on comments by mattgmg1990 and glenn bech:

Note that there is a difference between "stop" and "terminate". If you "stop" an instance that is backed by EBS then the information on the root volume will still be in the same state when you "start" the machine again. According to the documentation, "By default, the root device volume and the other Amazon EBS volumes attached when you launch an Amazon EBS-backed instance are automatically deleted when the instance terminates" but you can modify that via configuration.

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

I got this error, while using it on my rocketchat to communicate with my gitlab via enterprise proxy,

Because, was using the https://:8080 but actually, it worked for http://:8080

How can I check if a string contains ANY letters from the alphabet?

You can use regular expression like this:

import re

print re.search('[a-zA-Z]+',string)

ORACLE IIF Statement

In PL/SQL, there is a trick to use the undocumented OWA_UTIL.ITE function.

SET SERVEROUTPUT ON

DECLARE
    x   VARCHAR2(10);
BEGIN
    x := owa_util.ite('a' = 'b','T','F');
    dbms_output.put_line(x);
END;
/

F

PL/SQL procedure successfully completed.

Getting all names in an enum as a String[]

i'd do it this way (but i'd probably make names an unmodifiable set instead of an array):

import java.util.Arrays;
enum State {
    NEW,RUNNABLE,BLOCKED,WAITING,TIMED_WAITING,TERMINATED;
    public static final String[] names=new String[values().length];
    static {
        State[] values=values();
        for(int i=0;i<values.length;i++)
            names[i]=values[i].name();
    }
}
public class So13783295 {
    public static void main(String[] args) {
        System.out.println(Arrays.asList(State.names));
    }
}

How to loop and render elements in React-native?

For initial array, better use object instead of array, as then you won't be worrying about the indexes and it will be much more clear what is what:

const initialArr = [{
    color: "blue",
    text: "text1"
}, {
    color: "red",
    text: "text2"
}];

For actual mapping, use JS Array map instead of for loop - for loop should be used in cases when there's no actual array defined, like displaying something a certain number of times:

onPress = () => {
    ...
};

renderButtons() {
    return initialArr.map((item) => {
        return (
            <Button 
                style={{ borderColor: item.color }}
                onPress={this.onPress}
            >
                {item.text}
            </Button>
        );
    });
}

...

render() {
    return (
        <View style={...}>
            {
                this.renderButtons()
            }
        </View>
    )
}

I moved the mapping to separate function outside of render method for more readable code. There are many other ways to loop through list of elements in react native, and which way you'll use depends on what do you need to do. Most of these ways are covered in this article about React JSX loops, and although it's using React examples, everything from it can be used in React Native. Please check it out if you're interested in this topic!

Also, not on the topic on the looping, but as you're already using the array syntax for defining the onPress function, there's no need to bind it again. This, again, applies only if the function is defined using this syntax within the component, as the arrow syntax auto binds the function.

How to get current CPU and RAM usage in Python?

To get a line-by-line memory and time analysis of your program, I suggest using memory_profiler and line_profiler.

Installation:

# Time profiler
$ pip install line_profiler
# Memory profiler
$ pip install memory_profiler
# Install the dependency for a faster analysis
$ pip install psutil

The common part is, you specify which function you want to analyse by using the respective decorators.

Example: I have several functions in my Python file main.py that I want to analyse. One of them is linearRegressionfit(). I need to use the decorator @profile that helps me profile the code with respect to both: Time & Memory.

Make the following changes to the function definition

@profile
def linearRegressionfit(Xt,Yt,Xts,Yts):
    lr=LinearRegression()
    model=lr.fit(Xt,Yt)
    predict=lr.predict(Xts)
    # More Code

For Time Profiling,

Run:

$ kernprof -l -v main.py

Output

Total time: 0.181071 s
File: main.py
Function: linearRegressionfit at line 35

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
    35                                           @profile
    36                                           def linearRegressionfit(Xt,Yt,Xts,Yts):
    37         1         52.0     52.0      0.1      lr=LinearRegression()
    38         1      28942.0  28942.0     75.2      model=lr.fit(Xt,Yt)
    39         1       1347.0   1347.0      3.5      predict=lr.predict(Xts)
    40                                           
    41         1       4924.0   4924.0     12.8      print("train Accuracy",lr.score(Xt,Yt))
    42         1       3242.0   3242.0      8.4      print("test Accuracy",lr.score(Xts,Yts))

For Memory Profiling,

Run:

$ python -m memory_profiler main.py

Output

Filename: main.py

Line #    Mem usage    Increment   Line Contents
================================================
    35  125.992 MiB  125.992 MiB   @profile
    36                             def linearRegressionfit(Xt,Yt,Xts,Yts):
    37  125.992 MiB    0.000 MiB       lr=LinearRegression()
    38  130.547 MiB    4.555 MiB       model=lr.fit(Xt,Yt)
    39  130.547 MiB    0.000 MiB       predict=lr.predict(Xts)
    40                             
    41  130.547 MiB    0.000 MiB       print("train Accuracy",lr.score(Xt,Yt))
    42  130.547 MiB    0.000 MiB       print("test Accuracy",lr.score(Xts,Yts))

Also, the memory profiler results can also be plotted using matplotlib using

$ mprof run main.py
$ mprof plot

enter image description here Note: Tested on

line_profiler version == 3.0.2

memory_profiler version == 0.57.0

psutil version == 5.7.0


EDIT: The results from the profilers can be parsed using the TAMPPA package. Using it, we can get line-by-line desired plots as plot

How to go back last page

You can implement routerOnActivate() method on your route class, it will provide information about previous route.

routerOnActivate(nextInstruction: ComponentInstruction, prevInstruction: ComponentInstruction) : any

Then you can use router.navigateByUrl() and pass data generated from ComponentInstruction. For example:

this._router.navigateByUrl(prevInstruction.urlPath);

How to check if image exists with given url?

To handle the lazy loading with image existence check I followed this in jQuery-

$('[data-src]').each(function() {
  var $image_place_holder_element = $(this);
  var image_url = $(this).data('src');
  $("<div class='hidden-classe' />").load(image_url, function(response, status, xhr) {
    if (!(status == "error")) {
      $image_place_holder_element.removeClass('image-placeholder');
      $image_place_holder_element.attr('src', image_url);
    }
  }).remove();
});

Reason: if I am using $image_place_holder_element.load() method it will be adding the response to the element, so random div and removing it appeared me a good solution. Hope it works for someone trying to implement lazy loading along with url check.

How to change status bar color to match app in Lollipop? [Android]

To set the status bar color, create a style.xml file under res/values-v21 folder with this content:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="AppBaseTheme" parent="AppTheme">
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:statusBarColor">@color/blue</item>
    </style>

</resources>

How to add background-image using ngStyle (angular2)?

import {BrowserModule, DomSanitizer} from '@angular/platform-browser'

  constructor(private sanitizer:DomSanitizer) {
    this.name = 'Angular!'
    this.backgroundImg = sanitizer.bypassSecurityTrustStyle('url(http://www.freephotos.se/images/photos_medium/white-flower-4.jpg)');
  }
<div [style.background-image]="backgroundImg"></div>

See also

HTML button opening link in new tab

Try this

window.open(urlValue, "_system", "location=yes");

afxwin.h file is missing in VC++ Express Edition

I encountered the same problem. The easiest thing is to install the free Visual Studio Community 2015 as answered in this question Is MFC only available with Visual Studio, and not Visual C++ Express?

Binding value to style

I managed to make it work with alpha28 like this:

import {Component, View} from 'angular2/angular2';

@Component({
  selector: 'circle', 
  properties: ['color: color'],
})
@View({
    template: `<style>
    .circle{
        width:50px;
        height: 50px;
        border-radius: 25px;
    }
</style>
<div class="circle" [style.background-color]="changeBackground()">
    <content></content>
</div>
`
})
export class Circle {
    color;

    constructor(){
    }

    changeBackground(): string {
        return this.color;
    }
}

and called it like this <circle color='yellow'></circle>

How to define partitioning of DataFrame?

So to start with some kind of answer : ) - You can't

I am not an expert, but as far as I understand DataFrames, they are not equal to rdd and DataFrame has no such thing as Partitioner.

Generally DataFrame's idea is to provide another level of abstraction that handles such problems itself. The queries on DataFrame are translated into logical plan that is further translated to operations on RDDs. The partitioning you suggested will probably be applied automatically or at least should be.

If you don't trust SparkSQL that it will provide some kind of optimal job, you can always transform DataFrame to RDD[Row] as suggested in of the comments.

HTML5 Canvas and Anti-aliasing

I haven't needed to turn on anti-alias because it's on by default but I have needed to turn it off. And if it can be turned off it can also be turned on.

ctx.imageSmoothingEnabled = true;

I usually shut it off when I'm working on my canvas rpg so when I zoom in the images don't look blurry.

How do I add more members to my ENUM-type column in MySQL?

Here is another way...

It adds "others" to the enum definition of the column "rtipo" of the table "firmas".

set @new_enum = 'others';
set @table_name = 'firmas';
set @column_name = 'rtipo';
select column_type into @tmp from information_schema.columns 
  where table_name = @table_name and column_name=@column_name;
set @tmp = insert(@tmp, instr(@tmp,')'), 0, concat(',\'', @new_enum, '\'') );
set @tmp = concat('alter table ', @table_name, ' modify ', @column_name, ' ', @tmp);
prepare stmt from @tmp;
execute stmt;
deallocate prepare stmt;

How to list all the roles existing in Oracle database?

all_roles.sql

SELECT SUBSTR(TRIM(rtp.role),1,12)          AS ROLE
     , SUBSTR(rp.grantee,1,16)              AS GRANTEE
     , SUBSTR(TRIM(rtp.privilege),1,12)     AS PRIVILEGE
     , SUBSTR(TRIM(rtp.owner),1,12)         AS OWNER
     , SUBSTR(TRIM(rtp.table_name),1,28)    AS TABLE_NAME
     , SUBSTR(TRIM(rtp.column_name),1,20)   AS COLUMN_NAME
     , SUBSTR(rtp.common,1,4)               AS COMMON
     , SUBSTR(rtp.grantable,1,4)            AS GRANTABLE
     , SUBSTR(rp.default_role,1,16)         AS DEFAULT_ROLE
     , SUBSTR(rp.admin_option,1,4)          AS ADMIN_OPTION
  FROM role_tab_privs rtp
  LEFT JOIN dba_role_privs rp
    ON (rtp.role = rp.granted_role)
 WHERE ('&1' IS NULL OR UPPER(rtp.role) LIKE UPPER('%&1%'))
   AND ('&2' IS NULL OR UPPER(rp.grantee) LIKE UPPER('%&2%'))
   AND ('&3' IS NULL OR UPPER(rtp.table_name) LIKE UPPER('%&3%'))
   AND ('&4' IS NULL OR UPPER(rtp.owner) LIKE UPPER('%&4%'))
 ORDER BY 1
        , 2
        , 3
        , 4
;

Usage

SQLPLUS> @all_roles '' '' '' '' '' ''
SQLPLUS> @all_roles 'somerol' '' '' '' '' ''
SQLPLUS> @all_roles 'roler' 'username' '' '' '' ''
SQLPLUS> @all_roles '' '' 'part-of-database-package-name' '' '' ''
etc.

Google Maps: Auto close open InfoWindows?

How about -

google.maps.event.addListener(yourMarker, 'mouseover', function () {
        yourInfoWindow.open(yourMap, yourMarker);

    });

google.maps.event.addListener(yourMarker, 'mouseout', function () {
        yourInfoWindow.open(yourMap, yourMarker);

    });

Then you can just hover over it and it will close itself.

Android Studio rendering problems

Just download minimum prefered SDK from SDK Manager, then build. Works for me.

Using CRON jobs to visit url?

You can also use the local commandline php-cli:

* * * * * php /local/root/path/to/tasks.php > /dev/null

It is faster and decrease load for your webserver.

How to use AND in IF Statement

Brief syntax lesson

Cells(Row, Column) identifies a cell. Row must be an integer between 1 and the maximum for version of Excel you are using. Column must be a identifier (for example: "A", "IV", "XFD") or a number (for example: 1, 256, 16384)

.Cells(Row, Column) identifies a cell within a sheet identified in a earlier With statement:

With ActiveSheet
  :
  .Cells(Row,Column)
  :
End With

If you omit the dot, Cells(Row,Column) is within the active worksheet. So wsh = ActiveWorkbook wsh.Range is not strictly necessary. However, I always use a With statement so I do not wonder which sheet I meant when I return to my code in six months time. So, I would write:

With ActiveSheet
  :
  .Range.  
  :
End With

Actually, I would not write the above unless I really did want the code to work on the active sheet. What if the user has the wrong sheet active when they started the macro. I would write:

With Sheets("xxxx")
  :
  .Range.  
  :
End With

because my code only works on sheet xxxx.

Cells(Row,Column) identifies a cell. Cells(Row,Column).xxxx identifies a property of the cell. Value is a property. Value is the default property so you can usually omit it and the compiler will know what you mean. But in certain situations the compiler can be confused so the advice to include the .Value is good.

Cells(Row,Column) like "*Miami*" will give True if the cell is "Miami", "South Miami", "Miami, North" or anything similar.

Cells(Row,Column).Value = "Miami" will give True if the cell is exactly equal to "Miami". "MIAMI" for example will give False. If you want to accept MIAMI, use the lower case function:

Lcase(Cells(Row,Column).Value) = "miami"  

My suggestions

Your sample code keeps changing as you try different suggestions which I find confusing. You were using Cells(Row,Column) <> "Miami" when I started typing this.

Use

If Cells(i, "A").Value like "*Miami*" And Cells(i, "D").Value like "*Florida*" Then
  Cells(i, "C").Value = "BA"

if you want to accept, for example, "South Miami" and "Miami, North".

Use

If Cells(i, "A").Value = "Miami" And Cells(i, "D").Value like "Florida" Then
  Cells(i, "C").Value = "BA"

if you want to accept, exactly, "Miami" and "Florida".

Use

If Lcase(Cells(i, "A").Value) = "miami" And _
   Lcase(Cells(i, "D").Value) = "florida" Then
  Cells(i, "C").Value = "BA"

if you don't care about case.

How to add title to seaborn boxplot

.set_title('') can be used to add title to Seaborn Plot

import seaborn as sb
sb.boxplot().set_title('Title')

How to convert a Map to List in Java?

// you can use this
List<Value> list = new ArrayList<Value>(map.values());

// or you may use 
List<Value> list = new ArrayList<Value>();
for (Map.Entry<String, String> entry : map.entrySet())
{
list.add(entry.getValue());    
}

Java random number with given length

Would that work for you?

public class Main {

public static void main(String[] args) {
    Random r = new Random(System.currentTimeMillis());
    System.out.println(r.nextInt(100000) * 0.000001);
}

}

result e.g. 0.019007

Python creating a dictionary of lists

You can use defaultdict:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> a = ['1', '2']
>>> for i in a:
...   for j in range(int(i), int(i) + 2):
...     d[j].append(i)
...
>>> d
defaultdict(<type 'list'>, {1: ['1'], 2: ['1', '2'], 3: ['2']})
>>> d.items()
[(1, ['1']), (2, ['1', '2']), (3, ['2'])]

Java Generics With a Class & an Interface - Together

Here's how you would do it in Kotlin

fun <T> myMethod(item: T) where T : ClassA, T : InterfaceB {
    //your code here
}

Automatically scroll down chat div

It's hard to tell without knowing the HTML code, but I'd assume your div doesn't have a height set and/or doesn't allow overflow (e.g. through CSS height: 200px; overflow: auto).

I've made a working sample on jsfiddle: http://jsfiddle.net/hu4zqq4x/

I created some dummy HTML markup inside a div that is a) overflowing and b) has a set height. Scrolling is done through calling the function

function getMessages(letter) {
    var div = $("#messages");
    div.scrollTop(div.prop('scrollHeight'));
}

, in this case once on 'documentReady'.

prop('scrollHeight') will access the value of the property on the first element in the set of matched elements.

how do I join two lists using linq or lambda expressions

The way to do this using the Extention Methods, instead of the linq query syntax would be like this:

var results = workOrders.Join(plans,
  wo => wo.WorkOrderNumber,
  p => p.WorkOrderNumber,
  (order,plan) => new {order.WorkOrderNumber, order.WorkDescription, plan.ScheduledDate}
);

JQuery find first parent element with specific class prefix

Use .closest() with a selector:

var $div = $('#divid').closest('div[class^="div-a"]');

Vue.js dynamic images not working

You can try the require function. like this:

<img :src="require(`@/xxx/${name}.png`)" alt class="icon" />

How to reset (clear) form through JavaScript?

Pure JS solution is as follows:

function clearForm(myFormElement) {

  var elements = myFormElement.elements;

  myFormElement.reset();

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

  field_type = elements[i].type.toLowerCase();

  switch(field_type) {

    case "text":
    case "password":
    case "textarea":
          case "hidden":

      elements[i].value = "";
      break;

    case "radio":
    case "checkbox":
        if (elements[i].checked) {
          elements[i].checked = false;
      }
      break;

    case "select-one":
    case "select-multi":
                elements[i].selectedIndex = -1;
      break;

    default:
      break;
  }
    }
}

Why does corrcoef return a matrix?

You can use the following function to return only the correlation coefficient:

def pearson_r(x, y):
"""Compute Pearson correlation coefficient between two arrays."""

   # Compute correlation matrix
   corr_mat = np.corrcoef(x, y)

   # Return entry [0,1]
   return corr_mat[0,1]

How do you properly use WideCharToMultiByte

You use the lpMultiByteStr [out] parameter by creating a new char array. You then pass this char array in to get it filled. You only need to initialize the length of the string + 1 so that you can have a null terminated string after the conversion.

Here are a couple of useful helper functions for you, they show the usage of all parameters.

#include <string>

std::string wstrtostr(const std::wstring &wstr)
{
    // Convert a Unicode string to an ASCII string
    std::string strTo;
    char *szTo = new char[wstr.length() + 1];
    szTo[wstr.size()] = '\0';
    WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);
    strTo = szTo;
    delete[] szTo;
    return strTo;
}

std::wstring strtowstr(const std::string &str)
{
    // Convert an ASCII string to a Unicode String
    std::wstring wstrTo;
    wchar_t *wszTo = new wchar_t[str.length() + 1];
    wszTo[str.size()] = L'\0';
    MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo, (int)str.length());
    wstrTo = wszTo;
    delete[] wszTo;
    return wstrTo;
}

--

Anytime in documentation when you see that it has a parameter which is a pointer to a type, and they tell you it is an out variable, you will want to create that type, and then pass in a pointer to it. The function will use that pointer to fill your variable.

So you can understand this better:

//pX is an out parameter, it fills your variable with 10.
void fillXWith10(int *pX)
{
  *pX = 10;
}

int main(int argc, char ** argv)
{
  int X;
  fillXWith10(&X);
  return 0;
}

Stop an input field in a form from being submitted

Add disabled="disabled" in input and while jquery remove the attribute disabled when you want to submit it using .removeAttr('disabled')

HTML:

<input type="hidden" name="test" value="test" disabled='disabled'/>

jquery:

$("input[name='test']").removeAttr('disabled');

Exception in thread "main" java.lang.Error: Unresolved compilation problems

Two possibilities here. Java Version incompatible or import

Explain the "setUp" and "tearDown" Python methods used in test cases

Suppose you have a suite with 10 tests. 8 of the tests share the same setup/teardown code. The other 2 don't.

setup and teardown give you a nice way to refactor those 8 tests. Now what do you do with the other 2 tests? You'd move them to another testcase/suite. So using setup and teardown also helps give a natural way to break the tests into cases/suites

Struct Constructor in C++?

struct HaveSome
{
   int fun;
   HaveSome()
   {
      fun = 69;
   }
};

I'd rather initialize inside the constructor so I don't need to keep the order.

C# - Create SQL Server table programmatically

Try this:

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection cn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");
    try
    {
        cn.Open();
        SqlCommand cmd = new SqlCommand("create table Employee (empno int,empname varchar(50),salary money);", cn);
        cmd.ExecuteNonQuery();
        lblAlert.Text = "SucessFully Connected";
        cn.Close();
    }
    catch (Exception eq)
    {
        lblAlert.Text = eq.ToString();
    }
}

PHP/MySQL: How to create a comment section in your website

Create a new table called comments

They should have a column containing the id of the post they are assigned to.

Make a form which adds a new comment to that table.

An example (not tested so may contain lil' syntax errors): I call a page with comments a post

Post.php

<!-- Post content here -->

<!-- Then cmments below -->
<h1>Comments</h1>
<?php
$result = mysql_query("SELECT * FROM comments WHERE postid=0");
//0 should be the current post's id
while($row = mysql_fetch_object($result))
{
?>
<div class="comment">
By: <?php echo $row->author; //Or similar in your table ?>
<p>
<?php echo;$row->body; ?>
</p>
</div>
<?php
}
?>
<h1>Leave a comment:</h1>
<form action="insertcomment.php" method="post">
<!-- Here the shit they must fill out -->
<input type="hidden" name="postid" value="<?php //your posts id ?>" />
<input type="submit" />
</form>

insertcomment.php

<?php
//First check if everything is filled in
if(/*some statements*/)
{
//Do a mysql_real_escape_string() to all fields

//Then insert comment
mysql_query("INSERT INTO comments VALUES ($author,$postid,$body,$etc)");
}
else
{
die("Fill out everything please. Mkay.");
}
?>

You must change the code a bit to make it work. I'n not doing your homework. Only a part of it ;)

How to load a jar file at runtime

I was asked to build a java system that will have the ability to load new code while running

You might want to base your system on OSGi (or at least take a lot at it), which was made for exactly this situation.

Messing with classloaders is really tricky business, mostly because of how class visibility works, and you do not want to run into hard-to-debug problems later on. For example, Class.forName(), which is widely used in many libraries does not work too well on a fragmented classloader space.

Normalizing images in OpenCV

If you want to change the range to [0, 1], make sure the output data type is float.

image = cv2.imread("lenacolor512.tiff", cv2.IMREAD_COLOR)  # uint8 image
norm_image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)

Why does Python code use len() function instead of a length method?

You can also say

>> x = 'test'
>> len(x)
4

Using Python 2.7.3.

How to convert a datetime to string in T-SQL

Try below :

DECLARE @myDateTime DATETIME
SET @myDateTime = '2013-02-02'

-- Convert to string now
SELECT LEFT(CONVERT(VARCHAR, @myDateTime, 120), 10)

Turn a simple socket into an SSL socket

Here my example ssl socket server threads (multiple connection) https://github.com/breakermind/CppLinux/blob/master/QtSslServerThreads/breakermindsslserver.cpp

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <iostream>

#include <breakermindsslserver.h>

using namespace std;

int main(int argc, char *argv[])
{
    BreakermindSslServer boom;
    boom.Start(123,"/home/user/c++/qt/BreakermindServer/certificate.crt", "/home/user/c++/qt/BreakermindServer/private.key");
    return 0;
}