Programs & Examples On #Exim4

Android - border for button

Step 1 : Create file named : my_button_bg.xml

Step 2 : Place this file in res/drawables.xml

Step 3 : Insert below code

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle">
  <gradient android:startColor="#FFFFFF" 
    android:endColor="#00FF00"
    android:angle="270" />
  <corners android:radius="3dp" />
  <stroke android:width="5px" android:color="#000000" />
</shape>

Step 4: Use code "android:background="@drawable/my_button_bg" where needed eg below:

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Your Text"
    android:background="@drawable/my_button_bg"
    />

Simplest way to form a union of two lists

The easiest way is to use LINQ's Union method:

var aUb = A.Union(B).ToList();

How to make padding:auto work in CSS?

You can reset the padding (and I think everything else) with initial to the default.

p {
    padding: initial;
}

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

For a new version of Swift try this

override var shouldAutorotate: Bool {
    return false
}

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return UIInterfaceOrientationMask.portrait
}

override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation {
    return UIInterfaceOrientation.portrait
}

What charset does Microsoft Excel use when saving files?

While it is true that exporting an excel file that contains special characters to csv can be a pain in the ass, there is however a simple work around: simply copy/paste the cells into a google docs and then save from there.

jQuery vs document.querySelectorAll

If you are optimizing your page for IE8 or newer, you should really consider whether you need jquery or not. Modern browsers have many assets natively which jquery provides.

If you care for performance, you can have incredible performance benefits (2-10 faster) using native javascript: http://jsperf.com/jquery-vs-native-selector-and-element-style/2

I transformed a div-tagcloud from jquery to native javascript (IE8+ compatible), the results are impressive. 4 times faster with just a little overhead.

                    Number of lines       Execution Time                       
Jquery version :        340                    155ms
Native version :        370                    27ms

You Might Not Need Jquery provides a really nice overview, which native methods replace for which browser version.

http://youmightnotneedjquery.com/


Appendix: Further speed comparisons how native methods compete to jquery

Taking the record with the max date

You could also use:

SELECT t.*
  FROM 
        TABLENAME t
    JOIN
        ( SELECT A, MAX(col_date) AS col_date
          FROM TABLENAME
          GROUP BY A
        ) m
      ON  m.A = t.A
      AND m.col_date = t.col_date

Error while inserting date - Incorrect date value:

You need to convert the date to YYYY-MM-DD in order to insert it as a MySQL date using the default configuration.

One way to do that is STR_TO_DATE():

insert into your_table (...)
values (...,str_to_date('07-25-2012','%m-%d-%Y'),...);

How does the stack work in assembly language?

The call stack is implemented by the x86 instruction set and the operating system.

Instructions like push and pop adjust the stack pointer while the operating system takes care of allocating memory as the stack grows for each thread.

The fact that the x86 stack "grows down" from higher to lower addresses make this architecture more susceptible to the buffer overflow attack.

Counting the number of elements in array

Best practice of getting length is use length filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}

But you can calculate count of elements in for loop. For example:

{% set count = 0 %}
{% for nc in notcount %}
    {% set count = count + 1 %}
{% endfor %}

{{ count }}

This solution helps if you want to calculate count of elements by condition, for example you have a property name inside object and you want to calculate count of objects with not empty names:

{% set countNotEmpty = 0 %}
{% for nc in notcount if nc.name %}
    {% set countNotEmpty = countNotEmpty + 1 %}
{% endfor %}

{{ countNotEmpty }}

Useful links:

How to send data in request body with a GET when using jQuery $.ajax()

we all know generally that for sending the data according to the http standards we generally use POST request. But if you really want to use Get for sending the data in your scenario I would suggest you to use the query-string or query-parameters.

1.GET use of Query string as. {{url}}admin/recordings/some_id

here the some_id is mendatory parameter to send and can be used and req.params.some_id at server side.

2.GET use of query string as{{url}}admin/recordings?durationExact=34&isFavourite=true

here the durationExact ,isFavourite is optional strings to send and can be used and req.query.durationExact and req.query.isFavourite at server side.

3.GET Sending arrays {{url}}admin/recordings/sessions/?os["Windows","Linux","Macintosh"]

and you can access those array values at server side like this

let osValues = JSON.parse(req.query.os);
        if(osValues.length > 0)
        {
            for (let i=0; i<osValues.length; i++)
            {
                console.log(osValues[i])
                //do whatever you want to do here
            }
        }

Delaying function in swift

You can use GCD (in the example with a 10 second delay):

Swift 2

let triggerTime = (Int64(NSEC_PER_SEC) * 10)
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in
    self.functionToCall()
})

Swift 3 and Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
    self.functionToCall()
})

Swift 5 or Later

 DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
        //call any function
    }

Don't understand why UnboundLocalError occurs (closure)

To answer the question in your subject line,* yes, there are closures in Python, except they only apply inside a function, and also (in Python 2.x) they are read-only; you can't re-bind the name to a different object (though if the object is mutable, you can modify its contents). In Python 3.x, you can use the nonlocal keyword to modify a closure variable.

def incrementer():
    counter = 0
    def increment():
        nonlocal counter
        counter += 1
        return counter
    return increment

increment = incrementer()

increment()   # 1
increment()   # 2

* The question origially asked about closures in Python.

Removing Spaces from a String in C?

#include <ctype>

char * remove_spaces(char * source, char * target)
{
     while(*source++ && *target)
     {
        if (!isspace(*source)) 
             *target++ = *source;
     }
     return target;
}

Notes;

  • This doesn't handle Unicode.

css overflow - only 1 line of text

if addition please, if you have a long text please you can use this css code bellow;

text-overflow: ellipsis;
overflow: visible;
white-space: nowrap;

make the whole line text visible.

Java check to see if a variable has been initialized

Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.

Now if you know that once assigned, the value will never reassigned a value of null, you can use:

if (box != null) {
    box.removeFromCanvas();
}

(and that also avoids a possible NullPointerException) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:

if (box != null) {
    box.removeFromCanvas();
    // Forget about the box - we don't want to try to remove it again
    box = null;
}

The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):

// Won't compile
String x;
System.out.println(x);

// Will compile, prints null
String y = null;
System.out.println(y);

What is the best or most commonly used JMX Console / Client

I would prefer using JConsole for application monitoring, and it does have graphical view. If you’re using JDK 5.0 or above then it’s the best. Please refer to this using jconsole page for more details.

I have been primarily using it for GC tuning and finding bottlenecks.

html 5 audio tag width

Set it the same way you'd set the width of any other HTML element, with CSS:

audio { width: 200px; }

Note that audio is an inline element by default in Firefox, so you might also want to set it to display: block. Here's an example.

How to Initialize char array from a string

Simply

const char S[] = "ABCD";

should work.

What's your compiler?

WPF chart controls

Visifire supports wide range of 2D and 3D charts with zooming and panning functionality.

Visifire Line chart with zooming

Full Disclosure: I have been involved in the development of Visifire.

Maven: How to change path to target directory from command line?

You should use profiles.

<profiles>
    <profile>
        <id>otherOutputDir</id>
        <build>
            <directory>yourDirectory</directory>
        </build>
    </profile>
</profiles>

And start maven with your profile

mvn compile -PotherOutputDir

If you really want to define your directory from the command line you could do something like this (NOT recommended at all) :

<properties>
    <buildDirectory>${project.basedir}/target</buildDirectory>
</properties>

<build>
    <directory>${buildDirectory}</directory>
</build>

And compile like this :

mvn compile -DbuildDirectory=test

That's because you can't change the target directory by using -Dproject.build.directory

Setting transparent images background in IrfanView

If you are using the batch conversion, in the window click "options" in the "Batch conversion settings-output format" and tick the two boxes "save transparent color" (one under "PNG" and the other under "ICO").

NSCameraUsageDescription in iOS 10.0 runtime crash?

the xcode UI has changed a bit from one version to the next so here is where you update the plist for 9.0 beta 4 if it helps Project ->Target ->Infoenter image description here

Javascript: set label text

For a dynamic approach, if your labels are always in front of your text areas:

$(object).prev("label").text(charsleft);

Using regular expression in css?

You can' just add a class to each of your DIVs and apply the rule to the class in this way:

HTML:

<div class="myclass" id="s1">...</div>
<div class="myclass" id="s2">...</div>

CSS:

//css
.myclass
{
   ...
}

How do I raise an exception in Rails so it behaves like other Rails exceptions?

You can do it like this:

class UsersController < ApplicationController
  ## Exception Handling
  class NotActivated < StandardError
  end

  rescue_from NotActivated, :with => :not_activated

  def not_activated(exception)
    flash[:notice] = "This user is not activated."
    Event.new_event "Exception: #{exception.message}", current_user, request.remote_ip
    redirect_to "/"
  end

  def show
      // Do something that fails..
      raise NotActivated unless @user.is_activated?
  end
end

What you're doing here is creating a class "NotActivated" that will serve as Exception. Using raise, you can throw "NotActivated" as an Exception. rescue_from is the way of catching an Exception with a specified method (not_activated in this case). Quite a long example, but it should show you how it works.

Best wishes,
Fabian

Sockets - How to find out what port and address I'm assigned

If it's a server socket, you should call listen() on your socket, and then getsockname() to find the port number on which it is listening:

struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(sock, (struct sockaddr *)&sin, &len) == -1)
    perror("getsockname");
else
    printf("port number %d\n", ntohs(sin.sin_port));

As for the IP address, if you use INADDR_ANY then the server socket can accept connections to any of the machine's IP addresses and the server socket itself does not have a specific IP address. For example if your machine has two IP addresses then you might get two incoming connections on this server socket, each with a different local IP address. You can use getsockname() on the socket for a specific connection (which you get from accept()) in order to find out which local IP address is being used on that connection.

How to set data attributes in HTML elements

Vanilla Javascript solution

HTML

<div id="mydiv" data-myval="10"></div>

JavaScript:

  • Using DOM's getAttribute() property

     var brand = mydiv.getAttribute("data-myval")//returns "10"
     mydiv.setAttribute("data-myval", "20")      //changes "data-myval" to "20"
     mydiv.removeAttribute("data-myval")         //removes "data-myval" attribute entirely
    
  • Using JavaScript's dataset property

    var myval = mydiv.dataset.myval     //returns "10"
    mydiv.dataset.myval = '20'          //changes "data-myval" to "20"
    mydiv.dataset.myval = null          //removes "data-myval" attribute
    

ImportError: No module named mysql.connector using Python2

If you have this error on PYCHARM: ImportError: No module named mysql.connector

Try this solution: Open Pycharm go to File->Settings-> Project->Python Interpreter inside Pycharm, Then press + icon to install mysql-connector. Problem solved!

How to update SQLAlchemy row entry?

I wrote telegram bot, and have some problem with update rows. Use this example, if you have Model

def update_state(chat_id, state):
    try:
        value = Users.query.filter(Users.chat_id == str(chat_id)).first()
        value.state = str(state)
        db.session.flush()
        db.session.commit()
        #db.session.close()
    except:
        print('Error in def update_state')

Why use db.session.flush()? That's why >>> SQLAlchemy: What's the difference between flush() and commit()?

SHA512 vs. Blowfish and Bcrypt

I would recommend Ulrich Drepper's SHA-256/SHA-512 based crypt implementation.

We ported these algorithms to Java, and you can find a freely licensed version of them at ftp://ftp.arlut.utexas.edu/java_hashes/.

Note that most modern (L)Unices support Drepper's algorithm in their /etc/shadow files.

How to use sed to extract substring

You should not parse XML using tools like sed, or awk. It's error-prone.

If input changes, and before name parameter you will get new-line character instead of space it will fail some day producing unexpected results.

If you are really sure, that your input will be always formated this way, you can use cut. It's faster than sed and awk:

cut -d'"' -f2 < input.txt

It will be better to first parse it, and extract only parameter name attribute:

xpath -q -e //@name input.txt | cut -d'"' -f2

To learn more about xpath, see this tutorial: http://www.w3schools.com/xpath/

The VMware Authorization Service is not running

type Services at search, then start Services

enter image description here

then start all VM services

enter image description here

foreach with index

My solution involves a simple Pair class I created for general utility, and which is operationally essentially the same as the framework class KeyValuePair. Then I created a couple extension functions for IEnumerable called Ordinate (from the set theory term "ordinal").

These functions will return for each item a Pair object containing the index, and the item itself.

public static IEnumerable<Pair<Int32, X>> Ordinate<X>(this IEnumerable<X> lhs)
{
    return lhs.Ordinate(0);
}

public static IEnumerable<Pair<Int32, X>> Ordinate<X>(this IEnumerable<X> lhs, Int32 initial)
{
    Int32 index = initial - 1;

    return lhs.Select(x => new Pair<Int32, X>(++index, x));
}

How to group an array of objects by key

Building on the answer by @Jonas_Wilms if you do not want to type in all your fields:

    var result = {};

    for ( let { first_field, ...fields } of your_data ) 
    { 
       result[first_field] = result[first_field] || [];
       result[first_field].push({ ...fields }); 
    }

I didn't make any benchmark but I believe using a for loop would be more efficient than anything suggested in this answer as well.

NewtonSoft.Json Serialize and Deserialize class with property of type IEnumerable<ISomeInterface>

Considering that in most cases you don't want your entire data contract to have types supplied, but only those which are containing an abstract or interface, or list thereof; and also considering these instances are very rare and easily identifiable within your data entities, the easiest and least verbose way is to use

[JsonProperty(ItemTypeNameHandling = TypeNameHandling.Objects)]
public IEnumerable<ISomeInterface> Items { get; set; }

as attribute on your property containing the enumerable/list/collection. This will target only that list, and only append type information for the contained objects, like this:

{
  "Items": [
    {
      "$type": "Namespace.ClassA, Assembly",
      "Property": "Value"
    },
    {
      "$type": "Namespace.ClassB, Assembly",
      "Property": "Value",
      "Additional_ClassB_Property": 3
    }
  ]
}

Clean, simple, and located where the complexity of your data model is introduced, instead of hidden away in some converter.

Session 'app': Error Installing APK

Nothing above helped me. The fingerprint dialog did not appear. I checked another android device and the dialog appeared and debug was possible. So the problem was on device side not on computer side I made reset "to factory settings" on device and this helped me.

matching query does not exist Error in Django

You may try this way. just use a function to get your object

def get_object(self, id):
    try:
        return UniversityDetails.objects.get(email__exact=email)
    except UniversityDetails.DoesNotExist:
        return False

Regular Expression to get a string between parentheses in Javascript

var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/;
alert(rex.exec(str));

Will match the first number starting with a $ and followed by ')'. ')' will not be part of the match. The code alerts with the first match.

var str = "I expect five hundred dollars ($500) ($1).";
var rex = /\$\d+(?=\))/g;
var matches = str.match(rex);
for (var i = 0; i < matches.length; i++)
{
    alert(matches[i]);
}

This code alerts with all the matches.

References:

search for "?=n" http://www.w3schools.com/jsref/jsref_obj_regexp.asp

search for "x(?=y)" https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Vbscript list all PDF files in folder and subfolders

(For those who stumble upon this from your search engine of choice)

This just recursively traces down the folder, so you don't need to duplicate your code twice. Also the OPs logic is needlessly complex.

Wscript.Echo "begin."
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objSuperFolder = objFSO.GetFolder(WScript.Arguments(0))
Call ShowSubfolders (objSuperFolder)

Wscript.Echo "end."

WScript.Quit 0

Sub ShowSubFolders(fFolder)
    Set objFolder = objFSO.GetFolder(fFolder.Path)
    Set colFiles = objFolder.Files
    For Each objFile in colFiles
        If UCase(objFSO.GetExtensionName(objFile.name)) = "PDF" Then
            Wscript.Echo objFile.Name
        End If
    Next

    For Each Subfolder in fFolder.SubFolders
        ShowSubFolders(Subfolder)
    Next
End Sub

JavaScript: Check if mouse button down?

Using the MouseEvent api, to check the pressed button, if any:

_x000D_
_x000D_
document.addEventListener('mousedown', (e) => console.log(e.buttons))
_x000D_
_x000D_
_x000D_

Return:

A number representing one or more buttons. For more than one button pressed simultaneously, the values are combined (e.g., 3 is primary + secondary).

0 : No button or un-initialized
1 : Primary button (usually the left button)
2 : Secondary button (usually the right button)
4 : Auxilary button (usually the mouse wheel button or middle button)
8 : 4th button (typically the "Browser Back" button)
16 : 5th button (typically the "Browser Forward" button)

Text that shows an underline on hover

Fairly simple process I am using SCSS obviously but you don't have to as it's just CSS in the end!

HTML

<span class="menu">Menu</span>

SCSS

.menu {
    position: relative;
    text-decoration: none;
    font-weight: 400;
    color: blue;
    transition: all .35s ease;

    &::before {
        content: "";
        position: absolute;
        width: 100%;
        height: 2px;
        bottom: 0;
        left: 0;
        background-color: yellow;
        visibility: hidden;
        -webkit-transform: scaleX(0);
        transform: scaleX(0);
        -webkit-transition: all 0.3s ease-in-out 0s;
        transition: all 0.3s ease-in-out 0s;
    }

    &:hover {
        color: yellow;

        &::before {
            visibility: visible;
            -webkit-transform: scaleX(1);
            transform: scaleX(1);
        }
    }
}

Flask at first run: Do not use the development server in a production environment

If for some people (like me earlier) the above answers don't work, I think the following answer would work (for Mac users I think) Enter the following commands to do flask run

$ export FLASK_APP = hello.py
$ export FLASK_ENV = development
$ flask run

Alternatively you can do the following (I haven't tried this but one resource online talks about it)

$ export FLASK_APP = hello.py
$ python -m flask run

source: For more

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

add async defer at the begining of map api key call.

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

If you want to make a change global to the whole notebook:

import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams["figure.figsize"] = [10, 5]

Appending a line to a file only if it does not already exist

Just keep it simple :)

grep + echo should suffice:

grep -qxF 'include "/configs/projectname.conf"' foo.bar || echo 'include "/configs/projectname.conf"' >> foo.bar

Edit: incorporated @cerin and @thijs-wouters suggestions.

Response.Redirect to new window

I did this by putting target="_blank" in the linkbutton

<asp:LinkButton ID="btn" runat="server" CausesValidation="false"  Text="Print" Visible="false" target="_blank"  />

then in the codebehind pageload just set the href attribute:

btn.Attributes("href") = String.Format(ResolveUrl("~/") + "test/TestForm.aspx?formId={0}", formId)

How do I get the Git commit count?

git config --global alias.count 'rev-list --all --count'

If you add this to your config, you can just reference the command;

git count

get launchable activity name of package from adb

You can also use ddms for logcat logs where just giving search of the app name you will all info but you have to select Info instead of verbose or other options. check this below image.

enter image description here

Converting Symbols, Accent Letters to English Alphabet

The original request has been answered already.

However, I am posting the below answer for those who might be looking for generic transliteration code to transliterate any charset to Latin/English in Java.

Naive meaning of tranliteration: Translated string in it's final form/target charset sounds like the string in it's original form. If we want to transliterate any charset to Latin(English alphabets), then ICU4(ICU4J library in java ) will do the job.

Here is the code snippet in java:

    import com.ibm.icu.text.Transliterator; //ICU4J library import

    public static String TRANSLITERATE_ID = "NFD; Any-Latin; NFC";
    public static String NORMALIZE_ID = "NFD; [:Nonspacing Mark:] Remove; NFC";

    /**
    * Returns the transliterated string to convert any charset to latin.
    */
    public static String transliterate(String input) {
        Transliterator transliterator = Transliterator.getInstance(TRANSLITERATE_ID + "; " + NORMALIZE_ID);
        String result = transliterator.transliterate(input);
        return result;
    }

Bootstrap 3 Multi-column within a single ul not floating properly

you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]

http://www.bootply.com/118886

css

.even{background: red; color:white;}
.odd{background: darkred; color:white;}

html

<div class="container">
  <ul class="list-unstyled">
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
  </ul>
</div>

How can I make a float top with CSS?

<div class="block blockLeft">...</div>
<div class="block blockRight">...</div>
<div class="block blockLeft">...</div>
<div class="block blockRight">...</div>
<div class="block blockLeft">...</div>
<div class="block blockRight">...</div>

block {width:300px;}
blockLeft {float:left;}
blockRight {float:right;}

But if the number of div's elements is not fixed or you don't know how much it could be, you still need JS. use jQuery :even, :odd

Changing the cursor in WPF sometimes works, sometimes doesn't

Do you need the cursor to be a "wait" cursor only when it's over that particular page/usercontrol? If not, I'd suggest using Mouse.OverrideCursor:

Mouse.OverrideCursor = Cursors.Wait;
try
{
    // do stuff
}
finally
{
    Mouse.OverrideCursor = null;
}

This overrides the cursor for your application rather than just for a part of its UI, so the problem you're describing goes away.

SQL Server - INNER JOIN WITH DISTINCT

add "distinct" after "select".

select distinct a.FirstName, a.LastName, v.District , v.LastName
from AddTbl a 
inner join ValTbl v  where a.LastName = v.LastName  order by Firstname

Determine the data types of a data frame's columns

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

library(purrr)
map(df,class)

How to split a file into equal parts, without breaking individual lines?

The script isn't even necessary, split(1) supports the wanted feature out of the box:
split -l 75 auth.log auth.log. The above command splits the file in chunks of 75 lines a piece, and outputs file on the form: auth.log.aa, auth.log.ab, ...

wc -l on the original file and output gives:

  321 auth.log
   75 auth.log.aa
   75 auth.log.ab
   75 auth.log.ac
   75 auth.log.ad
   21 auth.log.ae
  642 total

How do I properly set the permgen size?

So you are doing the right thing concerning "-XX:MaxPermSize=512m": it is indeed the correct syntax. You could try to set these options directly to the Catalyna server files so they are used on server start.

Maybe this post will help you!

How to make sure that Tomcat6 reads CATALINA_OPTS on Windows?

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

They have set the header to SAMEORIGIN in this case, which means that they have disallowed loading of the resource in an iframe outside of their domain. So this iframe is not able to display cross domain

enter image description here

For this purpose you need to match the location in your apache or any other service you are using

If you are using apache then in httpd.conf file.

  <LocationMatch "/your_relative_path">
      ProxyPass absolute_path_of_your_application/your_relative_path
      ProxyPassReverse absolute_path_of_your_application/your_relative_path
   </LocationMatch>

Accessing SQL Database in Excel-VBA

Is that a proper connection string?
Where is the SQL Server instance located?

You will need to verify that you are able to conenct to SQL Server using the connection string, you specified above.

EDIT: Look at the State property of the recordset to see if it is Open?
Also, change the CursorLocation property to adUseClient before opening the recordset.

Changing a specific column name in pandas DataFrame

Following short code can help:

df3 = df3.rename(columns={c: c.replace(' ', '') for c in df3.columns})

Remove spaces from columns.

Get last n lines of a file, similar to tail

There is very useful module that can do this:

from file_read_backwards import FileReadBackwards

with FileReadBackwards("/tmp/file", encoding="utf-8") as frb:

# getting lines by lines starting from the last line up
for l in frb:
    print(l)

Difference Between ViewResult() and ActionResult()

In Controller i have specified the below code with ActionResult which is a base class that can have 11 subtypes in MVC like: ViewResult, PartialViewResult, EmptyResult, RedirectResult, RedirectToRouteResult, JsonResult, JavaScriptResult, ContentResult, FileContentResult, FileStreamResult, FilePathResult.

    public ActionResult Index()
                {
                    if (HttpContext.Session["LoggedInUser"] == null)
                    {
                        return RedirectToAction("Login", "Home");
                    }

                    else
                    {
                        return View(); // returns ViewResult
                    }

                }
//More Examples

    [HttpPost]
    public ActionResult Index(string Name)
    {
     ViewBag.Message = "Hello";
     return Redirect("Account/Login"); //returns RedirectResult
    }

    [HttpPost]
    public ActionResult Index(string Name)
    {
    return RedirectToRoute("RouteName"); // returns RedirectToRouteResult
    }

Likewise we can return all these 11 subtypes by using ActionResult() without specifying every subtype method explicitly. ActionResult is the best thing if you are returning different types of views.

Why can't I use the 'await' operator within the body of a lock statement?

Basically it would be the wrong thing to do.

There are two ways this could be implemented:

  • Keep hold of the lock, only releasing it at the end of the block.
    This is a really bad idea as you don't know how long the asynchronous operation is going to take. You should only hold locks for minimal amounts of time. It's also potentially impossible, as a thread owns a lock, not a method - and you may not even execute the rest of the asynchronous method on the same thread (depending on the task scheduler).

  • Release the lock in the await, and reacquire it when the await returns
    This violates the principle of least astonishment IMO, where the asynchronous method should behave as closely as possible like the equivalent synchronous code - unless you use Monitor.Wait in a lock block, you expect to own the lock for the duration of the block.

So basically there are two competing requirements here - you shouldn't be trying to do the first here, and if you want to take the second approach you can make the code much clearer by having two separated lock blocks separated by the await expression:

// Now it's clear where the locks will be acquired and released
lock (foo)
{
}
var result = await something;
lock (foo)
{
}

So by prohibiting you from awaiting in the lock block itself, the language is forcing you to think about what you really want to do, and making that choice clearer in the code that you write.

How to replace all occurrences of a string in Javascript?

There is now a finished proposal for integrating String.prototype.replaceAll into the official specification. Eventually, developers will not have to come up with their own implementations for replaceAll - instead, modern Javascript engines will support it natively.

The proposal is at stage 4, which means that everything is complete, and all that's left is for browsers to start implementing it.

It has shipped in the latest versions of Chrome, Firefox, and Safari.

Here are the implementation details:

Per the current TC39 consensus, String.prototype.replaceAll behaves identically to String.prototype.replace in all cases, except for the following two cases:

  1. If searchValue is a string, String.prototype.replace only replaces a single occurrence of the searchValue, whereas String.prototype.replaceAll replaces all occurrences of the searchValue (as if .split(searchValue).join(replaceValue) or a global & properly-escaped regular expression had been used).
  2. If searchValue is a non-global regular expression, String.prototype.replace replaces a single match, whereas String.prototype.replaceAll throws an exception. This is done to avoid the inherent confusion between the lack of a global flag (which implies "do NOT replace all") and the name of the method being called (which strongly suggests "replace all").

Notably, String.prototype.replaceAll behaves just like String.prototype.replace if searchValue is a global regular expression.

You can see a spec-compliant polyfill here.

In supported environments, the following snippet will log foo-bar-baz, without throwing an error:

_x000D_
_x000D_
const str = 'foo bar baz';
console.log(
  str.replaceAll(' ', '-')
);
_x000D_
_x000D_
_x000D_

Read file from aws s3 bucket using node fs

here is the example which i used to retrive and parse json data from s3.

    var params = {Bucket: BUCKET_NAME, Key: KEY_NAME};
    new AWS.S3().getObject(params, function(err, json_data)
    {
      if (!err) {
        var json = JSON.parse(new Buffer(json_data.Body).toString("utf8"));

       // PROCESS JSON DATA
           ......
     }
   });

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

I had the same problem, and my solving was to replace :

return redirect(url_for('index'))

with

return render_template('indexo.html',data=Todos.query.all())

in my POST and DELETE route.

Default Activity not found in Android Studio

In my case, it worked when I removed the .idea folder from the project (Project/.ida) and re-opened Android Studio again.

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

Create a new "Empty Project" , Add your Cpp file to the new project, delete the line that includes stdafx.

Done.

The project no longer needs the stdafx. It is added automatically when you create projects with installed templates. enter image description here

Print empty line?

Python's print function adds a newline character to its input. If you give it no input it will just print a newline character

print()

Will print an empty line. If you want to have an extra line after some text you're printing, you can a newline to your text

my_str = "hello world"
print(my_str + "\n")

If you're doing this a lot, you can also tell print to add 2 newlines instead of just one by changing the end= parameter (by default end="\n")

print("hello world", end="\n\n")

But you probably don't need this last method, the two before are much clearer.

How to send a html email with the bash command "sendmail"?

Found solution in http://senthilkl.blogspot.lu/2012/11/how-to-send-html-emails-using-sendemail.html

sendEmail -f "oracle@server" -t "[email protected]" -u "Alert: Backup complete" -o message-content-type=html -o message-file=$LOG_FILE  -a $LOG_FILE_ATTACH 

What is let-* in Angular 2 templates?

The Angular microsyntax lets you configure a directive in a compact, friendly string. The microsyntax parser translates that string into attributes on the <ng-template>. The let keyword declares a template input variable that you reference within the template.

Can I get the name of the currently running function in JavaScript?

Another use case could be an event dispatcher bound at runtime:

MyClass = function () {
  this.events = {};

  // Fire up an event (most probably from inside an instance method)
  this.OnFirstRun();

  // Fire up other event (most probably from inside an instance method)
  this.OnLastRun();

}

MyClass.prototype.dispatchEvents = function () {
  var EventStack=this.events[GetFunctionName()], i=EventStack.length-1;

  do EventStack[i]();
  while (i--);
}

MyClass.prototype.setEvent = function (event, callback) {
  this.events[event] = [];
  this.events[event].push(callback);
  this["On"+event] = this.dispatchEvents;
}

MyObject = new MyClass();
MyObject.setEvent ("FirstRun", somecallback);
MyObject.setEvent ("FirstRun", someothercallback);
MyObject.setEvent ("LastRun", yetanothercallback);

The advantage here is the dispatcher can be easily reused and doesn't have to receive the dispatch queue as an argument, instead it comes implicit with the invocation name...

In the end, the general case presented here would be "using the function name as an argument so you don't have to pass it explicitly", and that could be useful in many cases, such as the jquery animate() optional callback, or in timeouts/intervals callbacks, (ie you only pass a funcion NAME).

Vue component event after render

updated might be what you're looking for. https://vuejs.org/v2/api/#updated

Failed to read artifact descriptor for org.apache.maven.plugins:maven-source-plugin:jar:2.4

On my side it was coming from an error in my settings.xml file. I had a bad tag. Just removed it, refreshed and i was good to go.

VBA using ubound on a multidimensional array

You need to deal with the optional Rank parameter of UBound.

Dim arr(1 To 4, 1 To 3) As Variant
Debug.Print UBound(arr, 1)  '? returns 4
Debug.Print UBound(arr, 2)  '? returns 3

More at: UBound Function (Visual Basic)

How do I use sudo to redirect output to a location I don't have permission to write to?

A trick I figured out myself was

sudo ls -hal /root/ | sudo dd of=/root/test.out

Server cannot set status after HTTP headers have been sent IIS7.5

The HTTP server doesn't send the response header back to the client until you either specify an error or else you start sending data. If you start sending data back to the client, then the server has to send the response head (which contains the status code) first. Once the header has been sent, you can no longer put a status code in the header, obviously.

Here's the usual problem. You start up the page, and send some initial tags (i.e. <head>). The server then sends those tags to the client, after first sending the HTTP response header with an assumed SUCCESS status. Now you start working on the meat of the page and discover a problem. You can not send an error at this point because the response header, which would contain the error status, has already been sent.

The solution is this: Before you generate any content at all, check if there are going to be any errors. Only then, when you have assured that there will be no problems, can you then start sending content, like the tag.

In your case, it seems like you have a login page that processes a POST request from a form. You probably throw out some initial HTML, then check if the username and password are valid. Instead, you should authenticate the user/password first, before you generate any HTML at all.

Android - Pulling SQlite database android device

For debuggable apps1 on non-rooted devices, you could use following command:

adb shell run-as package.name chmod 666 /data/data/package.name/databases/file
adb pull /data/data/package.name/databases/file

Example:

adb shell run-as com.app chmod 666 /data/data/com.app/databases/data.db
adb pull /data/data/com.app/databases/data.db

Set PATH adb for Enviroment Variables or use cd command to android sdk folder platform-tools.

Example:

cd /folder/android-sdk/platform-tools/

then use above command


1 Note that most apps in Play store are not debuggable since it requires setting the debuggable flag in the manifest.

What is 'PermSize' in Java?

This blog post gives a nice explanation and some background. Basically, the "permanent generation" (whose size is given by PermSize) is used to store things that the JVM has to allocate space for, but which will not (normally) be garbage-collected (hence "permanent") (+). That means for example loaded classes and static fields.

There is also a FAQ on garbage collection directly from Sun, which answers some questions about the permanent generation. Finally, here's a blog post with a lot of technical detail.

(+) Actually parts of the permanent generation will be GCed, e.g. class objects will be removed when a class is unloaded. But that was uncommon when the permanent generation was introduced into the JVM, hence the name.

Fundamental difference between Hashing and Encryption algorithms

A Hash function turns a variable-sized amount of text into a fixed-sized text.

Hash

Source: https://en.wikipedia.org/wiki/Hash_function


Hash functions in PHP

A hash turns a string to a hashed string. See below.

HASH:

$str = 'My age is 29';
$hash = hash('sha1', $str);
echo $hash; // OUTPUT: 4d675d9fbefc74a38c89e005f9d776c75d92623e

Passwords are usually stored in their hashed representation instead as readable text. When an end-user wants gain access to an application protected with a password then a password must be given during authentication. When the user submits his password, then the valid authentication system receives the password and hashes this given password. This password hash is compared to the hash known by the system. Access is granted in case of equality.

DEHASH:

SHA1 is a one-way hash. Which means that you can't dehash the hash.

However, you can brute-force the hash. Please see: https://hashkiller.co.uk/sha1-decrypter.aspx.

MD5, is another hash. A MD5 dehasher can be found on this website: https://www.md5online.org/.

To hamper brute-force attacks on hashes a salt can be given. In php you can use password_hash() for creating a password hash. The function password_hash() automatically creates a salt. To verify a password on a password hash (with a salt) use password_verify().

// Invoke this little script 3 times, and it will give you everytime a new hash
$password = '1234';  
$hash = password_hash($password, PASSWORD_DEFAULT);  

echo $hash; 
// OUTPUT 

$2y$10$ADxKiJW/Jn2DZNwpigWZ1ePwQ4il7V0ZB4iPeKj11n.iaDtLrC8bu 

$2y$10$H8jRnHDOMsHFMEZdT4Mk4uI4DCW7/YRKjfdcmV3MiA/WdzEvou71u 

$2y$10$qhyfIT25jpR63vCGvRbEoewACQZXQJ5glttlb01DmR4ota4L25jaW

One password can be represented by more then one hash. When you verify the password with different password hashes by using password_verify(), then the password will be accepted as a valid password.

$password = '1234';  

$hash = '$2y$10$ADxKiJW/Jn2DZNwpigWZ1ePwQ4il7V0ZB4iPeKj11n.iaDtLrC8bu';  
var_dump( password_verify($password, $hash) );  

$hash = '$2y$10$H8jRnHDOMsHFMEZdT4Mk4uI4DCW7/YRKjfdcmV3MiA/WdzEvou71u';  
var_dump( password_verify($password, $hash) );  

$hash = '$2y$10$qhyfIT25jpR63vCGvRbEoewACQZXQJ5glttlb01DmR4ota4L25jaW';  
var_dump( password_verify($password, $hash) );

// OUTPUT 

boolean true 

boolean true 

boolean true




An Encryption function transforms a text into a nonsensical ciphertext by using an encryption key, and vice versa. enter image description here

Source: https://en.wikipedia.org/wiki/Encryption


Encryption in PHP

Let's dive into some PHP code that handles encryption.

--- The Mcrypt extention ---

ENCRYPT:

$cipher = MCRYPT_RIJNDAEL_128;
$key = 'A_KEY';
$data = 'My age is 29';
$mode = MCRYPT_MODE_ECB;

$encryptedData = mcrypt_encrypt($cipher, $key , $data , $mode);
var_dump($encryptedData);

//OUTPUT:
string '„Ùòyªq³¿ì¼üÀpå' (length=16)

DECRYPT:

$decryptedData = mcrypt_decrypt($cipher, $key , $encryptedData, $mode);
$decryptedData = rtrim($decryptedData, "\0\4"); // Remove the nulls and EOTs at the END
var_dump($decryptedData);

//OUTPUT:
string 'My age is 29' (length=12)

--- The OpenSSL extention ---

The Mcrypt extention was deprecated in 7.1. and removed in php 7.2. The OpenSSL extention should be used in php 7. See the code snippets below:

$key = 'A_KEY';
$data = 'My age is 29';

// ENCRYPT
$encryptedData = openssl_encrypt($data , 'AES-128-CBC', $key, 0, 'IV_init_vector01');
var_dump($encryptedData);

// DECRYPT    
$decryptedData = openssl_decrypt($encryptedData, 'AES-128-CBC', $key, 0, 'IV_init_vector01');
var_dump($decryptedData);

//OUTPUT
string '4RJ8+18YkEd7Xk+tAMLz5Q==' (length=24)
string 'My age is 29' (length=12)

How to Reload ReCaptcha using JavaScript?

Try this

<script type="text/javascript" src="//www.google.com/recaptcha/api/js/recaptcha_ajax.js"></script>
<script type="text/javascript">
          function showRecaptcha() {
            Recaptcha.create("YOURPUBLICKEY", 'captchadiv', {
              theme: 'red',
              callback: Recaptcha.focus_response_field
            });
          }
 </script>

<div id="captchadiv"></div>

If you calll showRecaptcha the captchadiv will be populated with a new recaptcha instance.

How do I parse command line arguments in Bash?

I wanna submit my project : https://github.com/flyingangel/argparser

source argparser.sh
parse_args "$@"

Simple as that. The environment will be populated with variables with the same name as the arguments

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

For those who have a CREATE DATABASE script (as was my case) for the database that is causing this issue you can use the following CREATE script to match the collation:

-- Create Case Sensitive Database
CREATE DATABASE CaseSensitiveDatabase
COLLATE SQL_Latin1_General_CP1_CS_AS -- or any collation you require
GO
USE CaseSensitiveDatabase
GO
SELECT *
FROM sys.types
GO
--rest of your script here

or

-- Create Case In-Sensitive Database
CREATE DATABASE CaseInSensitiveDatabase
COLLATE SQL_Latin1_General_CP1_CI_AS -- or any collation you require
GO
USE CaseInSensitiveDatabase
GO
SELECT *
FROM sys.types
GO
--rest of your script here

This applies the desired collation to all the tables, which was just what I needed. It is ideal to try and keep the collation the same for all databases on a server. Hope this helps.

More info on the following link: SQL SERVER – Creating Database with Different Collation on Server

How do I diff the same file between two different commits on the same branch?

If you have configured the "difftool" you can use

git difftool revision_1:file_1 revision_2:file_2

Example: Comparing a file from its last commit to its previous commit on the same branch: Assuming that if you are in your project root folder

$git difftool HEAD:src/main/java/com.xyz.test/MyApp.java HEAD^:src/main/java/com.xyz.test/MyApp.java

You should have the following entries in your ~/.gitconfig or in project/.git/config file. Install the p4merge [This is my preferred diff and merge tool]

[merge]
    tool = p4merge
    keepBackup = false
[diff]
    tool = p4merge
    keepBackup = false
[difftool "p4merge"]
    path = C:/Program Files (x86)/Perforce/p4merge.exe
[mergetool]
    keepBackup = false
[difftool]
    keepBackup = false
[mergetool "p4merge"]
    path = C:/Program Files (x86)/Perforce/p4merge.exe
    cmd = p4merge.exe \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\"

Getting the IP address of the current machine using Java

Example in scala (useful in sbt file):

  import collection.JavaConverters._
  import java.net._

  def getIpAddress: String = {

    val enumeration = NetworkInterface.getNetworkInterfaces.asScala.toSeq

    val ipAddresses = enumeration.flatMap(p =>
      p.getInetAddresses.asScala.toSeq
    )

    val address = ipAddresses.find { address =>
      val host = address.getHostAddress
      host.contains(".") && !address.isLoopbackAddress
    }.getOrElse(InetAddress.getLocalHost)

    address.getHostAddress
  }

Ruby: character to ascii from a string

Ruby String provides the codepoints method after 1.9.1.

str = 'hello world'
str.codepoints.to_a
=> [104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100] 

str = "????"
str.codepoints.to_a
=> [20320, 22909, 19990, 30028]

Convert blob to base64

function bufferToBinaryString(arrayBuffer){
    return String.fromCharCode(...new Uint8Array(arrayBuffer));
}
(async () => console.log(btoa(bufferToBinaryString(await new Response(blob).arrayBuffer()))))();

or

function bufferToBinaryString(arrayBuffer){
    return String.fromCharCode(...new Uint8Array(arrayBuffer));
}
new Response(blob).arrayBuffer().then(arr_buf => console.log(btoa(bufferToBinaryString(arr_buf)))))

see Response's constructor, you can turn [blob, buffer source form data, readable stream, etc.] into Response, which can then be turned into [json, text, array buffer, blob] with async method/callbacks.

edit: as @Ralph mentioned, turning everything into utf-8 string causes problems (unfortunately Response API doesn't provide a way converting to binary string), so array buffer is use as intermediate instead, which requires two more steps (converting it to byte array THEN to binary string), if you insist on using native btoa method.

Get the string representation of a DOM node

You can create a temporary parent node, and get the innerHTML content of it:

var el = document.createElement("p");
el.appendChild(document.createTextNode("Test"));

var tmp = document.createElement("div");
tmp.appendChild(el);
console.log(tmp.innerHTML); // <p>Test</p>

EDIT: Please see answer below about outerHTML. el.outerHTML should be all that is needed.

Leaflet changing Marker color

Ahh an event listener and change the icon through setIcon() method:

createdMarker.on("dblclick", function(evt) {

        var myIcon = L.icon({
            iconUrl: 'res/marker-icon-red.png',
            shadowUrl: 'res/marker-shadow.png'
        });
        this.setIcon(myIcon);
});

What is the difference between signed and unsigned variables?

Unsigned variables can only be positive numbers, because they lack the ability to indicate that they are negative.

This ability is called the 'sign' or 'signing bit'.

A side effect is that without a signing bit, they have one more bit that can be used to represent the number, doubling the maximum number it can represent.

How to slice an array in Bash

Array slicing like in Python (From the rebash library):

array_slice() {
    local __doc__='
    Returns a slice of an array (similar to Python).

    From the Python documentation:
    One way to remember how slices work is to think of the indices as pointing
    between elements, with the left edge of the first character numbered 0.
    Then the right edge of the last element of an array of length n has
    index n, for example:
    ```
    +---+---+---+---+---+---+
    | 0 | 1 | 2 | 3 | 4 | 5 |
    +---+---+---+---+---+---+
    0   1   2   3   4   5   6
    -6  -5  -4  -3  -2  -1
    ```

    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 1:-2 "${a[@]}")
    1 2 3
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 0:1 "${a[@]}")
    0
    >>> local a=(0 1 2 3 4 5)
    >>> [ -z "$(array.slice 1:1 "${a[@]}")" ] && echo empty
    empty
    >>> local a=(0 1 2 3 4 5)
    >>> [ -z "$(array.slice 2:1 "${a[@]}")" ] && echo empty
    empty
    >>> local a=(0 1 2 3 4 5)
    >>> [ -z "$(array.slice -2:-3 "${a[@]}")" ] && echo empty
    empty
    >>> [ -z "$(array.slice -2:-2 "${a[@]}")" ] && echo empty
    empty

    Slice indices have useful defaults; an omitted first index defaults to
    zero, an omitted second index defaults to the size of the string being
    sliced.
    >>> local a=(0 1 2 3 4 5)
    >>> # from the beginning to position 2 (excluded)
    >>> echo $(array.slice 0:2 "${a[@]}")
    >>> echo $(array.slice :2 "${a[@]}")
    0 1
    0 1

    >>> local a=(0 1 2 3 4 5)
    >>> # from position 3 (included) to the end
    >>> echo $(array.slice 3:"${#a[@]}" "${a[@]}")
    >>> echo $(array.slice 3: "${a[@]}")
    3 4 5
    3 4 5

    >>> local a=(0 1 2 3 4 5)
    >>> # from the second-last (included) to the end
    >>> echo $(array.slice -2:"${#a[@]}" "${a[@]}")
    >>> echo $(array.slice -2: "${a[@]}")
    4 5
    4 5

    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice -4:-2 "${a[@]}")
    2 3

    If no range is given, it works like normal array indices.
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice -1 "${a[@]}")
    5
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice -2 "${a[@]}")
    4
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 0 "${a[@]}")
    0
    >>> local a=(0 1 2 3 4 5)
    >>> echo $(array.slice 1 "${a[@]}")
    1
    >>> local a=(0 1 2 3 4 5)
    >>> array.slice 6 "${a[@]}"; echo $?
    1
    >>> local a=(0 1 2 3 4 5)
    >>> array.slice -7 "${a[@]}"; echo $?
    1
    '
    local start end array_length length
    if [[ $1 == *:* ]]; then
        IFS=":"; read -r start end <<<"$1"
        shift
        array_length="$#"
        # defaults
        [ -z "$end" ] && end=$array_length
        [ -z "$start" ] && start=0
        (( start < 0 )) && let "start=(( array_length + start ))"
        (( end < 0 )) && let "end=(( array_length + end ))"
    else
        start="$1"
        shift
        array_length="$#"
        (( start < 0 )) && let "start=(( array_length + start ))"
        let "end=(( start + 1 ))"
    fi
    let "length=(( end - start ))"
    (( start < 0 )) && return 1
    # check bounds
    (( length < 0 )) && return 1
    (( start < 0 )) && return 1
    (( start >= array_length )) && return 1
    # parameters start with $1, so add 1 to $start
    let "start=(( start + 1 ))"
    echo "${@: $start:$length}"
}
alias array.slice="array_slice"

Python to print out status bar and percentage

Here you can use following code as a function:

def drawProgressBar(percent, barLen = 20):
    sys.stdout.write("\r")
    progress = ""
    for i in range(barLen):
        if i < int(barLen * percent):
            progress += "="
        else:
            progress += " "
    sys.stdout.write("[ %s ] %.2f%%" % (progress, percent * 100))
    sys.stdout.flush()

With use of .format:

def drawProgressBar(percent, barLen = 20):
    # percent float from 0 to 1. 
    sys.stdout.write("\r")
    sys.stdout.write("[{:<{}}] {:.0f}%".format("=" * int(barLen * percent), barLen, percent * 100))
    sys.stdout.flush()

Android LinearLayout Gradient Background

You can used a custom view to do that. With this solution, it's finished the gradient shapes of all colors in your projects:

class GradientView(context: Context, attrs: AttributeSet) : View(context, attrs) {

    // Properties
    private val paint: Paint = Paint()
    private val rect = Rect()

    //region Attributes
    var start: Int = Color.WHITE
    var end: Int = Color.WHITE
    //endregion

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        // Update Size
        val usableWidth = width - (paddingLeft + paddingRight)
        val usableHeight = height - (paddingTop + paddingBottom)
        rect.right = usableWidth
        rect.bottom = usableHeight
        // Update Color
        paint.shader = LinearGradient(0f, 0f, width.toFloat(), 0f,
                start, end, Shader.TileMode.CLAMP)
        // ReDraw
        invalidate()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.drawRect(rect, paint)
    }

}

I also create an open source project GradientView with this custom view:

https://github.com/lopspower/GradientView

implementation 'com.mikhaellopez:gradientview:1.1.0'

How do I pass JavaScript values to Scriptlet in JSP?

If you are saying you wanna pass javascript value from one jsp to another in javascript then use URLRewriting technique to pass javascript variable to next jsp file and access that in next jsp in request object.

Other wise you can't do it.

XAMPP on Windows - Apache not starting

I had my Apache service not start same as MySQL one. Please follow these steps if none of above tips works :

  1. Open regedit.exe on any windows this available . Run as administrator. (Only on windows 7 and later editions )
    1. Go to local machine/system/controlset001/services
    2. Find and delete folders of services apache and mysql .
    3. Uninstall xampp . Delete folder of xampp.
    4. Restart computer and reinstall Xampp . After that your Xampp apache and Mysql should work.

Note: Ports 80 and 443 must be unused by any program. 
      If it is in use . Just edit ports. There is a lot of tutorials about that .

How to make rounded percentages add up to 100%

DO NOT sum the rounded numbers. You're going to have inaccurate results. The total could be off significantly depending on the number of terms and the distribution of fractional parts.

Display the rounded numbers but sum the actual values. Depending on how you're presenting the numbers, the actual way to do that would vary. That way you get

 14
 48
 10
 29
 __
100

Any way you go you're going to have discrepancy. There's no way in your example to show numbers that add up to 100 without "rounding" one value the wrong way (least error would be changing 9.596 to 9)

EDIT

You need to choose between one of the following:

  1. Accuracy of the items
  2. Accuracy of the sum (if you're summing rounded values)
  3. Consistency between the rounded items and the rounded sum)

Most of the time when dealing with percentages #3 is the best option because it's more obvious when the total equals 101% than when the individual items don't total to 100, and you keep the individual items accurate. "Rounding" 9.596 to 9 is inaccurate in my opinion.

To explain this I sometimes add a footnote that explains that the individual values are rounded and may not total 100% - anyone that understands rounding should be able to understand that explanation.

Read file data without saving it in Flask

I was trying to do the exact same thing, open a text file (a CSV for Pandas actually). Don't want to make a copy of it, just want to open it. The form-WTF has a nice file browser, but then it opens the file and makes a temporary file, which it presents as a memory stream. With a little work under the hood,

form = UploadForm() 
 if form.validate_on_submit(): 
      filename = secure_filename(form.fileContents.data.filename)  
      filestream =  form.fileContents.data 
      filestream.seek(0)
      ef = pd.read_csv( filestream  )
      sr = pd.DataFrame(ef)  
      return render_template('dataframe.html',tables=[sr.to_html(justify='center, classes='table table-bordered table-hover')],titles = [filename], form=form) 

JOptionPane Input to int

Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.

MongoDB inserts float when trying to insert integer

If the value type is already double, then update the value with $set command can not change the value type double to int when using NumberInt() or NumberLong() function. So, to Change the value type, it must update the whole record.

var re = db.data.find({"name": "zero"})
re['value']=NumberInt(0)
db.data.update({"name": "zero"}, re)

Auto code completion on Eclipse

You can also set auto completion to open automatically while typing.

Go to Preferences > Java > Editor > Content Assist and write .abcdefghijklmnopqrstuvwxyz in the Auto activation triggers for Java field.

See this question for more details.

How do I change the android actionbar title and icon

The action bar title will, by default, use the label of the current activity, but you can also set it programmatically via ActionBar.setTitle().

To implement the "Back" (more precisely, "Up") button functionality you're talking about, read the "Using the App Icon for Navigation" section of the Action Bar developer guide.

Finally, to change the icon, the guide covers that as well. In short, the action bar will display the image supplied in android:icon in your manifest's application or activity element, if there is one. The typical practice is to create an application icon (in all of the various densities you'll need) named ic_launcher.png, and place it in your drawable-* directories.

How to efficiently concatenate strings in go

I do it using the following :-

package main

import (
    "fmt"
    "strings"
)

func main (){
    concatenation:= strings.Join([]string{"a","b","c"},"") //where second parameter is a separator. 
    fmt.Println(concatenation) //abc
}

What's the Kotlin equivalent of Java's String[]?

This example works perfectly in Android

In kotlin you can use a lambda expression for this. The Kotlin Array Constructor definition is:

Array(size: Int, init: (Int) -> T)

Which evaluates to:

skillsSummaryDetailLinesArray = Array(linesLen) {
        i: Int -> skillsSummaryDetailLines!!.getString(i)
}

Or:

skillsSummaryDetailLinesArray = Array<String>(linesLen) {
        i: Int -> skillsSummaryDetailLines!!.getString(i)
}

In this example the field definition was:

private var skillsSummaryDetailLinesArray: Array<String>? = null

Hope this helps

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

I got this error when using Visual Studio 2013 with Microsoft SQL Server Management Studio 2016 trying to update database with Entity Framework migrations

The fix was to install Microsoft SQL Server Management Studio 2012 SP1 as Visual Studio 2013 was missing the necessary libraries to connect to the SQL Server database.

I put together this detailed page with all the steps I took.

Upgrade python in a virtualenv

Let's consider that the environment that one wants to update has the name venv.

1. Backup venv requirementes (optional)

First of all, backup the requirements of the virtual environment:

pip freeze > requirements.txt
deactivate
#Move the folder to a new one
mv venv venv_old

2. Install Python

Assuming that one doesn't have sudo access, pyenv is a reliable and fast way to install Python. For that, one should run

$ curl https://pyenv.run | bash

and then

$ exec $SHELL

As it is suggested here.

If, when one tries to update pyenv

pyenv update

And one gets the error

bash: pyenv: command not found

It is because pyenv path wasn't exported to .bashrc. It can be solved by executing the following commands:

echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n eval "$(pyenv init -)"\nfi' >> ~/.bashrc

Then restart the shell

exec "$SHELL"

Now one should install the Python version that one wants. Let's say version 3.8.3

pyenv install 3.8.3

One can confirm if it was properly installed by running

pyenv versions

The output should be the location and the versions (in this case 3.8.3)

3. Create the new virtual environment

Finally, with the new Python version installed, create a new virtual environment (let's call it venv)

python3.8 -m venv venv

Activate it

source venv/bin/activate

and install the requirements

pip install -r requirements.txt

Now one should be up and running with a new environment.

How do I properly 'printf' an integer and a string in C?

You're on the right track. Here's a corrected version:

char str[10];
int n;

printf("type a string: ");
scanf("%s %d", str, &n);

printf("%s\n", str);
printf("%d\n", n);

Let's talk through the changes:

  1. allocate an int (n) to store your number in
  2. tell scanf to read in first a string and then a number (%d means number, as you already knew from your printf

That's pretty much all there is to it. Your code is a little bit dangerous, still, because any user input that's longer than 9 characters will overflow str and start trampling your stack.

Choosing bootstrap vs material design

As far as I know you can use all mentioned technologies separately or together. It's up to you. I think you look at the problem from the wrong angle. Material Design is just the way particular elements of the page are designed, behave and put together. Material Design provides great UI/UX, but it relies on the graphic layout (HTML/CSS) rather than JS (events, interactions).

On the other hand, AngularJS and Bootstrap are front-end frameworks that can speed up your development by saving you from writing tons of code. For example, you can build web app utilizing AngularJS, but without Material Design. Or You can build simple HTML5 web page with Material Design without AngularJS or Bootstrap. Finally you can build web app that uses AngularJS with Bootstrap and with Material Design. This is the best scenario. All technologies support each other.

  1. Bootstrap = responsive page
  2. AngularJS = MVC
  3. Material Design = great UI/UX

You can check awesome material design components for AngularJS:

https://material.angularjs.org


enter image description here

Demo: https://material.angularjs.org/latest/demo/ enter image description here

AngularJS: How to make angular load script inside ng-include?

Short answer: AngularJS ("jqlite") doesn't support this. Include jQuery on your page (before including Angular), and it should work. See https://groups.google.com/d/topic/angular/H4haaMePJU0/discussion

How do I drop a MongoDB database from the command line?

Open a terminal and type:

mongo 

The below command should show the listed databases:

show dbs 

/* the <dbname> is the database you'd like to drop */
use <dbname> 

/* the below command will delete the database */
db.dropDatabase()  

The below should be the output in the terminal:

{
  "dropped": "<dbname>",
  "ok": 1
}

maxlength ignored for input type="number" in Chrome

I will make this quick and easy to understand!

Instead of maxlength for type='number' (maxlength is meant to define the maximum amount of letters for a string in a text type), use min='' and max='' .

Cheers

How to format strings in Java

If you choose not to use String.format, the other option is the + binary operator

String str = "Step " + a + " of " + b;

This is the equivalent of

new StringBuilder("Step ").append(String.valueOf(1)).append(" of ").append(String.valueOf(2));

Whichever you use is your choice. StringBuilder is faster, but the speed difference is marginal. I prefer to use the + operator (which does a StringBuilder.append(String.valueOf(X))) and find it easier to read.

Conditional formatting using AND() function

You can use a much simpler formula. I just created a new workbook to test it.

Column A = Date1 | Column B = Date2 | Column C = Date3

Highlight Column A and enter the conditional formatting formula:

=AND(A1>B1,A1<C1)

How to place a JButton at a desired location in a JFrame using Java

You should set layout first by syntax pnlButton.setLayout(), and then choose the most suitable layout which u want. Ex: pnlButton.setLayout(new FlowLayout(FlowLayout.LEADING, 5, 5));. And then, take that JButton into JPanel.

How to call MVC Action using Jquery AJAX and then submit form in MVC?

Assuming that your button is in a form, you are not preventing the default behaviour of the button click from happening i.e. Your AJAX call is made in addition to the form submission; what you're very likely seeing is one of

  1. the form submission happens faster than the AJAX call returns
  2. the form submission causes the browser to abort the AJAX request and continues with submitting the form.

So you should prevent the default behaviour of the button click

$('#btnSave').click(function (e) {

    // prevent the default event behaviour    
    e.preventDefault();

    $.ajax({
        url: "/Home/SaveDetailedInfo",
        type: "POST",
        data: JSON.stringify({ 'Options': someData}),
        dataType: "json",
        traditional: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {

            // perform your save call here

            if (data.status == "Success") {
                alert("Done");
            } else {
                alert("Error occurs on the Database level!");
            }
        },
        error: function () {
            alert("An error has occured!!!");
        }
    });
});

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

//*[text()='ABC'] 

returns

<street>ABC</street>
<comment>BLAH BLAH BLAH <br><br>ABC</comment>

React.js create loop through Array

In CurrentGame component you need to change initial state because you are trying use loop for participants but this property is undefined that's why you get error.,

getInitialState: function(){
    return {
       data: {
          participants: [] 
       }
    };
},

also, as player in .map is Object you should get properties from it

this.props.data.participants.map(function(player) {
   return <li key={player.championId}>{player.summonerName}</li>
   // -------------------^^^^^^^^^^^---------^^^^^^^^^^^^^^
})

Example

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

If you have recently installed or updated the Microsoft.CodeDom.Providers.DotNetCompilerPlatform package, double-check that the versions of that package referenced in your project point to the correct, and same, version of that package:

  • In ProjectName.csproj, ensure that an <Import> tag for Microsoft.CodeDom.Providers.DotNetCompilerPlatform is present and points to the correct version.

  • In ProjectName.csproj, ensure that a <Reference> tag for Microsoft.CodeDom.Providers.DotNetCompilerPlatform is present, and points to the correct version, both in the Include attribute and the child <HintPath>.

  • In that project's web.config, ensure that the <system.codedom> tag is present, and that its child <compiler> tags have the same version in their type attribute.

For some reason, in my case an upgrade of this package from 1.0.5 to 1.0.8 caused the <Reference> tag in the.csproj to have its Include pointing to the old version 1.0.5.0 (which I had deleted after upgrading the package), but everything else was pointing to the new and correct version 1.0.8.0.

How do I replicate a \t tab space in HTML?

You must use

<dd> </dd> in the html code.

<dd>A free, open source, cross-platform,graphical web browser developed by theMozilla Corporation and hundreds of volunteers.</dd>

----------------------------------
Firefox
    A free, open source, cross-platform, graphical web browser developed by the Mozilla 
    Corporation and hundreds of volunteers.

enter image description here

How to determine tables size in Oracle

Here is a query, you can run it in SQL Developer (or SQL*Plus):

SELECT DS.TABLESPACE_NAME, SEGMENT_NAME, ROUND(SUM(DS.BYTES) / (1024 * 1024)) AS MB
  FROM DBA_SEGMENTS DS
  WHERE SEGMENT_NAME IN (SELECT TABLE_NAME FROM DBA_TABLES)
 GROUP BY DS.TABLESPACE_NAME,
       SEGMENT_NAME;

Converting File to MultiPartFile

If you can't import MockMultipartFile using

import org.springframework.mock.web.MockMultipartFile;

you need to add the below dependency into pom.xml:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

Jquery click not working with ipad

I had a span that would create a popup. If I used "click touchstart" it would trigger parts of the popup during the touchend. I fixed this by making the span "click touchend".

Pandas KeyError: value not in index

Use reindex to get all columns you need. It'll preserve the ones that are already there and put in empty columns otherwise.

p = p.reindex(columns=['1Sun', '2Mon', '3Tue', '4Wed', '5Thu', '6Fri', '7Sat'])

So, your entire code example should look like this:

df = pd.read_csv(CsvFileName)

p = df.pivot_table(index=['Hour'], columns='DOW', values='Changes', aggfunc=np.mean).round(0)
p.fillna(0, inplace=True)

columns = ["1Sun", "2Mon", "3Tue", "4Wed", "5Thu", "6Fri", "7Sat"]
p = p.reindex(columns=columns)
p[columns] = p[columns].astype(int)

How do I convert certain columns of a data frame to become factors?

Here's an example:

#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
  a b
1 1 2
2 2 3
3 3 4

#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL

#Convert that column to a factor
> d$a <- factor(d$a)
> d
  a b
1 1 2
2 2 3
3 3 4

#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"

You can also handle this when reading in your data. See the colClasses and stringsAsFactors parameters in e.g. readCSV().

Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.

Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.

Get the value of bootstrap Datetimepicker in JavaScript

It seems the doc evolved.

One should now use : $("#datetimepicker1").data("DateTimePicker").date().

NB : Doing so return a Moment object, not a Date object

How to list all the roles existing in Oracle database?

Got the answer :

SELECT * FROM DBA_ROLES;

File size exceeds configured limit (2560000), code insight features not available

This is built from Álvaro González's answer and How to increase IDE memory limit in IntelliJ IDEA on Mac?

Go to Help > Edit Custom Properties

Add:

idea.max.intellisense.filesize=999999

Restart the IDE.

'typeid' versus 'typeof' in C++

The primary difference between the two is the following

  • typeof is a compile time construct and returns the type as defined at compile time
  • typeid is a runtime construct and hence gives information about the runtime type of the value.

typeof Reference: http://www.delorie.com/gnu/docs/gcc/gcc_36.html

typeid Reference: https://en.wikipedia.org/wiki/Typeid

Set markers for individual points on a line in Matplotlib

You can do:

import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [2,1,3,6,7]

plt.plot(x, y, style='.-')
plt.show()

This will return a graph with the data points marked with a dot

Merge two (or more) lists into one, in C# .NET

When you got few list but you don't know how many exactly, use this:

listsOfProducts contains few lists filled with objects.

List<Product> productListMerged = new List<Product>();

listsOfProducts.ForEach(q => q.ForEach(e => productListMerged.Add(e)));

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

How can I write a heredoc to a file in Bash script?

If you want to keep the heredoc indented for readability:

$ perl -pe 's/^\s*//' << EOF
     line 1
     line 2
EOF

The built-in method for supporting indented heredoc in Bash only supports leading tabs, not spaces.

Perl can be replaced with awk to save a few characters, but the Perl one is probably easier to remember if you know basic regular expressions.

Check if file exists and whether it contains a specific string

Instead of storing the output of grep in a variable and then checking whether the variable is empty, you can do this:

if grep -q "poet" $file_name
then
    echo "poet was found in $file_name"
fi

============

Here are some commonly used tests:

   -d FILE
          FILE exists and is a directory
   -e FILE
          FILE exists
   -f FILE
          FILE exists and is a regular file
   -h FILE
          FILE exists and is a symbolic link (same as -L)
   -r FILE
          FILE exists and is readable
   -s FILE
          FILE exists and has a size greater than zero
   -w FILE
          FILE exists and is writable
   -x FILE
          FILE exists and is executable
   -z STRING
          the length of STRING is zero

Example:

if [ -e "$file_name" ] && [ ! -z "$used_var" ]
then
    echo "$file_name exists and $used_var is not empty"
fi

PuTTY scripting to log onto host

When you use the -m option putty does not allocate a tty, it runs the command and quits. If you want to run an interactive script (such as a sql client), you need to tell it to allocate a tty with -t, see 3.8.3.12 -t and -T: control pseudo-terminal allocation. You'll avoid keeping a script on the server, as well as having to invoke it once you're connected.

Here's what I'm using to connect to mysql from a batch file:

#mysql.bat start putty -t -load "sessionname" -l username -pw password -m c:\mysql.sh

#mysql.sh mysql -h localhost -u username --password="foo" mydb

https://superuser.com/questions/587629/putty-run-a-remote-command-after-login-keep-the-shell-running

Allow access permission to write in Program Files of Windows 7

Your program has to run with Administrative Rights. You can't do this automatically with code, but you can request the user (in code) to elevate the rights of your program while it's running. There's a wiki on how to do this. Alternatively, any program can be run as administrator by right-clicking its icon and clicking "Run as administrator".

However, I wouldn't suggest doing this. It would be better to use something like this:

Environment.GetFolderPath(SpecialFolder.ApplicationData);

to get the AppData Folder path and create a folder there for your app. Then put the temp files there.

Find a commit on GitHub given the commit hash

A URL of the form https://github.com/<owner>/<project>/commit/<hash> will show you the changes introduced in that commit. For example here's a recent bugfix I made to one of my projects on GitHub:

https://github.com/jerith666/git-graph/commit/35e32b6a00dec02ae7d7c45c6b7106779a124685

You can also shorten the hash to any unique prefix, like so:

https://github.com/jerith666/git-graph/commit/35e32b


I know you just asked about GitHub, but for completeness: If you have the repository checked out, from the command line, you can achieve basically the same thing with either of these commands (unique prefixes work here too):

git show 35e32b6a00dec02ae7d7c45c6b7106779a124685
git log -p -1 35e32b6a00dec02ae7d7c45c6b7106779a124685

Note: If you shorten the commit hash too far, the command line gives you a helpful disambiguation message, but GitHub will just return a 404.

Difference between getAttribute() and getParameter()

getParameter - Is used for getting the information you need from the Client's HTML page

getAttribute - This is used for getting the parameters set previously in another or the same JSP or Servlet page.

Basically, if you are forwarding or just going from one jsp/servlet to another one, there is no way to have the information you want unless you choose to put them in an Object and use the set-attribute to store in a Session variable.

Using getAttribute, you can retrieve the Session variable.

Determining if a number is prime

If you are lazy, and have a lot of RAM, create a sieve of Eratosthenes which is practically a giant array from which you kicked all numbers that are not prime. From then on every prime "probability" test will be super quick. The upper limit for this solution for fast results is the amount of you RAM. The upper limit for this solution for superslow results is your hard disk's capacity.

ES6 exporting/importing in index file

Nav.js comp inside components folder

export {Nav}

index.js in component folder

export {Nav} from './Nav';
export {Another} from './Another';

import anywhere

import {Nav, Another} from './components'

How to get error message when ifstream open fails

You could try letting the stream throw an exception on failure:

std::ifstream f;
//prepare f to throw if failbit gets set
std::ios_base::iostate exceptionMask = f.exceptions() | std::ios::failbit;
f.exceptions(exceptionMask);

try {
  f.open(fileName);
}
catch (std::ios_base::failure& e) {
  std::cerr << e.what() << '\n';
}

e.what(), however, does not seem to be very helpful:

  • I tried it on Win7, Embarcadero RAD Studio 2010 where it gives "ios_base::failbit set" whereas strerror(errno) gives "No such file or directory."
  • On Ubuntu 13.04, gcc 4.7.3 the exception says "basic_ios::clear" (thanks to arne)

If e.what() does not work for you (I don't know what it will tell you about the error, since that's not standardized), try using std::make_error_condition (C++11 only):

catch (std::ios_base::failure& e) {
  if ( e.code() == std::make_error_condition(std::io_errc::stream) )
    std::cerr << "Stream error!\n"; 
  else
    std::cerr << "Unknown failure opening file.\n";
}

Use jQuery to hide a DIV when the user clicks outside of it

And for Touch devices like IPAD and IPHONE we can use following code

$(document).on('touchstart', function (event) {
var container = $("YOUR CONTAINER SELECTOR");

if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.hide();
    }
});

Get current time in seconds since the Epoch on Linux, Bash

Pure bash solution

Since bash 5.0 (released on 7 Jan 2019) you can use the built-in variable EPOCHSECONDS.

$ echo $EPOCHSECONDS
1547624774

There is also EPOCHREALTIME which includes fractions of seconds.

$ echo $EPOCHREALTIME
1547624774.371215

EPOCHREALTIME can be converted to micro-seconds (µs) by removing the decimal point. This might be of interest when using bash's built-in arithmetic (( expression )) which can only handle integers.

$ echo ${EPOCHREALTIME/./}
1547624774371215

In all examples from above the printed time values are equal for better readability. In reality the time values would differ since each command takes a small amount of time to be executed.

System.Timers.Timer vs System.Threading.Timer

The two classes are functionally equivalent, except that System.Timers.Timer has an option to invoke all its timer expiration callbacks through ISynchronizeInvoke by setting SynchronizingObject. Otherwise, both timers invoke expiration callbacks on thread pool threads.

When you drag a System.Timers.Timer onto a Windows Forms design surface, Visual Studio sets SynchronizingObject to the form object, which causes all expiration callbacks to be called on the UI thread.

json_decode returns NULL after webservice call

I was having this problem, when I was calling a soap method to obtain my data, and then return a json string, when I tried to do json_decode I just keep getting null.

Since I was using nusoap to do the soap call I tried to just return json string and now I could do a json_decode, since I really neaded to get my data with a SOAP call, what I did was add ob_start() before include nusoap, id did my call genereate json string, and then before returning my json string I did ob_end_clean(), and GOT MY PROBLEM FIXED :)

EXAMPLE

//HRT - SIGNED
//20130116
//verifica se um num assoc deco é valido
ob_start();
require('/nusoap.php');
$aResponse['SimpleIsMemberResult']['IsMember'] = FALSE;
if(!empty($iNumAssociadoTmp))
{
    try
    {
        $client = new soapclientNusoap(PartnerService.svc?wsdl',
         array( 
            // OPTS 
            'trace' => 0,
            'exceptions' => false,
            'cache_wsdl' => WSDL_CACHE_NONE
         )
        );
    //MENSAGEM A ENVIAR
    $sMensagem1 = '
        <SimpleIsMember>
            <request>
                <CheckDigit>'.$iCheckDigitAssociado.'</CheckDigit>
                <Country>Portugal</Country>
                <MemberNumber">'.$iNumAssociadoDeco.'</MemberNumber>
            </request>
        </SimpleIsMember>';
    $aResponse = $client->call('SimpleIsMember',$sMensagem1);
    $aData = array('dados'=>$aResponse->xpto, 'success'=>$aResponse->example);
    }
}
ob_end_clean();
return json_encode($aData);

How do I store an array in localStorage?

Just created this:

https://gist.github.com/3854049

//Setter
Storage.setObj('users.albums.sexPistols',"blah");
Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" });
Storage.setObj('users.albums.sexPistols.sid',"Other songs");

//Getters
Storage.getObj('users');
Storage.getObj('users.albums');
Storage.getObj('users.albums.sexPistols');
Storage.getObj('users.albums.sexPistols.sid');
Storage.getObj('users.albums.sexPistols.nancy');

Best Practices for Custom Helpers in Laravel 5

Custom Blade Directives in Laravel 5

Yes, there is another way to do this!

Step 1: Register a custom Blade directive:

<?php // code in app/Providers/AppServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Blade; // <-- This is important! Without it you'll get an exception.

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
     public function boot()
     {
         // Make a custom blade directive:
         Blade::directive('shout', function ($string) {
             return trim(strtoupper($string), '(\'\')');
         });

         // And another one for good measure:
         Blade::directive('customLink', function () {
             return '<a href="#">Custom Link</a>';
         });
     }
    ...

Step 2: Use your custom Blade directive:

<!-- // code in resources/views/view.blade.php -->

@shout('this is my custom blade directive!!')
<br />
@customLink

Outputs:

THIS IS MY CUSTOM BLADE DIRECTIVE!!
Custom Link


Source: https://laravel.com/docs/5.1/blade#extending-blade

Additional Reading: https://mattstauffer.co/blog/custom-conditionals-with-laravels-blade-directives


If you want to learn how to best make custom classes that you can use anywhere, see Custom Classes in Laravel 5, the Easy Way

Easy way to concatenate two byte arrays

For two or multiple arrays, this simple and clean utility method can be used:

/**
 * Append the given byte arrays to one big array
 *
 * @param arrays The arrays to append
 * @return The complete array containing the appended data
 */
public static final byte[] append(final byte[]... arrays) {
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    if (arrays != null) {
        for (final byte[] array : arrays) {
            if (array != null) {
                out.write(array, 0, array.length);
            }
        }
    }
    return out.toByteArray();
}

When should we use mutex and when should we use semaphore

As was pointed out, a semaphore with a count of one is the same thing as a 'binary' semaphore which is the same thing as a mutex.

The main things I've seen semaphores with a count greater than one used for is producer/consumer situations in which you have a queue of a certain fixed size.

You have two semaphores then. The first semaphore is initially set to be the number of items in the queue and the second semaphore is set to 0. The producer does a P operation on the first semaphore, adds to the queue. and does a V operation on the second. The consumer does a P operation on the second semaphore, removes from the queue, and then does a V operation on the first.

In this way the producer is blocked whenever it fills the queue, and the consumer is blocked whenever the queue is empty.

Selecting multiple columns with linq query and lambda expression

using LINQ and Lamba, i wanted to return two field values and assign it to single entity object field;

as Name = Fname + " " + LName;

See my below code which is working as expected; hope this is useful;

Myentity objMyEntity = new Myentity
{
id = obj.Id,
Name = contxt.Vendors.Where(v => v.PQS_ID == obj.Id).Select(v=> new { contact = v.Fname + " " + v.LName}).Single().contact
}

no need to declare the 'contact'

PHP "pretty print" json_encode

Here's a function to pretty up your json: pretty_json

Right pad a string with variable number of spaces

The easiest way to right pad a string with spaces (without them being trimmed) is to simply cast the string as CHAR(length). MSSQL will sometimes trim whitespace from VARCHAR (because it is a VARiable-length data type). Since CHAR is a fixed length datatype, SQL Server will never trim the trailing spaces, and will automatically pad strings that are shorter than its length with spaces. Try the following code snippet for example.

SELECT CAST('Test' AS CHAR(20))

This returns the value 'Test '.

Switch to another Git tag

As of Git v2.23.0 (August 2019), git switch is preferred over git checkout when you’re simply switching branches/tags. I’m guessing they did this since git checkout had two functions: for switching branches and for restoring files. So in v2.23.0, they added two new commands, git switch, and git restore, to separate those concerns. I would predict at some point in the future, git checkout will be deprecated.

To switch to a normal branch, use git switch <branch-name>. To switch to a commit-like object, including single commits and tags, use git switch --detach <commitish>, where <commitish> is the tag name or commit number.

The --detach option forces you to recognize that you’re in a mode of “inspection and discardable experiments”. To create a new branch from the commitish you’re switching to, use git switch -c <new-branch> <start-point>.

How to identify unused CSS definitions from multiple CSS files in a project

Chrome Developer Tools has an Audits tab which can show unused CSS selectors.

Run an audit, then, under Web Page Performance see Remove unused CSS rules

enter image description here

' << ' operator in verilog

1 << ADDR_WIDTH means 1 will be shifted 8 bits to the left and will be assigned as the value for RAM_DEPTH.

In addition, 1 << ADDR_WIDTH also means 2^ADDR_WIDTH.

Given ADDR_WIDTH = 8, then 2^8 = 256 and that will be the value for RAM_DEPTH

CFLAGS, CCFLAGS, CXXFLAGS - what exactly do these variables control?

As you noticed, these are Makefile {macros or variables}, not compiler options. They implement a set of conventions. (Macros is an old name for them, still used by some. GNU make doc calls them variables.)

The only reason that the names matter is the default make rules, visible via make -p, which use some of them.

If you write all your own rules, you get to pick all your own macro names.

In a vanilla gnu make, there's no such thing as CCFLAGS. There are CFLAGS, CPPFLAGS, and CXXFLAGS. CFLAGS for the C compiler, CXXFLAGS for C++, and CPPFLAGS for both.

Why is CPPFLAGS in both? Conventionally, it's the home of preprocessor flags (-D, -U) and both c and c++ use them. Now, the assumption that everyone wants the same define environment for c and c++ is perhaps questionable, but traditional.


P.S. As noted by James Moore, some projects use CPPFLAGS for flags to the C++ compiler, not flags to the C preprocessor. The Android NDK, for one huge example.

Split bash string by newline characters

Another way:

x=$'Some\nstring'
readarray -t y <<<"$x"

Or, if you don't have bash 4, the bash 3.2 equivalent:

IFS=$'\n' read -rd '' -a y <<<"$x"

You can also do it the way you were initially trying to use:

y=(${x//$'\n'/ })

This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'. To make it work, you need to restrict the word separator before parsing it:

IFS=$'\n' y=(${x//$'\n'/ })

...and then, since you are changing the separator, you don't need to convert the \n to space anymore, so you can simplify it to:

IFS=$'\n' y=($x)

This approach will function unless $x contains a matching globbing pattern (such as "*") - in which case it will be replaced by the matched file name(s). The read/readarray methods require newer bash versions, but work in all cases.

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Even though your JDK in eclipse is 1.7, you need to make sure eclipse compilance level also set to 1.7. You can check compilance level--> Window-->Preferences--> Java--Compiler--compilance level.

Unsupported major minor error happens in cases where compilance level doesn't match with runtime.

Change drawable color programmatically

You can try this for svg vector drawable

DrawableCompat.setTint(
    DrawableCompat.wrap(myImageView.getDrawable()),
    ContextCompat.getColor(context, R.color.another_nice_color)
);

Constraint Layout Vertical Align Center

You can easily center multiple things by creating a chain. It works both vertically and horizontally

Link to official documentation about chains

Edit to answer comment :

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
    <TextView
        android:id="@+id/first_score"
        android:layout_width="60dp"
        android:layout_height="wrap_content"
        android:text="10"
        app:layout_constraintEnd_toStartOf="@+id/second_score"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/second_score"
        app:layout_constraintBottom_toTopOf="@+id/subtitle"
        app:layout_constraintHorizontal_chainStyle="spread"
        app:layout_constraintVertical_chainStyle="packed"
        android:gravity="center"
        />
    <TextView
        android:id="@+id/subtitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Subtitle"
        app:layout_constraintTop_toBottomOf="@+id/first_score"
        app:layout_constraintBottom_toBottomOf="@+id/second_score"
        app:layout_constraintStart_toStartOf="@id/first_score"
        app:layout_constraintEnd_toEndOf="@id/first_score"
        />
    <TextView
        android:id="@+id/second_score"
        android:layout_width="60dp"
        android:layout_height="120sp"
        android:text="243"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toStartOf="@+id/thrid_score"
        app:layout_constraintStart_toEndOf="@id/first_score"
        app:layout_constraintTop_toTopOf="parent"
        android:gravity="center"
        />
    <TextView
        android:id="@+id/thrid_score"
        android:layout_width="60dp"
        android:layout_height="wrap_content"
        android:text="3200"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/second_score"
        app:layout_constraintTop_toTopOf="@id/second_score"
        app:layout_constraintBottom_toBottomOf="@id/second_score"
        android:gravity="center"
        />
</android.support.constraint.ConstraintLayout>

This code gives this result

You have the horizontal chain : first_score <=> second_score <=> third_score. second_score is centered vertically. The other scores are centered vertically according to it.

You can definitely create a vertical chain first_score <=> subtitle and center it according to second_score

Blade if(isset) is not working Laravel

I solved this using the optional() helper. Using the example here it would be:

{{ optional($usersType) }}

A more complicated example would be if, like me, say you are trying to access a property of a null object (ie. $users->type) in a view that is using old() helper.

value="{{ old('type', optional($users)->type }}"

Important to note that the brackets go around the object variable and not the whole thing if trying to access a property of the object.

https://laravel.com/docs/5.8/helpers#method-optional

How to check in Javascript if one element is contained within another

Another solution that wasn't mentioned:

Example Here

var parent = document.querySelector('.parent');

if (parent.querySelector('.child') !== null) {
    // .. it's a child
}

It doesn't matter whether the element is a direct child, it will work at any depth.


Alternatively, using the .contains() method:

Example Here

var parent = document.querySelector('.parent'),
    child = document.querySelector('.child');

if (parent.contains(child)) {
    // .. it's a child
}

Remove specific characters from a string in Python

#!/usr/bin/python
import re

strs = "how^ much for{} the maple syrup? $20.99? That's[] ricidulous!!!"
print strs
nstr = re.sub(r'[?|$|.|!|a|b]',r' ',strs)#i have taken special character to remove but any #character can be added here
print nstr
nestr = re.sub(r'[^a-zA-Z0-9 ]',r'',nstr)#for removing special character
print nestr

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

In this case that you know that you have all items in the first place on array you can parse the string to JArray and then parse the first item using JObject.Parse

var  jsonArrayString = @"
[
  {
    ""country"": ""India"",
    ""city"": ""Mall Road, Gurgaon"",
  },
  {
    ""country"": ""India"",
    ""city"": ""Mall Road, Kanpur"",
  }
]";
JArray jsonArray = JArray.Parse(jsonArrayString);
dynamic data = JObject.Parse(jsonArray[0].ToString());

Read response body in JAX-RS client from a post request

I just found a solution for jaxrs-ri-2.16 - simply use

String output = response.readEntity(String.class)

this delivers the content as expected.

Create text file and fill it using bash

#!/bin/bash
file_location=/home/test/$1.json
if [ -e $policy ]; then
  echo "File $1.json already exists!"
else
  cat > $file_location <<EOF
{
      "contact": {
          "name": "xyz",
          "phonenumber":   "xxx-xxx-xxxx"
      }
    }
EOF
fi

This code checks if the given JSON file of the user is present in test home directory or not. If it's not present it will create it with the content. You can modify the file location and content according to your needs.

The conversion of a datetime2 data type to a datetime data type resulted in an out-of-range value

I got this error after I changed my model (code first) as follows:

public DateTime? DateCreated

to

public DateTime DateCreated

Present rows with null-value in DateCreated caused this error. So I had to use SQL UPDATE Statement manually for initializing the field with a standard value.

Another solution could be a specifying of the default value for the filed.

How can get the text of a div tag using only javascript (no jQuery)

Actually you dont need to call document.getElementById() function to get access to your div.

You can use this object directly by id:

text = test.textContent || test.innerText;
alert(text);

What is HEAD in Git?

There is a, perhaps subtle, but important misconception in a number these answers. I thought I'd add my answer to clear it up.

What is HEAD?

HEAD is YOU

HEADis a symbolic reference pointing to wherever you are in your commit history. It follows you wherever you go, whatever you do, like a shadow. If you make a commit, HEAD will move. If you checkout something, HEAD will move. Whatever you do, if you have moved somewhere new in your commit history, HEAD has moved along with you. To address one common misconception: you cannot detach yourself from HEAD. That is not what a detached HEAD state is. If you ever find yourself thinking: "oh no, i'm in detached HEAD state! I've lost my HEAD!" Remember, it's your HEAD. HEAD is you. You haven't detached from the HEAD, you and your HEAD have detached from something else.

What can HEAD attach to?

HEAD can point to a commit, yes, but typically it does not. Let me say that again. Typically HEAD does not point to a commit. It points to a branch reference. It is attached to that branch, and when you do certain things (e.g., commit or reset), the attached branch will move along with HEAD. You can see what it is pointing to by looking under the hood.

cat .git/HEAD

Normally you'll get something like this:

ref: refs/heads/master

Sometimes you'll get something like this:

a3c485d9688e3c6bc14b06ca1529f0e78edd3f86

That's what happens when HEAD points directly to a commit. This is called a detached HEAD, because HEAD is pointing to something other than a branch reference. If you make a commit in this state, master, no longer being attached to HEAD, will no longer move along with you. It does not matter where that commit is. You could be on the same commit as your master branch, but if HEAD is pointing to the commit rather than the branch, it is detached and a new commit will not be associated with a branch reference.

You can look at this graphically if you try the following exercise. From a git repository, run this. You'll get something slightly different, but they key bits will be there. When it is time to checkout the commit directly, just use whatever abbreviated hash you get from the first output (here it is a3c485d).

git checkout master
git log --pretty=format:"%h:  %d" -1
# a3c485d:   (HEAD -> master)

git checkout a3c485d -q # (-q is for dramatic effect)
git log --pretty=format:"%h:  %d" -1   
# a3c485d:   (HEAD, master)

OK, so there is a small difference in the output here. Checking out the commit directly (instead of the branch) gives us a comma instead of an arrow. What do you think, are we in a detached HEAD state? HEAD is still referring to a specific revision that is associated with a branch name. We're still on the master branch, aren't we?

Now try:

git status
# HEAD detached at a3c485d

Nope. We're in 'detached HEAD' state.

You can see the same representation of (HEAD -> branch) vs. (HEAD, branch) with git log -1.

In conclusion

HEAD is you. It points to whatever you checked out, wherever you are. Typically that is not a commit, it is a branch. If HEAD does point to a commit (or tag), even if it's the same commit (or tag) that a branch also points to, you (and HEAD) have been detached from that branch. Since you don't have a branch attached to you, the branch won't follow along with you as you make new commits. HEAD, however, will.

Node.js Error: Cannot find module express

After you do express in your terminal, then do

npm install

To install all the dependencies.

Then you can do node app to run the server.

Can I set up HTML/Email Templates with ASP.NET?

DotLiquid is another option. You specify values from a class model as {{ user.name }} and then at runtime you provide the data in that class, and the template with the markup, and it will merge the values in for you. It is similar to using the Razor templating engine in many ways. It supports more complex things like loops and various function like ToUpper. The nice thing is these are "safe" so that user's who create the templates can't crash your system or write unsafe code like you would in razor: http://dotliquidmarkup.org/try-online

fatal: git-write-tree: error building trees

This happened for me when I was trying to stash my changes, but then my changes had conflicts with my branch's current state.

So I did git reset --mixed and then resolved the git conflict and stashed again.

What is causing "Unable to allocate memory for pool" in PHP?

Monitor your Cached Files Size (you can use apc.php from apc pecl package) and increase apc.shm_size according to your needs.

This solves the problem.

How do I block comment in Jupyter notebook?

I am using chrome, Linux Mint; and for commenting and dis-commenting bundle of lines:

Ctrl + /

How to remove leading and trailing whitespace in a MySQL field?

Just to be clear, TRIM by default only remove spaces (not all whitespaces). Here is the doc: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim

Adding 30 minutes to time formatted as H:i in PHP

$time = 30 * 60; //30 minutes
$start_time = date('Y-m-d h:i:s', time() - $time);
$end_time = date('Y-m-d h:i:s', time() + $time);

Efficient iteration with index in Scala

There's nothing in the stdlib that will do it for you without creating tuple garbage, but it's not too hard to write your own. Unfortunately I've never bothered to figure out how to do the proper CanBuildFrom implicit raindance to make such things generic in the type of collection they're applied to, but if it's possible, I'm sure someone will enlighten us. :)

def foreachWithIndex[A](as: Traversable[A])(f: (Int,A) => Unit) {
  var i = 0
  for (a <- as) {
    f(i, a)
    i += 1
  }
}

def mapWithIndex[A,B](in: List[A])(f: (Int,A) => B): List[B] = {
  def mapWithIndex0(in: List[A], gotSoFar: List[B], i: Int): List[B] = {
    in match {
      case Nil         => gotSoFar.reverse
      case one :: more => mapWithIndex0(more, f(i, one) :: gotSoFar, i+1)
    }
  }
  mapWithIndex0(in, Nil, 0)
}

// Tests....

@Test
def testForeachWithIndex() {
  var out = List[Int]()
  ScalaUtils.foreachWithIndex(List(1,2,3,4)) { (i, num) =>
    out :+= i * num
  }
  assertEquals(List(0,2,6,12),out)
}

@Test
def testMapWithIndex() {
  val out = ScalaUtils.mapWithIndex(List(4,3,2,1)) { (i, num) =>
    i * num
  }

  assertEquals(List(0,3,4,3),out)
}

Faking an RS232 Serial Port

I use com0com - With Signed Driver, on windows 7 x64 to emulate COM3 AND COM4 as a pair.

Then i use COM Dataport Emulator to recieve from COM4.

Then i open COM3 with the app im developping (c#) and send data to COM3.

The data sent thru COM3 is received by COM4 and shown by 'COM Dataport Emulator' who can also send back a response (not automated).

So with this 2 great programs i managed to emulate Serial RS-232 comunication.

Hope it helps.

Both programs are free!!!!!

Easy way to prevent Heroku idling?

You can use http://pingdom.com/ to check your app; if done every minute or so, heroku won't idle your app and won't need to spin-up.

Java - Find shortest path between 2 points in a distance weighted map

Estimated sanjan:

The idea behind Dijkstra's Algorithm is to explore all the nodes of the graph in an ordered way. The algorithm stores a priority queue where the nodes are ordered according to the cost from the start, and in each iteration of the algorithm the following operations are performed:

  1. Extract from the queue the node with the lowest cost from the start, N
  2. Obtain its neighbors (N') and their associated cost, which is cost(N) + cost(N, N')
  3. Insert in queue the neighbor nodes N', with the priority given by their cost

It's true that the algorithm calculates the cost of the path between the start (A in your case) and all the rest of the nodes, but you can stop the exploration of the algorithm when it reaches the goal (Z in your example). At this point you know the cost between A and Z, and the path connecting them.

I recommend you to use a library which implements this algorithm instead of coding your own. In Java, you might take a look to the Hipster library, which has a very friendly way to generate the graph and start using the search algorithms.

Here you have an example of how to define the graph and start using Dijstra with Hipster.

// Create a simple weighted directed graph with Hipster where
// vertices are Strings and edge values are just doubles
HipsterDirectedGraph<String,Double> graph = GraphBuilder.create()
  .connect("A").to("B").withEdge(4d)
  .connect("A").to("C").withEdge(2d)
  .connect("B").to("C").withEdge(5d)
  .connect("B").to("D").withEdge(10d)
  .connect("C").to("E").withEdge(3d)
  .connect("D").to("F").withEdge(11d)
  .connect("E").to("D").withEdge(4d)
  .buildDirectedGraph();

// Create the search problem. For graph problems, just use
// the GraphSearchProblem util class to generate the problem with ease.
SearchProblem p = GraphSearchProblem
  .startingFrom("A")
  .in(graph)
  .takeCostsFromEdges()
  .build();

// Search the shortest path from "A" to "F"
System.out.println(Hipster.createDijkstra(p).search("F"));

You only have to substitute the definition of the graph for your own, and then instantiate the algorithm as in the example.

I hope this helps!

Usage of __slots__?

You have — essentially — no use for __slots__.

For the time when you think you might need __slots__, you actually want to use Lightweight or Flyweight design patterns. These are cases when you no longer want to use purely Python objects. Instead, you want a Python object-like wrapper around an array, struct, or numpy array.

class Flyweight(object):

    def get(self, theData, index):
        return theData[index]

    def set(self, theData, index, value):
        theData[index]= value

The class-like wrapper has no attributes — it just provides methods that act on the underlying data. The methods can be reduced to class methods. Indeed, it could be reduced to just functions operating on the underlying array of data.

How to update a git clone --mirror?

See here: Git doesn't clone all branches on subsequent clones?

If you really want this by pulling branches instead of push --mirror, you can have a look here:

"fetch --all" in a git bare repository doesn't synchronize local branches to the remote ones

This answer provides detailed steps on how to achieve that relatively easily:

jQuery 'if .change() or .keyup()'

If you're ever dynamically generating page content or loading content through AJAX, the following example is really the way you should go:

  1. It prevents double binding in the case where the script is loaded more than once, such as in an AJAX request.
  2. The bind lives on the body of the document, so regardless of what elements are added, moved, removed and re-added, all descendants of body matching the selector specified will retain proper binding.

The Code:

// Define the element we wish to bind to.
var bind_to = ':input';

// Prevent double-binding.
$(document.body).off('change', bind_to);

// Bind the event to all body descendants matching the "bind_to" selector.
$(document.body).on('change keyup', bind_to, function(event) {
    alert('something happened!');
});

Please notice! I'm making use of $.on() and $.off() rather than other methods for several reasons:

  1. $.live() and $.die() are deprecated and have been omitted from more recent versions of jQuery.
  2. I'd either need to define a separate function (therefore cluttering up the global scope,) and pass the function to both $.change() and $.keyup() separately, or pass the same function declaration to each function called; Duplicating logic... Which is absolutely unacceptable.
  3. If elements are ever added to the DOM, $.bind() does not dynamically bind to elements as they are created. Therefore if you bind to :input and then add an input to the DOM, that bind method is not attached to the new input. You'd then need to explicitly un-bind and then re-bind to all elements in the DOM (otherwise you'll end up with binds being duplicated). This process would need to be repeated each time an input was added to the DOM.

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

<form action="portfolio.html">
 <button type="link" class="btn btn-primary btn-lg">View Work</button>
</form>

I just figured this out, and it links perfectly to another page without having my default link settings over ride my button classes! :)

Scala vs. Groovy vs. Clojure

Groovy is a dynamically typed language, whose syntax is very close to Java, with a number of syntax improvements that allow for lighter code and less boilerplate. It can run through an interpreter as well as being compiled, which makes it good for fast prototyping, scripts, and learning dynamic languages without having to learn a new syntax (assuming you know Java). As of Groovy 2.0, it also has growing support for static compilation. Groovy supports closures and has support for programming in a somewhat functional style, although it's still fairly far from the traditional definition of functional programming.

Clojure is a dialect of Lisp with a few advanced features like Software Transactional Memory. If you like Lisp and would like to use something like it under the JVM, Clojure is for you. It's possibly the most functional language running on the JVM, and certainly the most famous one. Also, it has a stronger emphasis on immutability than other Lisp dialects, which takes it closer to the heart of functional language enthusiasts.

Scala is a fully object oriented language, more so than Java, with one of the most advanced type systems available on non-research languages, and certainly the most advanced type system on the JVM. It also combines many concepts and features of functional languages, without compromising the object orientation, but its compromise on functional language characteristics put off some enthusiasts of the latter.

Groovy has good acceptance and a popular web framework in Grails. It also powers the Gradle build system, which is becoming a popular alternative to Maven. I personally think it is a language with limited utility, particularly as Jython and JRuby start making inroads on the JVM-land, compared to the others.

Clojure, even discounting some very interesting features, has a strong appeal just by being a Lisp dialect on JVM. It might limit its popularity, granted, but I expect it will have loyal community around it for a long time.

Scala can compete directly with Java, and give it a run for its money on almost all aspects. It can't compete in popularity at the moment, of course, and the lack of a strong corporate backing may hinder its acceptance on corporate environments. It's also a much more dynamic language than Java, in the sense of how the language evolves. From the perspective of the language, that's a good thing. From the perspective of users who plan on having thousands of lines of code written in it, not so.

As a final disclosure, I'm very familiar with Scala, and only acquainted with the other two.

How to verify static void method has been called with power mockito

If you are mocking the behavior (with something like doNothing()) there should really be no need to call to verify*(). That said, here's my stab at re-writing your test method:

@PrepareForTest({InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest { //Note the renaming of the test class.
   public void testProcessOrder() {
        //Variables
        InternalService is = new InternalService();
        Order order = mock(Order.class);

        //Mock Behavior
        when(order.isSuccessful()).thenReturn(true);
        mockStatic(Internalutils.class);
        doNothing().when(InternalUtils.class); //This is the preferred way
                                               //to mock static void methods.
        InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());

        //Execute
        is.processOrder(order);            

        //Verify
        verifyStatic(InternalUtils.class); //Similar to how you mock static methods
                                           //this is how you verify them.
        InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
   }
}

I grouped into four sections to better highlight what is going on:

1. Variables

I choose to declare any instance variables / method arguments / mock collaborators here. If it is something used in multiple tests, consider making it an instance variable of the test class.

2. Mock Behavior

This is where you define the behavior of all of your mocks. You're setting up return values and expectations here, prior to executing the code under test. Generally speaking, if you set the mock behavior here you wouldn't need to verify the behavior later.

3. Execute

Nothing fancy here; this just kicks off the code being tested. I like to give it its own section to call attention to it.

4. Verify

This is when you call any method starting with verify or assert. After the test is over, you check that the things you wanted to have happen actually did happen. That is the biggest mistake I see with your test method; you attempted to verify the method call before it was ever given a chance to run. Second to that is you never specified which static method you wanted to verify.

Additional Notes

This is mostly personal preference on my part. There is a certain order you need to do things in but within each grouping there is a little wiggle room. This helps me quickly separate out what is happening where.

I also highly recommend going through the examples at the following sites as they are very robust and can help with the majority of the cases you'll need:

JavaScript closure inside loops – simple practical example

After reading through various solutions, I'd like to add that the reason those solutions work is to rely on the concept of scope chain. It's the way JavaScript resolve a variable during execution.

  • Each function definition forms a scope consisting of all the local variables declared by var and its arguments.
  • If we have inner function defined inside another (outer) function, this forms a chain, and will be used during execution
  • When a function gets executed, the runtime evaluates variables by searching the scope chain. If a variable can be found in a certain point of the chain it will stop searching and use it, otherwise it continues until the global scope reached which belongs to window.

In the initial code:

funcs = {};
for (var i = 0; i < 3; i++) {         
  funcs[i] = function inner() {        // function inner's scope contains nothing
    console.log("My value: " + i);    
  };
}
console.log(window.i)                  // test value 'i', print 3

When funcs gets executed, the scope chain will be function inner -> global. Since the variable i cannot be found in function inner (neither declared using var nor passed as arguments), it continues to search, until the value of i is eventually found in the global scope which is window.i.

By wrapping it in an outer function either explicitly define a helper function like harto did or use an anonymous function like Bjorn did:

funcs = {};
function outer(i) {              // function outer's scope contains 'i'
  return function inner() {      // function inner, closure created
   console.log("My value: " + i);
  };
}
for (var i = 0; i < 3; i++) {
  funcs[i] = outer(i);
}
console.log(window.i)          // print 3 still

When funcs gets executed, now the scope chain will be function inner -> function outer. This time i can be found in the outer function's scope which is executed 3 times in the for loop, each time has value i bound correctly. It won't use the value of window.i when inner executed.

More detail can be found here
It includes the common mistake in creating closure in the loop as what we have here, as well as why we need closure and the performance consideration.

Jquery Ajax beforeSend and success,error & complete

Maybe you can try the following :

var i = 0;
function AjaxSendForm(url, placeholder, form, append) {
var data = $(form).serialize();
append = (append === undefined ? false : true); // whatever, it will evaluate to true or false only
$.ajax({
    type: 'POST',
    url: url,
    data: data,
    beforeSend: function() {
        // setting a timeout
        $(placeholder).addClass('loading');
        i++;
    },
    success: function(data) {
        if (append) {
            $(placeholder).append(data);
        } else {
            $(placeholder).html(data);
        }
    },
    error: function(xhr) { // if error occured
        alert("Error occured.please try again");
        $(placeholder).append(xhr.statusText + xhr.responseText);
        $(placeholder).removeClass('loading');
    },
    complete: function() {
        i--;
        if (i <= 0) {
            $(placeholder).removeClass('loading');
        }
    },
    dataType: 'html'
});
}

This way, if the beforeSend statement is called before the complete statement i will be greater than 0 so it will not remove the class. Then only the last call will be able to remove it.

I cannot test it, let me know if it works or not.

how to call an ASP.NET c# method using javascript

I'm going to go right ahead and offer a solution using jQuery, which means you will need to import the library if you haven't already...

Import the jQuery library in your page mark-up:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>

Then create another *.js script file (I call mine ExecutePageMethod, since that is the only method it is going to expose) and import it:

<script type="text/javascript" src="/ExecutePageMethod.js" ></script>

Within the newly added file, add the following code (I remember pulling this from elsewhere, so someone else deserves credit for it really):

function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) {
    var paramList = '';
    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    $.ajax({
        type: "POST",
        url: page + "/" + fn,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "json",
        success: successFn,
        error: errorFn
    });
}

You will then need to augment your .NET page method with the appropriate attributes, as such:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string MyMethod()
{
    return "Yay!";
}

Now, within your page mark-up, within a script block or from another script file, you can call the method, like so:

ExecutePageMethod("PageName.aspx", "MyMethod", [], OnSuccess, OnFailure);

Obviously you will need to implement the OnSuccess and OnFailure methods.

To consume the results, say in the OnSuccess method, you can use the parseJSON method, which, if the results become more complex (in the case or returning an array of types, for instance) this method will parse it into objects:

function OnSuccess(result) {
    var parsedResult = jQuery.parseJSON(result.d);
}

This ExecutePageMethod code is particularly useful since it it reusable, so rather than having to manage an $.ajax call for each page method you might want to execute, you just need to pass the page, method name and arguments to this method.

Gradient of n colors ranging from color 1 and color 2

Just to expand on the previous answer colorRampPalettecan handle more than two colors.

So for a more expanded "heat map" type look you can....

colfunc<-colorRampPalette(c("red","yellow","springgreen","royalblue"))
plot(rep(1,50),col=(colfunc(50)), pch=19,cex=2)

The resulting image:

enter image description here

How can I stop .gitignore from appearing in the list of untracked files?

After you add the .gitignore file and commit it, it will no longer show up in the "untracked files" list.

git add .gitignore
git commit -m "add .gitignore file"
git status

How to justify a single flexbox item (override justify-content)

To expand on Pavlo's answer https://stackoverflow.com/a/34063808/1069914, you can have multiple child items justify-content: flex-start in their behavior but have the last item justify-content: flex-end

_x000D_
_x000D_
.container {
  height: 100px;
  border: solid 10px skyblue;
  display: flex;
  justify-content: flex-end;
}

.container > *:not(:last-child) {
    margin-right: 0;
    margin-left: 0;
}

/* set the second to last-child */
.container > :nth-last-child(2) {
    margin-right: auto;
    margin-left: 0;
}

.block {
  width: 50px;
  background: tomato;
  border: 1px solid black;
}
_x000D_
<div class="container">
    <div class="block"></div>
    <div class="block"></div>
    <div class="block"></div>
    <div class="block" style="width:150px">I should be at the end of the flex container (i.e. justify-content: flex-end)</div>
</div>
_x000D_
_x000D_
_x000D_

How can I catch a ctrl-c event?

signal isn't the most reliable way as it differs in implementations. I would recommend using sigaction. Tom's code would now look like this :

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

void my_handler(int s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{

   struct sigaction sigIntHandler;

   sigIntHandler.sa_handler = my_handler;
   sigemptyset(&sigIntHandler.sa_mask);
   sigIntHandler.sa_flags = 0;

   sigaction(SIGINT, &sigIntHandler, NULL);

   pause();

   return 0;    
}

assignment operator overloading in c++

Under the circumstances, you're almost certainly better off skipping the check for self-assignment -- when you're only assigning one member that seems to be a simple type (probably a double), it's generally faster to do that assignment than avoid it, so you'd end up with:

SimpleCircle & SimpleCircle::operator=(const SimpleCircle & rhs)
{
    itsRadius = rhs.getRadius(); // or just `itsRadius = rhs.itsRadius;`
    return *this;
}

I realize that many older and/or lower quality books advise checking for self assignment. At least in my experience, however, it's sufficiently rare that you're better off without it (and if the operator depends on it for correctness, it's almost certainly not exception safe).

As an aside, I'd note that to define a circle, you generally need a center and a radius, and when you copy or assign, you want to copy/assign both.

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

Use Query.setParameterList(), Javadoc here.

There are four variants to pick from.

Rounded corners for <input type='text' /> using border-radius.htc for IE

W3C doc says regarding "border-radius" property: "supported in IE9+, Firefox, Chrome, Safari, and Opera".

Hence I assume you're testing on IE8 or below.

For "regular elements" there is a solution compatible with IE8 & other old/poor browsers. See below.

HTML:

<div class="myWickedClass">
  <span class="myCoolItem">Some text</span> <span class="myCoolItem">Some text</span> <span class="myCoolItem"> Some text</span> <span class="myCoolItem">Some text</span>
</div>

CSS:

.myWickedClass{
  padding: 0 5px 0 0;
  background: #F7D358 url(../img/roundedCorner_right.png) top right no-repeat scroll;
  -moz-border-radius: 10px;
  -webkit-border-radius: 10px;
  border-radius: 10px;
  font: normal 11px Verdana, Helvetica, sans-serif;
  color: #A4A4A4;
}
.myWickedClass > .myCoolItem:first-child {
  padding-left: 6px;
  background: #F7D358 url(../img/roundedCorner_left.png) 0px 0px no-repeat scroll;
}
.myWickedClass > .myCoolItem {
  padding-right: 5px;
}

You need to create both roundedCorner_right.png & roundedCorner_left.png. These are work around for IE8 (& below) to fake the rounded corner feature.

So in this example above we apply the left rounded corner to the first span element in the containing div, & we apply the right rounded corner to the containing div. These images overlap the browser-provided "squary corners" & give the illusion of being part of a rounded element.

The idea for inputs would be to do the same logic. However, input is an empty element, " element is empty, it contains attributes only", in other word, you cannot wrap a span into an input such as <input><span class="myCoolItem"></span></input> to then use background images like in the previous example.

Hence the solution seems to be to do the opposite: wrap the input into another element. see this answer rounded corners of input elements in IE

What is a predicate in c#?

The Predicate will always return a boolean, by definition.

Predicate<T> is basically identical to Func<T,bool>.

Predicates are very useful in programming. They are often used to allow you to provide logic at runtime, that can be as simple or as complicated as necessary.

For example, WPF uses a Predicate<T> as input for Filtering of a ListView's ICollectionView. This lets you write logic that can return a boolean determining whether a specific element should be included in the final view. The logic can be very simple (just return a boolean on the object) or very complex, all up to you.

Excel VBA to Export Selected Sheets to PDF

Once you have Selected a group of sheets, you can use Selection

Consider:

Sub luxation()
    ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
    Selection.ExportAsFixedFormat _
        Type:=xlTypePDF, _
        Filename:="C:\TestFolder\temp.pdf", _
        Quality:=xlQualityStandard, _
        IncludeDocProperties:=True, _
        IgnorePrintAreas:=False, _
        OpenAfterPublish:=True
End Sub

EDIT#1:

Further testing has reveled that this technique depends on the group of cells selected on each worksheet. To get a comprehensive output, use something like:

Sub Macro1()

   Sheets("Sheet1").Activate
   ActiveSheet.UsedRange.Select
   Sheets("Sheet2").Activate
   ActiveSheet.UsedRange.Select
   Sheets("Sheet3").Activate
   ActiveSheet.UsedRange.Select

   ThisWorkbook.Sheets(Array("Sheet1", "Sheet2", "Sheet3")).Select
   Selection.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
      "C:\Users\James\Desktop\pdfmaker.pdf", Quality:=xlQualityStandard, _
      IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:= _
      True
End Sub