Programs & Examples On #Wcfserviceclient

What is the best workaround for the WCF client `using` block issue?

Override the client's Dispose() without the need to generate a proxy class based on ClientBase, also without the need to manage channel creation and caching! (Note that WcfClient is not an ABSTRACT class and is based on ClientBase)

// No need for a generated proxy class
//using (WcfClient<IOrderService> orderService = new WcfClient<IOrderService>())
//{
//    results = orderService.GetProxy().PlaceOrder(input);
//}

public class WcfClient<TService> : ClientBase<TService>, IDisposable
    where TService : class
{
    public WcfClient()
    {
    }

    public WcfClient(string endpointConfigurationName) :
        base(endpointConfigurationName)
    {
    }

    public WcfClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress)
    {
    }

    public WcfClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress)
    {
    }

    public WcfClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
        base(binding, remoteAddress)
    {
    }

    protected virtual void OnDispose()
    {
        bool success = false;

        if ((base.Channel as IClientChannel) != null)
        {
            try
            {
                if ((base.Channel as IClientChannel).State != CommunicationState.Faulted)
                {
                    (base.Channel as IClientChannel).Close();
                    success = true;
                }
            }
            finally
            {
                if (!success)
                {
                    (base.Channel as IClientChannel).Abort();
                }
            }
        }
    }

    public TService GetProxy()
    {
        return this.Channel as TService;
    }

    public void Dispose()
    {
        OnDispose();
    }
}

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

The formatting can be done like this (I assumed you meant HH:MM instead of HH:SS, but it's easy to change):

Time.now.strftime("%d/%m/%Y %H:%M")
#=> "14/09/2011 14:09"

Updated for the shifting:

d = DateTime.now
d.strftime("%d/%m/%Y %H:%M")
#=> "11/06/2017 18:11"
d.next_month.strftime("%d/%m/%Y %H:%M")
#=> "11/07/2017 18:11"

You need to require 'date' for this btw.

Converting bytes to megabytes

BTW: Hard drive manufacturers don't count as authorities on this one!

Oh, yes they do (and the definition they assume from the S.I. is the correct one). On a related issue, see this post on CodingHorror.

jQuery.animate() with css class only, without explicit styles

Check out James Padolsey's animateToSelector

Intro: This jQuery plugin will allow you to animate any element to styles specified in your stylesheet. All you have to do is pass a selector and the plugin will look for that selector in your StyleSheet and will then apply it as an animation.

MySQL: How to reset or change the MySQL root password?

This solution belongs to the previous version of MySQL. By logging in to MySQL using socket authentication, you can do it.

sudo mysql -u root

Then the following command could be run.

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

Details are available here .

Is there a way to use max-width and height for a background image?

You can do this with background-size:

html {
    background: url(images/bg.jpg) no-repeat center center fixed; 
    background-size: cover;
}

There are a lot of values other than cover that you can set background-size to, see which one works for you: https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

Spec: https://www.w3.org/TR/css-backgrounds-3/#the-background-size

It works in all modern browsers: http://caniuse.com/#feat=background-img-opts

How to export a table dataframe in PySpark to csv?

If you cannot use spark-csv, you can do the following:

df.rdd.map(lambda x: ",".join(map(str, x))).coalesce(1).saveAsTextFile("file.csv")

If you need to handle strings with linebreaks or comma that will not work. Use this:

import csv
import cStringIO

def row2csv(row):
    buffer = cStringIO.StringIO()
    writer = csv.writer(buffer)
    writer.writerow([str(s).encode("utf-8") for s in row])
    buffer.seek(0)
    return buffer.read().strip()

df.rdd.map(row2csv).coalesce(1).saveAsTextFile("file.csv")

UTF-8 output from PowerShell

This is a bug in .NET. When PowerShell launches, it caches the output handle (Console.Out). The Encoding property of that text writer does not pick up the value StandardOutputEncoding property.

When you change it from within PowerShell, the Encoding property of the cached output writer returns the cached value, so the output is still encoded with the default encoding.

As a workaround, I would suggest not changing the encoding. It will be returned to you as a Unicode string, at which point you can manage the encoding yourself.

Caching example:

102 [C:\Users\leeholm]
>> $r1 = [Console]::Out

103 [C:\Users\leeholm]
>> $r1

Encoding                                          FormatProvider
--------                                          --------------
System.Text.SBCSCodePageEncoding                  en-US



104 [C:\Users\leeholm]
>> [Console]::OutputEncoding = [System.Text.Encoding]::UTF8

105 [C:\Users\leeholm]
>> $r1

Encoding                                          FormatProvider
--------                                          --------------
System.Text.SBCSCodePageEncoding                  en-US

Tool to compare directories (Windows 7)

The tool that richardtz suggests is excellent.

Another one that is amazing and comes with a 30 day free trial is Araxis Merge. This one does a 3 way merge and is much more feature complete than winmerge, but it is a commercial product.

You might also like to check out Scott Hanselman's developer tool list, which mentions a couple more in addition to winmerge

Java Delegates?

The code described offers many of the advantages of C# delegates. Methods, either static or dynamic, can be treated in a uniform manner. The complexity in calling methods through reflection is reduced and the code is reusable, in the sense of requiring no additional classes in the user code. Note we are calling an alternate convenience version of invoke, where a method with one parameter can be called without creating an object array.Java code below:

  class Class1 {
        public void show(String s) { System.out.println(s); }
    }

    class Class2 {
        public void display(String s) { System.out.println(s); }
    }

    // allows static method as well
    class Class3 {
        public static void staticDisplay(String s) { System.out.println(s); }
    }

    public class TestDelegate  {
        public static final Class[] OUTPUT_ARGS = { String.class };
        public final Delegator DO_SHOW = new Delegator(OUTPUT_ARGS,Void.TYPE);

        public void main(String[] args)  {
            Delegate[] items = new Delegate[3];

            items[0] = DO_SHOW .build(new Class1(),"show,);
            items[1] = DO_SHOW.build (new Class2(),"display");
            items[2] = DO_SHOW.build(Class3.class, "staticDisplay");

            for(int i = 0; i < items.length; i++) {
                items[i].invoke("Hello World");
            }
        }
    }

The module ".dll" was loaded but the entry-point was not found

I had this problem and

dumpbin /exports mydll.dll

and

depends mydll.dll

showed 'DllRegisterServer'.

The problem was that there was another DLL in the system that had the same name. After renaming mydll the registration succeeded.

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

The problem is that the CASE statement won't work in the way you're trying to use it. You can only use it to switch the value of one field in a query. If I understand what you're trying to do, you might need this:

SELECT 
   ActivityID,
   FieldName = CASE 
                  WHEN ActivityTypeID <> 2 THEN
                      (Some Aggregate Sub Query)
                  ELSE
                     (Some Aggregate Sub Query with diff result)
               END,
   FieldName2 = CASE
                  WHEN ActivityTypeID <> 2 THEN
                      (Some Aggregate Sub Query)
                  ELSE
                     (Some Aggregate Sub Query with diff result)
               END

Deserialize json object into dynamic object using Json.net

If you use JSON.NET with old version which didn't JObject.

This is another simple way to make a dynamic object from JSON: https://github.com/chsword/jdynamic

NuGet Install

PM> Install-Package JDynamic

Support using string index to access member like:

dynamic json = new JDynamic("{a:{a:1}}");
Assert.AreEqual(1, json["a"]["a"]);

Test Case

And you can use this util as following :

Get the value directly

dynamic json = new JDynamic("1");

//json.Value

2.Get the member in the json object

dynamic json = new JDynamic("{a:'abc'}");
//json.a is a string "abc"

dynamic json = new JDynamic("{a:3.1416}");
//json.a is 3.1416m

dynamic json = new JDynamic("{a:1}");
//json.a is integer: 1

3.IEnumerable

dynamic json = new JDynamic("[1,2,3]");
/json.Length/json.Count is 3
//And you can use json[0]/ json[2] to get the elements

dynamic json = new JDynamic("{a:[1,2,3]}");
//json.a.Length /json.a.Count is 3.
//And you can use  json.a[0]/ json.a[2] to get the elements

dynamic json = new JDynamic("[{b:1},{c:1}]");
//json.Length/json.Count is 2.
//And you can use the  json[0].b/json[1].c to get the num.

Other

dynamic json = new JDynamic("{a:{a:1} }");

//json.a.a is 1.

The maximum value for an int type in Go

A lightweight package contains them (as well as other int types limits and some widely used integer functions):

import (
    "fmt"
    "<Full URL>/go-imath/ix"
    "<Full URL>/go-imath/ux"
)
...
fmt.Println(ix.Minimal) // Output: -2147483648 (32-bit) or -9223372036854775808 (64-bit)
fmt.Println(ix.Maximal) // Output: 2147483647 or 9223372036854775807
fmt.Println(ux.Minimal) // Output: 0
fmt.Println(ux.Maximal) // Output: 4294967295 or 18446744073709551615

how to get data from selected row from datagridview

To get the cell value, you need to read it directly from DataGridView1 using e.RowIndex and e.ColumnIndex properties.

Eg:

Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
   Dim value As Object = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value

   If IsDBNull(value) Then 
      TextBox1.Text = "" ' blank if dbnull values
   Else
      TextBox1.Text = CType(value, String)
   End If
End Sub

How to check for empty array in vba macro

You can check if the array is empty by retrieving total elements count using JScript's VBArray() object (works with arrays of variant type, single or multidimensional):

Sub Test()

    Dim a() As Variant
    Dim b As Variant
    Dim c As Long

    ' Uninitialized array of variant
    ' MsgBox UBound(a) ' gives 'Subscript out of range' error
    MsgBox GetElementsCount(a) ' 0

    ' Variant containing an empty array
    b = Array()
    MsgBox GetElementsCount(b) ' 0

    ' Any other types, eg Long or not Variant type arrays
    MsgBox GetElementsCount(c) ' -1

End Sub

Function GetElementsCount(aSample) As Long

    Static oHtmlfile As Object ' instantiate once

    If oHtmlfile Is Nothing Then
        Set oHtmlfile = CreateObject("htmlfile")
        oHtmlfile.parentWindow.execScript ("function arrlength(arr) {try {return (new VBArray(arr)).toArray().length} catch(e) {return -1}}"), "jscript"
    End If
    GetElementsCount = oHtmlfile.parentWindow.arrlength(aSample)

End Function

For me it takes about 0.3 mksec for each element + 15 msec initialization, so the array of 10M elements takes about 3 sec. The same functionality could be implemented via ScriptControl ActiveX (it is not available in 64-bit MS Office versions, so you can use workaround like this).

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

You can check shouldShowRequestPermissionRationale() in your onRequestPermissionsResult().

shouldShowRequestPermissionRationale https://youtu.be/C8lUdPVSzDk?t=2m23s

Check whether permission was granted or not in onRequestPermissionsResult(). If not then check shouldShowRequestPermissionRationale().

  1. If this method returns true then show an explanation that why this particular permission is needed. Then depending on user's choice again requestPermissions().
  2. If it returns false then show an error message that permission was not granted and app cannot proceed further or a particular feature is disabled.

Below is sample code.

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    switch (requestCode) {
        case STORAGE_PERMISSION_REQUEST:
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission was granted :)
                downloadFile();
            } else {
                // permission was not granted
                if (getActivity() == null) {
                    return;
                }
                if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    showStoragePermissionRationale();
                } else {
                    Snackbar snackbar = Snackbar.make(getView(), getResources().getString(R.string.message_no_storage_permission_snackbar), Snackbar.LENGTH_LONG);
                    snackbar.setAction(getResources().getString(R.string.settings), new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (getActivity() == null) {
                                return;
                            }
                            Intent intent = new Intent();
                            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                            intent.setData(uri);
                            OrderDetailFragment.this.startActivity(intent);
                        }
                    });
                    snackbar.show();
                }
            }
            break;
    }
}

Apparently, google maps does exactly this for location permission.

Bootstrap change carousel height

From Bootstrap 4

.carousel-item{
    height: 200px;
} 
.carousel-item img{
    height: 200px;
}

Select distinct values from a table field

By example:

# select distinct code from Platform where id in ( select platform__id from Build where product=p)
pl_ids = Build.objects.values('platform__id').filter(product=p)
platforms = Platform.objects.values_list('code', flat=True).filter(id__in=pl_ids).distinct('code')
platforms = list(platforms) if platforms else []

PHP memcached Fatal error: Class 'Memcache' not found

I went into wp-config/ and deleted the object-cache.php and advanced-cache.php and it worked fine for me.

Encrypt and decrypt a password in Java

EDIT : this answer is old. Usage of MD5 is now discouraged as it can easily be broken.


MD5 must be good enough for you I imagine? You can achieve it with MessageDigest.

MessageDigest.getInstance("MD5");

There are also other algorithms listed here.

And here's an third party version of it, if you really want: Fast MD5

Does the Java &= operator apply & or &&?

It's the last one:

a = a & b;

How to define a default value for "input type=text" without using attribute 'value'?

this is working for me

<input defaultValue="1000" type="text" />

or

let x = document.getElementById("myText").defaultValue; 

SQL Error with Order By in Subquery

If you're working with SQL Server 2012 or later, this is now easy to fix. Add an offset 0 rows:

SELECT (
  SELECT
  COUNT(1) FROM Seanslar WHERE MONTH(tarihi) = 4
  GROUP BY refKlinik_id
  ORDER BY refKlinik_id OFFSET 0 ROWS
) as dorduncuay

How to run the sftp command with a password from Bash script?

EXPECT is a great program to use.

On Ubuntu install it with:

sudo apt-get install expect

On a CentOS Machine install it with:

yum install expect

Lets say you want to make a connection to a sftp server and then upload a local file from your local machine to the remote sftp server

#!/usr/bin/expect

spawn sftp [email protected]
expect "password:"
send "yourpasswordhere\n"
expect "sftp>"
send "cd logdirectory\n"
expect "sftp>"
send "put /var/log/file.log\n"
expect "sftp>"
send "exit\n"
interact

This opens a sftp connection with your password to the server.

Then it goes to the directory where you want to upload your file, in this case "logdirectory"

This uploads a log file from the local directory found at /var/log/ with the files name being file.log to the "logdirectory" on the remote server

How to use SortedMap interface in Java?

TreeMap sorts by the key natural ordering. The keys should implement Comparable or be compatible with a Comparator (if you passed one instance to constructor). In you case, Float already implements Comparable so you don't have to do anything special.

You can call keySet to retrieve all the keys in ascending order.

Django template how to look up a dictionary value with a variable

Write a custom template filter:

from django.template.defaulttags import register
...
@register.filter
def get_item(dictionary, key):
    return dictionary.get(key)

(I use .get so that if the key is absent, it returns none. If you do dictionary[key] it will raise a KeyError then.)

usage:

{{ mydict|get_item:item.NAME }}

Convert generic List/Enumerable to DataTable?

To Convert Generic list into DataTable

using Newtonsoft.Json;

public DataTable GenericToDataTable(IList<T> list)
{
    var json = JsonConvert.SerializeObject(list);
    DataTable dt = (DataTable)JsonConvert.DeserializeObject(json, (typeof(DataTable)));
    return dt;
}

Access-Control-Allow-Origin: * in tomcat

At the time of writing this, the current version of Tomcat 7 (7.0.41) has a built-in CORS filter http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#CORS_Filter

CSS: Set Div height to 100% - Pixels

The best way to do this is to use view port styles. It just does the work and no other techniques needed.

Code:

_x000D_
_x000D_
div{_x000D_
  height:100vh;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

Turning off some legends in a ggplot

You can use guide=FALSE in scale_..._...() to suppress legend.

For your example you should use scale_colour_continuous() because length is continuous variable (not discrete).

(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
   scale_colour_continuous(guide = FALSE) +
   geom_point()
)

Or using function guides() you should set FALSE for that element/aesthetic that you don't want to appear as legend, for example, fill, shape, colour.

p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
  geom_point()    
p0+guides(colour=FALSE)

UPDATE

Both provided solutions work in new ggplot2 version 2.0.0 but movies dataset is no longer present in this library. Instead you have to use new package ggplot2movies to check those solutions.

library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

This happened for me when I tried installing my app on a new device. I solved it by selecting Automatic for all of my Provisioning Profiles. After doing that and trying to install again, it now let me know that I just needed to add this new device to my profile, and gave me a Fix Issue button, which solved it.

E: Unable to locate package npm

Your system can't find npm package because you haven't add nodejs repository to your system..

Try follow this installation step:
Add nodejs PPA repository to our system and python software properties too

sudo apt-get install curl python-software-properties 
// sudo apt-get install curl software-properties-common

curl -sL https://deb.nodesource.com/setup_10.x | sudo bash -
sudo apt-get update

Then install npm

sudo apt-get install nodejs

Check if npm and node was installed and you're ready to use node.js

node -v
npm -v

If someone was failed to install nodejs.. Try remove the npm first, maybe the old installation was broken..

sudo apt-get remove nodejs
sudo apt-get remove npm

Check if npm or node folder still exist, delete it if you found them

which node
which npm

How to set an environment variable in a running docker container

here is how to update a docker container config permanently

  1. stop container: docker stop <container name>
  2. edit container config: docker run -it -v /var/lib/docker:/var/lib/docker alpine vi $(docker inspect --format='/var/lib/docker/containers/{{.Id}}/config.v2.json' <container name>)
  3. restart docker

Server did not recognize the value of HTTP Header SOAPAction

While calling the .asmx / wcf web service please take care of below points:

  1. The namespace is case sensitive,the SOAP request MUST be sent with the same namespace with which the WebService is declared.

e.g. For the WebService declared as below

[WebService(Namespace = "http://MyDomain.com/TestService")] 
public class FooClass : System.Web.Services.WebService 
{
   [WebMethod]   
    public bool Foo( string name)    
     {

      ...... 
     }

 }

The SOAP request must maintain the same case for namespace while calling.Sometime we overlook the case sensitivity.

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
     <Foo xmlns="http://MyDomain.com/TestService">
     <name>string</name>      
     </Foo>
  </soap:Body> 
</soap:Envelope>
  1. The namespace need not be same as hosted url of the service.The namespace can be any string.

e.g. Above service may be hosted at http://84.23.9.65/MyTestService , but still while invoking the Web Service from client the namespace should be the same which the serice class is having i.e.http://MyDomain.com/TestService

How to write connection string in web.config file and read from it?

Try this After open web.config file in application and add sample db connection in connectionStrings section like this

<connectionStrings>
<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient"/>
</connectionStrings >

Regex to test if string begins with http:// or https://

This will work for URL encoded strings too.

^(https?)(:\/\/|(\%3A%2F%2F))

What's the simplest way to print a Java array?

Different Ways to Print Arrays in Java:

  1. Simple Way

    List<String> list = new ArrayList<String>();
    list.add("One");
    list.add("Two");
    list.add("Three");
    list.add("Four");
    // Print the list in console
    System.out.println(list);
    

Output: [One, Two, Three, Four]

  1. Using toString()

    String[] array = new String[] { "One", "Two", "Three", "Four" };
    System.out.println(Arrays.toString(array));
    

Output: [One, Two, Three, Four]

  1. Printing Array of Arrays

    String[] arr1 = new String[] { "Fifth", "Sixth" };
    String[] arr2 = new String[] { "Seventh", "Eight" };
    String[][] arrayOfArray = new String[][] { arr1, arr2 };
    System.out.println(arrayOfArray);
    System.out.println(Arrays.toString(arrayOfArray));
    System.out.println(Arrays.deepToString(arrayOfArray));
    

Output: [[Ljava.lang.String;@1ad086a [[Ljava.lang.String;@10385c1, [Ljava.lang.String;@42719c] [[Fifth, Sixth], [Seventh, Eighth]]

Resource: Access An Array

How to create a button programmatically?

    // UILabel:
    let label = UILabel()
    label.frame = CGRectMake(35, 100, 250, 30)
    label.textColor = UIColor.blackColor()
    label.textAlignment = NSTextAlignment.Center
    label.text = "Hello World"
    self.view.addSubview(label)

    // UIButton:
    let btn: UIButton = UIButton(type: UIButtonType.Custom) as UIButton
    btn.frame = CGRectMake(130, 70, 60, 20)
    btn.setTitle("Click", forState: UIControlState.Normal)
    btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
    btn.addTarget(self, action:Selector("clickAction"), forControlEvents: UIControlEvents.TouchUpInside)
    view.addSubview(btn)


    // Button Action:
    @IBAction func clickAction(sender:AnyObject)
    {
        print("Click Action")
    }

How to resolve conflicts in EGit

Just right click on a conflicting file and add it to the index after resolving conflicts.

How to use Bootstrap 4 in ASP.NET Core

Unfortunately, you're going to have a hard time using NuGet to install Bootstrap (or most other JavaScript/CSS frameworks) on a .NET Core project. If you look at the NuGet install it tells you it is incompatible:

enter image description here

if you must know where local packages dependencies are, they are now in your local profile directory. i.e. %userprofile%\.nuget\packages\bootstrap\4.0.0\content\Scripts.

However, I suggest switching to npm, or bower - like in Saineshwar's answer.

Compare 2 arrays which returns difference

The short version can be like this:

const diff = (a, b) => b.filter((i) => a.indexOf(i) === -1);

result:

diff(['a', 'b'], ['a', 'b', 'c', 'd']);

["c", "d"]

No suitable driver found for 'jdbc:mysql://localhost:3306/mysql

Just telling my resolution: in my case, the libraries and projects weren't being added automatically to the classpath (i don't know why), even clicking at the "add to build path" option. So I went on run -> run configurations -> classpath and added everything I needed through there.

React-Redux: Actions must be plain objects. Use custom middleware for async actions

Action Definition

const selectSlice = () => {
  return {
    type: 'SELECT_SLICE'
  }
};

Action Dispatch

store.dispatch({
  type:'SELECT_SLICE'
});

Make sure the object structure of action defined is same as action dispatched. In my case, while dispatching action, type was not assigned to property type.

CardView background color always white

You can use

app:cardBackgroundColor="@color/red"

or

android:backgroundTint="@color/red"

How to set Android camera orientation properly?

This solution will work for all versions of Android. You can use reflection in Java to make it work for all Android devices:

Basically you should create a reflection wrapper to call the Android 2.2 setDisplayOrientation, instead of calling the specific method.

The method:

    protected void setDisplayOrientation(Camera camera, int angle){
    Method downPolymorphic;
    try
    {
        downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
        if (downPolymorphic != null)
            downPolymorphic.invoke(camera, new Object[] { angle });
    }
    catch (Exception e1)
    {
    }
}

And instead of using camera.setDisplayOrientation(x) use setDisplayOrientation(camera, x) :

    if (Integer.parseInt(Build.VERSION.SDK) >= 8)
        setDisplayOrientation(mCamera, 90);
    else
    {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
        {
            p.set("orientation", "portrait");
            p.set("rotation", 90);
        }
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
        {
            p.set("orientation", "landscape");
            p.set("rotation", 90);
        }
    }   

Saving and loading objects and using pickle

As for your second problem:

 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "C:\Python31\lib\pickle.py", line
 1365, in load encoding=encoding,
 errors=errors).load() EOFError

After you have read the contents of the file, the file pointer will be at the end of the file - there will be no further data to read. You have to rewind the file so that it will be read from the beginning again:

file.seek(0)

What you usually want to do though, is to use a context manager to open the file and read data from it. This way, the file will be automatically closed after the block finishes executing, which will also help you organize your file operations into meaningful chunks.

Finally, cPickle is a faster implementation of the pickle module in C. So:

In [1]: import _pickle as cPickle

In [2]: d = {"a": 1, "b": 2}

In [4]: with open(r"someobject.pickle", "wb") as output_file:
   ...:     cPickle.dump(d, output_file)
   ...:

# pickle_file will be closed at this point, preventing your from accessing it any further

In [5]: with open(r"someobject.pickle", "rb") as input_file:
   ...:     e = cPickle.load(input_file)
   ...:

In [7]: print e
------> print(e)
{'a': 1, 'b': 2}

Changing MongoDB data store directory

Create a file called mongod.cfg in MongoDB folder if you dont have it. In my case: C:\Users\ivanbtrujillo\MongoDB

Then, edit mongod.cfg with notepad and add a line with the following (our custom dbpath):

dbpath=C:\Users\ivanbtrujillo\MongoDB\data\db

In this file you should especify the logpath too. My mongod.cfg file is:

logpath=C:\Users\ivanbtrujillo\MongoDB\log\mongo.log
dbpath=C:\Users\ivanbtrujillo\MongoDB\data\db

If you uses mongoDB as a windows service, you have to change this key and especify the mongod.cfg file.

To install mongodb as a windows service run this command:

**"C:\Users\ivanbtrujillo\MongoDB\bin\mongod.exe" --config "C:\Users\ivanbtrujillo\MongoDB\mongod.cfg" –install**

Open regedit.exe and go to the following route:

HKEYLOCALMACHINE\SYSTEM\CurrentControlSet\services\MongoDB

MongoDB service does not work, we have to edit the ImagePath key, delete its content and put the following:

**"C:\Users\ivanbtrujillo\MongoDB\bin\mongod.exe" --config "C:\Users\ivanbtrujillo\MongoDB\mongod.cfg" 
--logpath="C:\Users\ivanbtrujillo\MongoDB\log\mongo.log" –service**

We indicates to mongo it's config file and its logpath.

Then when you init the mongodb service, it works.

Here is a full tutorial to install mongoDB in windows: http://ivanbtrujillo.herokuapp.com/2014/07/24/installing-mongodb-as-a-service-windows/

Hope it helps,

How do you input command line arguments in IntelliJ IDEA?

If you are using intellij go to Run > Edit Configurations menu setting. A dialog box will appear. Now you can add arguments to the Program arguments input field.

How to subtract 2 hours from user's local time?

Subtract from another date object

var d = new Date();

d.setHours(d.getHours() - 2);

What is the difference between a var and val definition in Scala?

It's as simple as it name.

var means it can vary

val means invariable

Make multiple-select to adjust its height to fit options without scroll bar

To adjust the size (height) of all multiple selects to the number of options, use jQuery:

$('select[multiple = multiple]').each(function() {
    $(this).attr('size', $(this).find('option').length)
})

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

How do you roll back (reset) a Git repository to a particular commit?

Update:

Because of changes to how tracking branches are created and pushed I no longer recommend renaming branches. This is what I recommend now:

Make a copy of the branch at its current state:

git branch crazyexperiment

(The git branch <name> command will leave you with your current branch still checked out.)

Reset your current branch to your desired commit with git reset:

git reset --hard c2e7af2b51

(Replace c2e7af2b51 with the commit that you want to go back to.)

When you decide that your crazy experiment branch doesn't contain anything useful, you can delete it with:

git branch -D crazyexperiment

It's always nice when you're starting out with history-modifying git commands (reset, rebase) to create backup branches before you run them. Eventually once you're comfortable you won't find it necessary. If you do modify your history in a way that you don't want and haven't created a backup branch, look into git reflog. Git keeps commits around for quite a while even if there are no branches or tags pointing to them.

Original answer:

A slightly less scary way to do this than the git reset --hard method is to create a new branch. Let's assume that you're on the master branch and the commit you want to go back to is c2e7af2b51.

Rename your current master branch:

git branch -m crazyexperiment

Check out your good commit:

git checkout c2e7af2b51

Make your new master branch here:

git checkout -b master

Now you still have your crazy experiment around if you want to look at it later, but your master branch is back at your last known good point, ready to be added to. If you really want to throw away your experiment, you can use:

git branch -D crazyexperiment

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

Oracle: not a valid month

You can also change the value of this database parameter for your session by using the ALTER SESSION command and use it as you wanted

ALTER SESSION SET NLS_DATE_FORMAT = 'DD-MM-YYYY';
SELECT TO_DATE('05-12-2015') FROM dual;

05/12/2015

Content Security Policy: The page's settings blocked the loading of a resource

With my ASP.NET Core Angular project running in Visual Studio 2019, sometimes I get this error message in the Firefox console:

Content Security Policy: The page’s settings blocked the loading of a resource at inline (“default-src”).

In Chrome, the error message is instead:

Failed to load resource: the server responded with a status of 404 ()

In my case it had nothing to do with my Content Security Policy, but instead was simply the result of a TypeScript error on my part.

Check your IDE output window for a TypeScript error, like:

> ERROR in src/app/shared/models/person.model.ts(8,20): error TS2304: Cannot find name 'bool'.
>
> i ?wdm?: Failed to compile.

Note: Since this question is the first result on Google for this error message.

importing go files in same folder

No import is necessary as long as you declare both a.go and b.go to be in the same package. Then, you can use go run to recognize multiple files with:

$ go run a.go b.go

What is a race condition?

Race condition is not only related with software but also related with hardware too. Actually the term was initially coined by the hardware industry.

According to wikipedia:

The term originates with the idea of two signals racing each other to influence the output first.

Race condition in a logic circuit:

enter image description here

Software industry took this term without modification, which makes it a little bit difficult to understand.

You need to do some replacement to map it to the software world:

  • "two signals" => "two threads"/"two processes"
  • "influence the output" => "influence some shared state"

So race condition in software industry means "two threads"/"two processes" racing each other to "influence some shared state", and the final result of the shared state will depend on some subtle timing difference, which could be caused by some specific thread/process launching order, thread/process scheduling, etc.

Display HTML snippets in HTML

is there a tag for don't render HTML until you hit the closing tag?

No, there is not. In HTML proper, there’s no way short of escaping some characters:

  • & as &amp;
  • < as &lt;

(Incidentally, there is no need to escape > but people often do it for reasons of symmetry.)

And of course you should surround the resulting, escaped HTML code within <pre><code>…</code></pre> to (a) preserve whitespace and line breaks, and (b) mark it up as a code element.

All other solutions, such as wrapping your code into a <textarea> or the (deprecated) <xmp> element, will break.1

XHTML that is declared to the browser as XML (via the HTTP Content-Type header! — merely setting a DOCTYPE is not enough) could alternatively use a CDATA section:

<![CDATA[Your <code> here]]>

But this only works in XML, not in HTML, and even this isn’t a foolproof solution, since the code mustn’t contain the closing delimiter ]]>. So even in XML the simplest, most robust solution is via escaping.


1 Case in point:

_x000D_
_x000D_
textarea {border: none; width: 100%;}
_x000D_
<textarea readonly="readonly">
  <p>Computer <textarea>says</textarea> <span>no.</span>
</textarea>

<xmp>
  Computer <xmp>says</xmp> <span>no.</span>
</xmp>
_x000D_
_x000D_
_x000D_

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

It is better to use onchange(event) with <select>. With <input> you can use below event:

- onkeyup(event)
- onkeydown(event)
- onkeypress(event)

Storing Python dictionaries

If you're after serialization, but won't need the data in other programs, I strongly recommend the shelve module. Think of it as a persistent dictionary.

myData = shelve.open('/path/to/file')

# Check for values.
keyVar in myData

# Set values
myData[anotherKey] = someValue

# Save the data for future use.
myData.close()

Byte Array to Hex String

If you have a numpy array, you can do the following:

>>> import numpy as np
>>> a = np.array([133, 53, 234, 241])
>>> a.astype(np.uint8).data.hex()
'8535eaf1'

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

file_put_contents - failed to open stream: Permission denied

Try adjusting the directory permissions.

from a terminal, run chmod 777 database (from the directory that contains the database folder)

apache and nobody will have access to this directory if it is chmodd'ed correctly.

The other thing to do is echo "getcwd()". This will show you the current directory, and if this isn't '/something.../database/' then you'll need to change 'query.txt' to the full path for your server.

Check input value length

You can add a form onsubmit handler, something like:

<form onsubmit="return validate();">

</form>


<script>function validate() {
 // check if input is bigger than 3
 var value = document.getElementById('titleeee').value;
 if (value.length < 3) {
   return false; // keep form from submitting
 }

 // else form is good let it submit, of course you will 
 // probably want to alert the user WHAT went wrong.

 return true;
}</script>

Parenthesis/Brackets Matching using Stack algorithm

//basic code non strack algorithm just started learning java ignore space and time.
/// {[()]}[][]{}
// {[( -a -> }]) -b -> replace a(]}) -> reverse a( }]))-> 
//Split string to substring {[()]}, next [], next [], next{}

public class testbrackets {
    static String stringfirst;
    static String stringsecond;
    static int open = 0;
    public static void main(String[] args) {
        splitstring("(()){}()");
    }
static void splitstring(String str){

    int len = str.length();
    for(int i=0;i<=len-1;i++){
        stringfirst="";
        stringsecond="";
        System.out.println("loop starttttttt");
        char a = str.charAt(i);
    if(a=='{'||a=='['||a=='(')
    {
        open = open+1;
        continue;
    }
    if(a=='}'||a==']'||a==')'){
        if(open==0){
            System.out.println(open+"started with closing brace");
            return;
        }
        String stringfirst=str.substring(i-open, i);
        System.out.println("stringfirst"+stringfirst);
        String stringsecond=str.substring(i, i+open);
        System.out.println("stringsecond"+stringsecond);
        replace(stringfirst, stringsecond);

        }
    i=(i+open)-1;
    open=0;
    System.out.println(i);
    }
    }
    static void replace(String stringfirst, String stringsecond){
        stringfirst = stringfirst.replace('{', '}');
        stringfirst = stringfirst.replace('(', ')');
        stringfirst = stringfirst.replace('[', ']');
        StringBuilder stringfirst1 = new StringBuilder(stringfirst);
        stringfirst = stringfirst1.reverse().toString();
    System.out.println("stringfirst"+stringfirst);
    System.out.println("stringsecond"+stringsecond);
if(stringfirst.equals(stringsecond)){
    System.out.println("pass");
}
    else{
        System.out.println("fail");
        System.exit(0);
        }
    }
}

invalid use of incomplete type

You derive B from A<B>, so the first thing the compiler does, once it sees the definition of class B is to try to instantiate A<B>. To do this it needs to known B::mytype for the parameter of action. But since the compiler is just in the process of figuring out the actual definition of B, it doesn't know this type yet and you get an error.

One way around this is would be to declare the parameter type as another template parameter, instead of inside the derived class:

template<typename Subclass, typename Param>
class A {
    public:
        void action(Param var) {
                (static_cast<Subclass*>(this))->do_action(var);
        }
};

class B : public A<B, int> { ... };

How to properly add 1 month from now to current date in moment.js

var currentDate = moment('2015-10-30');
var futureMonth = moment(currentDate).add(1, 'M');
var futureMonthEnd = moment(futureMonth).endOf('month');

if(currentDate.date() != futureMonth.date() && futureMonth.isSame(futureMonthEnd.format('YYYY-MM-DD'))) {
    futureMonth = futureMonth.add(1, 'd');
}

console.log(currentDate);
console.log(futureMonth);

DEMO

EDIT

moment.addRealMonth = function addRealMonth(d) {
  var fm = moment(d).add(1, 'M');
  var fmEnd = moment(fm).endOf('month');
  return d.date() != fm.date() && fm.isSame(fmEnd.format('YYYY-MM-DD')) ? fm.add(1, 'd') : fm;  
}

var nextMonth = moment.addRealMonth(moment());

DEMO

Can't find SDK folder inside Android studio path, and SDK manager not opening

I faced the same issue. And I am able to resolve it by uninstalling the previous version I had, and removing the Android studio projects and reinstalling it.

And then go to Settings-> Android Studio -> Click on edit, to specify studio location, it will recognize the requask you if you would like to download sdk,

Ansible: filter a list by its attributes

To filter a list of dicts you can use the selectattr filter together with the equalto test:

network.addresses.private_man | selectattr("type", "equalto", "fixed")

The above requires Jinja2 v2.8 or later (regardless of Ansible version).


Ansible also has the tests match and search, which take regular expressions:

match will require a complete match in the string, while search will require a match inside of the string.

network.addresses.private_man | selectattr("type", "match", "^fixed$")

To reduce the list of dicts to a list of strings, so you only get a list of the addr fields, you can use the map filter:

... | map(attribute='addr') | list

Or if you want a comma separated string:

... | map(attribute='addr') | join(',')

Combined, it would look like this.

- debug: msg={{ network.addresses.private_man | selectattr("type", "equalto", "fixed") | map(attribute='addr') | join(',') }}

Length of array in function argument

First, a better usage to compute number of elements when the actual array declaration is in scope is:

sizeof array / sizeof array[0]

This way you don't repeat the type name, which of course could change in the declaration and make you end up with an incorrect length computation. This is a typical case of don't repeat yourself.

Second, as a minor point, please note that sizeof is not a function, so the expression above doesn't need any parenthesis around the argument to sizeof.

Third, C doesn't have references so your usage of & in a declaration won't work.

I agree that the proper C solution is to pass the length (using the size_t type) as a separate argument, and use sizeof at the place the call is being made if the argument is a "real" array.

Note that often you work with memory returned by e.g. malloc(), and in those cases you never have a "true" array to compute the size off of, so designing the function to use an element count is more flexible.

Replacing NULL with 0 in a SQL server query

UPDATE TableName SET ColumnName= ISNULL(ColumnName, 0 ) WHERE Id = 10

Is there a template engine for Node.js?

You can try beardless (it's inspired by weld/plates):

For example:

{ post:
  { title: "Next generation templating: Start shaving!"
  , text: "TL;DR You should really check out beardless!"
  , comments:
    [ {text: "Hey cool!"}
    , {text: "Really gotta check that out..."}  ]
  }
}

Your template:

<h1 data-template="post.title"></h1>
<p data-template="post.text"></p>
<div>
  <div data-template="post.comments" class="comment">
    <p data-template="post.comments.text"></p>
  </div>
</div>

Output:

<h1>Next generation templating: Start shaving!</h1>
<p>TL;DR You should really check out beardless!</p>
<div>
  <div class="comment">
    <p>Hey cool!</p>
  </div>
  <div class="comment">
    <p>Really gotta check that out...</p>
  </div>
</div>

tmux status bar configuration

I used tmux-powerline to fully pimp my tmux status bar. I was googling for a way to change to background of the status bar when your typing a tmux command. When I stumbled on this post I thought I should mention it for completeness.

Update: This project is in a maintenance mode and no future functionality is likely to be added. tmux-powerline, with all other powerline projects, is replaced by the new unifying powerline. However this project is still functional and can serve as a lightweight alternative for non-python users.

New Line Issue when copying data from SQL Server 2012 to Excel

In order to be able to copy and paste results from SQL Server Management Studio 2012 to Excel or to export to Csv with list separators you must first change the query option.

  1. Click on Query then options.

  2. Under Results click on the Grid.

  3. Check the box next to:

    Quote strings containing list separators when saving .csv results.

This should solve the problem.

Efficient way to Handle ResultSet in Java

Here is the code little modified that i got it from google -

 List data_table = new ArrayList<>();
    Class.forName("oracle.jdbc.driver.OracleDriver");
            con = DriverManager.getConnection(conn_url, user_id, password);
            Statement stmt = con.createStatement();
            System.out.println("query_string: "+query_string);
            ResultSet rs = stmt.executeQuery(query_string);
            ResultSetMetaData rsmd = rs.getMetaData();


            int row_count = 0;
            while (rs.next()) {
                HashMap<String, String> data_map = new HashMap<>();
                if (row_count == 240001) {
                    break;
                }
                for (int i = 1; i <= rsmd.getColumnCount(); i++) {
                    data_map.put(rsmd.getColumnName(i), rs.getString(i));
                }
                data_table.add(data_map);
                row_count = row_count + 1;
            }
            rs.close();
            stmt.close();
            con.close();

OpenCV get pixel channel value from Mat image

Assuming the type is CV_8UC3 you would do this:

for(int i = 0; i < foo.rows; i++)
{
    for(int j = 0; j < foo.cols; j++)
    {
        Vec3b bgrPixel = foo.at<Vec3b>(i, j);

        // do something with BGR values...
    }
}

Here is the documentation for Vec3b. Hope that helps! Also, don't forget OpenCV stores things internally as BGR not RGB.

EDIT :
For performance reasons, you may want to use direct access to the data buffer in order to process the pixel values:

Here is how you might go about this:

uint8_t* pixelPtr = (uint8_t*)foo.data;
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;

for(int i = 0; i < foo.rows; i++)
{
    for(int j = 0; j < foo.cols; j++)
    {
        bgrPixel.val[0] = pixelPtr[i*foo.cols*cn + j*cn + 0]; // B
        bgrPixel.val[1] = pixelPtr[i*foo.cols*cn + j*cn + 1]; // G
        bgrPixel.val[2] = pixelPtr[i*foo.cols*cn + j*cn + 2]; // R

        // do something with BGR values...
    }
}

Or alternatively:

int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;

for(int i = 0; i < foo.rows; i++)
{
    uint8_t* rowPtr = foo.row(i);
    for(int j = 0; j < foo.cols; j++)
    {
        bgrPixel.val[0] = rowPtr[j*cn + 0]; // B
        bgrPixel.val[1] = rowPtr[j*cn + 1]; // G
        bgrPixel.val[2] = rowPtr[j*cn + 2]; // R

        // do something with BGR values...
    }
}

500 Internal Server Error for php file not for html

Google guides me here but it didn't fix mine, this is a very general question and there are various causes, so I post my problem and solution here for reference in case anyone might read this later.

Another possible cause of 500 error is syntax error in header(...) function, like this one:

header($_SERVER['SERVER_PROTOCOL'] . '200 OK');

Be aware there should be space between server protocol and status code, so it should be:

header($_SERVER['SERVER_PROTOCOL'] . ' 200 OK');

So I suggest check your http header call if you have it in your code.

How to sort an associative array by its values in Javascript?

Continued discussion & other solutions covered at How to sort an (associative) array by value? with the best solution (for my case) being by saml (quoted below).

Arrays can only have numeric indexes. You'd need to rewrite this as either an Object, or an Array of Objects.

var status = new Array();
status.push({name: 'BOB', val: 10});
status.push({name: 'TOM', val: 3});
status.push({name: 'ROB', val: 22});
status.push({name: 'JON', val: 7});

If you like the status.push method, you can sort it with:

status.sort(function(a,b) {
    return a.val - b.val;
});

RecyclerView vs. ListView

The RecyclerView is a new ViewGroup that is prepared to render any adapter-based view in a similar way. It is supossed to be the successor of ListView and GridView, and it can be found in the latest support-v7 version. The RecyclerView has been developed with extensibility in mind, so it is possible to create any kind of layout you can think of, but not without a little pain-in-the-ass dose.

Answer taken from Antonio leiva

 compile 'com.android.support:recyclerview-v7:27.0.0'

RecyclerView is indeed a powerful view than ListView . For more details you can visit This page.

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

try typing the following code in anaconda prompt one by one.

this worked for me.

Source: https://anaconda.org/conda-forge/python-graphviz

conda install -c conda-forge python-graphviz
conda install -c conda-forge/label/broken python-graphviz
conda install -c conda-forge/label/cf201901 python-graphviz
conda install -c conda-forge/label/cf202003 python-graphviz 

How to find the logs on android studio?

C:\Users\bob.AndroidStudio2.3\system\log

How to access Winform textbox control from another class?

If your other class inherits Form1 and if your textBox1 is declared public, then you can access that text box from your other class by simply calling:

otherClassInstance.textBox1.Text = "hello world";

Add line break within tooltips

The &#013; combined with the style white-space: pre-line; worked for me.

nodejs get file name from absolute path?

To get the file name portion of the file name, the basename method is used:

var path = require("path");
var fileName = "C:\\Python27\\ArcGIS10.2\\python.exe";
var file = path.basename(fileName);

console.log(file); // 'python.exe'

If you want the file name without the extension, you can pass the extension variable (containing the extension name) to the basename method telling Node to return only the name without the extension:

var path = require("path");
var fileName = "C:\\Python27\\ArcGIS10.2\\python.exe";
var extension = path.extname(fileName);
var file = path.basename(fileName,extension);

console.log(file); // 'python'

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

Make div stay at bottom of page's content all the time even when there are scrollbars

Unfortunately you can't do this with out adding a little extra HTML and having one piece of CSS rely on another.

HTML

First you need to wrap your header,footer and #body into a #holder div:

<div id="holder">
    <header>.....</header>
    <div id="body">....</div>
    <footer>....</footer>
</div>

CSS

Then set height: 100% to html and body (actual body, not your #body div) to ensure you can set minimum height as a percentage on child elements.

Now set min-height: 100% on the #holder div so it fills the content of the screen and use position: absolute to sit the footer at the bottom of the #holder div.

Unfortunately, you have to apply padding-bottom to the #body div that is the same height as the footer to ensure that the footer does not sit above any content:

html,body{
    height: 100%
}

#holder{
    min-height: 100%;
    position:relative;
}

#body{
    padding-bottom: 100px;    /* height of footer */
}

footer{
    height: 100px; 
    width:100%;
    position: absolute;
    left: 0;
    bottom: 0; 
}

Working example, short body: http://jsfiddle.net/ELUGc/

Working example, long body: http://jsfiddle.net/ELUGc/1/

No module named 'openpyxl' - Python 3.4 - Ubuntu

If you don't use conda, just use :

pip install openpyxl

If you use conda, I'd recommend :

conda install -c anaconda openpyxl

instead of simply conda install openpyxl

Because there are issues right now with conda updating (see GitHub Issue #8842) ; this is being fixed and it should work again after the next release (conda 4.7.6)

Increasing the timeout value in a WCF service

You can choose two ways:

1) By code in the client

public static void Main()
{
    Uri baseAddress = new Uri("http://localhost/MyServer/MyService");

    try
    {
        ServiceHost serviceHost = new ServiceHost(typeof(CalculatorService));

        WSHttpBinding binding = new WSHttpBinding();
        binding.OpenTimeout = new TimeSpan(0, 10, 0);
        binding.CloseTimeout = new TimeSpan(0, 10, 0);
        binding.SendTimeout = new TimeSpan(0, 10, 0);
        binding.ReceiveTimeout = new TimeSpan(0, 10, 0);

        serviceHost.AddServiceEndpoint("ICalculator", binding, baseAddress);
        serviceHost.Open();

        // The service can now be accessed.
        Console.WriteLine("The service is ready.");
        Console.WriteLine("Press <ENTER> to terminate service.");
        Console.WriteLine();
        Console.ReadLine();

    }
    catch (CommunicationException ex)
    {
        // Handle exception ...
    }
}

2)By WebConfig in a web server

<configuration>
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding openTimeout="00:10:00" 
                 closeTimeout="00:10:00" 
                 sendTimeout="00:10:00" 
                 receiveTimeout="00:10:00">
        </binding>
      </wsHttpBinding>
    </bindings>
  </system.serviceModel>

For more detail view the official documentations

Configuring Timeout Values on a Binding

Class WSHttpBinding

How to parse JSON in Kotlin?

Download the source of deme from here(Json parsing in android kotlin)

Add this dependency:

compile 'com.squareup.okhttp3:okhttp:3.8.1'

Call api function:

 fun run(url: String) {
    dialog.show()
    val request = Request.Builder()
            .url(url)
            .build()

    client.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            dialog.dismiss()

        }

        override fun onResponse(call: Call, response: Response) {
            var str_response = response.body()!!.string()
            val json_contact:JSONObject = JSONObject(str_response)

            var jsonarray_contacts:JSONArray= json_contact.getJSONArray("contacts")

            var i:Int = 0
            var size:Int = jsonarray_contacts.length()

            al_details= ArrayList();

            for (i in 0.. size-1) {
                var json_objectdetail:JSONObject=jsonarray_contacts.getJSONObject(i)


                var model:Model= Model();
                model.id=json_objectdetail.getString("id")
                model.name=json_objectdetail.getString("name")
                model.email=json_objectdetail.getString("email")
                model.address=json_objectdetail.getString("address")
                model.gender=json_objectdetail.getString("gender")

                al_details.add(model)


            }

            runOnUiThread {
                //stuff that updates ui
                val obj_adapter : CustomAdapter
                obj_adapter = CustomAdapter(applicationContext,al_details)
                lv_details.adapter=obj_adapter
            }

            dialog.dismiss()

        }

    })

Spring Resttemplate exception handling

I fixed it by overriding the hasError method from DefaultResponseErrorHandler class:

public class BadRequestSafeRestTemplateErrorHandler extends DefaultResponseErrorHandler
{
    @Override
    protected boolean hasError(HttpStatus statusCode)
    {
        if(statusCode == HttpStatus.BAD_REQUEST)
        {
            return false;
        }
        return statusCode.isError();
    }
}

And you need to set this handler for restemplate bean:

@Bean
    protected RestTemplate restTemplate(RestTemplateBuilder builder)
    {
        return builder.errorHandler(new BadRequestSafeRestTemplateErrorHandler()).build();
    }

What's the difference between 'r+' and 'a+' when open file in python?

If you have used them in C, then they are almost same as were in C.

From the manpage of fopen() function : -

  • r+ : - Open for reading and writing. The stream is positioned at the beginning of the file.

  • a+ : - Open for reading and writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subse- quent writes to the file will always end up at the then current end of file, irrespective of any intervening fseek(3) or similar.

How do I "break" out of an if statement?

if (test)
{
    ...
    goto jmp;
    ...
}
jmp:

Oh why not :)

Full Page <iframe>

For full-screen frame redirects and similar things I have two methods. Both work fine on mobile and desktop.

Note this are complete cross-browser working, valid HTML files. Just change title and src for your needs.

1. this is my favorite:

<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-1 </title>
<meta name=viewport content="width=device-width">
<style>
 html, body, iframe { height:100%; width:100%; margin:0; border:0; display:block }
</style>
<iframe src=src1></iframe>

<!-- More verbose CSS for better understanding:
  html   { height:100% }
  body   { height:100%; margin:0 }
  iframe { height:100%; width:100%; border:0; display:block }
-->

or 2. something like that, slightly shorter:

<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-2 </title>
<meta name=viewport content="width=device-width">
<iframe src=src2 style="position:absolute; top:0; left:0; width:100%; height:100%; border:0">
</iframe>


Note:
The above examples avoid using height:100vh because old browsers don't know it (maybe moot these days) and height:100vh is not always equal to height:100% on mobile browsers (probably not applicable here). Otherwise, vh simplifies things a little bit, so

3. this is an example using vh (not my favorite, less compatible with little advantage)

<!DOCTYPE html>
<meta charset=utf-8>
<title> Title-3 </title>
<meta name=viewport content="width=device-width">
<style>
 body { margin:0 }
 iframe { display:block; width:100%; height:100vh; border:0 }
</style>
<iframe src=src3></iframe>

Undefined reference to 'vtable for xxx'

GNU linker, in my case companion of GCC 8.1.0, well detects not re-declared pure virtual methods, but above certain complexity of class design it fails to identify missing implementation of methods and answers with a flat "V-Table Missing",

or even tends to report missing implementation, in spite it is there.

The only solution then is to verify consistency of declaration of implementation manually, method by method.

How do I make background-size work in IE?

I tried with the following script -

.selector { 
background-image: url("img/image.jpg");
background-size: 100%;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-repeat: no-repeat;
}

It worked for me!

Save multiple sheets to .pdf

I recommend adding the following line after the export to PDF:

ThisWorkbook.Sheets("Sheet1").Select

(where eg. Sheet1 is the single sheet you want to be active afterwards)

Leaving multiple sheets in a selected state may cause problems executing some code. (eg. unprotect doesn't function properly when multiple sheets are actively selected.)

How to repair a serialized string which has been corrupted by an incorrect byte count length?

You can fix broken serialize string using following function, with multibyte character handling.

function repairSerializeString($value)
{

    $regex = '/s:([0-9]+):"(.*?)"/';

    return preg_replace_callback(
        $regex, function($match) {
            return "s:".mb_strlen($match[2]).":\"".$match[2]."\""; 
        },
        $value
    );
}

How to Install Sublime Text 3 using Homebrew

To install Sublime Text 3 run:

brew install --cask sublime-text

reference: https://formulae.brew.sh/cask/sublime-text

Get local href value from anchor (a) tag

The below code gets the full path, where the anchor points:

document.getElementById("aaa").href; // http://example.com/sec/IF00.html

while the one below gets the value of the href attribute:

document.getElementById("aaa").getAttribute("href"); // sec/IF00.html

Sending JSON to PHP using ajax

If you want to get the values via the $_POST variable then you should not specify the contentType as "application/json" but rather use the default "application/x-www-form-urlencoded; charset=UTF-8":

JavaScript:

var person = { name: "John" };

$.ajax({
    //contentType: "application/json", // php://input
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", // $_POST
    dataType : "json",
    method: "POST",
    url: "http://localhost/test/test.php",
    data: {data: person}
})
.done(function(data) {  
    console.log("test: ", data);
    $("#result").text(data.name);
})
.fail(function(data) {
    console.log("error: ", data);
});

PHP:

<?php

// $_POST

$jsonString = $_POST['data'];

$newJsonString = json_encode($jsonString);
header('Content-Type: application/json');
echo $newJsonString;

Else if you want to send a JSON from JavaScript to PHP:

JavaScript:

var person = { name: "John" };

$.ajax({
    contentType: "application/json", // php://input
    //contentType: "application/x-www-form-urlencoded; charset=UTF-8", // $_POST
    dataType : "json",
    method: "POST",
    url: "http://localhost/test/test.php",
    data: person
})
.done(function(data) {  
    console.log("test: ", data);
    $("#result").text(data.name);
})
.fail(function(data) {
    console.log("error: ", data);
});

PHP:

<?php

$jsonString = file_get_contents("php://input");
$phpObject = json_decode($jsonString);

$newJsonString = json_encode($phpObject);
header('Content-Type: application/json');
echo $newJsonString;

Is there a need for range(len(a))?

What if you need to access two elements of the list simultaneously?

for i in range(len(a[0:-1])):
    something_new[i] = a[i] * a[i+1]

You can use this, but it's probably less clear:

for i, _ in enumerate(a[0:-1]):
     something_new[i] = a[i] * a[i+1]

Personally I'm not 100% happy with either!

How to find which version of Oracle is installed on a Linux server (In terminal)

A bit manual searching but its an alternative way...
Find the Oracle home or where the installation files for Oracle is installed on your linux server.

cd / <-- Goto root directory
find . -print| grep -i dbm*.sql

Result varies on how you installed Oracle but mine displays this

/db/oracle

Goto the folder

less /db/oracle/db1/sqlplus/doc/README.htm

scroll down and you should see something like this

SQL*Plus Release Notes - Release 11.2.0.2

How to set app icon for Electron / Atom Shell App

Please be aware that the examples for icon file path tend to assume that main.js is under the base directory. If the file is not in the base directory of the app, the path specification must account for that fact.

For example, if the main.js is under the src/ subdirectory, and the icon is under assets/icons/, this icon path specification will work:

icon: __dirname + "../assets/icons/icon.png"

Forking vs. Branching in GitHub

You cannot always make a branch or pull an existing branch and push back to it, because you are not registered as a collaborator for that specific project.

Forking is nothing more than a clone on the GitHub server side:

  • without the possibility to directly push back
  • with fork queue feature added to manage the merge request

You keep a fork in sync with the original project by:

  • adding the original project as a remote
  • fetching regularly from that original project
  • rebase your current development on top of the branch of interest you got updated from that fetch.

The rebase allows you to make sure your changes are straightforward (no merge conflict to handle), making your pulling request that more easy when you want the maintainer of the original project to include your patches in his project.

The goal is really to allow collaboration even though direct participation is not always possible.


The fact that you clone on the GitHub side means you have now two "central" repository ("central" as "visible from several collaborators).
If you can add them directly as collaborator for one project, you don't need to manage another one with a fork.

fork on GitHub

The merge experience would be about the same, but with an extra level of indirection (push first on the fork, then ask for a pull, with the risk of evolutions on the original repo making your fast-forward merges not fast-forward anymore).
That means the correct workflow is to git pull --rebase upstream (rebase your work on top of new commits from upstream), and then git push --force origin, in order to rewrite the history in such a way your own commits are always on top of the commits from the original (upstream) repo.

See also:

inserting characters at the start and end of a string

Let's say we have a string called yourstring:

for x in range(0, [howmanytimes you want it at the beginning]):
    yourstring = "L" + yourstring
for x in range(0, [howmanytimes you want it at the end]):
    yourstring += "L"

How to install bcmath module?

Worked great on CentOS 6.5

yum install bcmath

All my calls to bcmath functions started working right after an apache restart

service httpd restart

Sweet!

What is Gradle in Android Studio?

Gradle is an automated build toolkit that can integrate into lots of different environments not only for Android projects.

Here are few things that you can do with gradle.

  • Minimal Configuration Required for New Projects because Gradle has defaults configurations for your android studio projects.

  • Dependancy Declaration. You can declare dependency jar files or library files that is hosted in local or remote server.

  • Gradle automatically generates a test directory and a test APK from your project's source.

  • If you add all the necessary information, such as keyPassword and keyAlias, to your Gradle build file, you can use Gradle to generate signed APKs.

  • Gradle can generate multiple APKs with different package and build configurations from a single module.

Java Thread Example?

create java application in which you define two threads namely t1 and t2, thread t1 will generate random number 0 and 1 (simulate toss a coin ). 0 means head and one means tail. the other thread t2 will do the same t1 and t2 will repeat this loop 100 times and finally your application should determine how many times t1 guesses the number generated by t2 and then display the score. for example if thread t1 guesses 20 number out of 100 then the score of t1 is 20/100 =0.2 if t1 guesses 100 numbers then it gets score 1 and so on

How to delete an item in a list if it exists?

try:
    s.remove("")
except ValueError:
    print "new_tag_list has no empty string"

Note that this will only remove one instance of the empty string from your list (as your code would have, too). Can your list contain more than one?

What does it mean "No Launcher activity found!"

Multiple action tags in a single intent-filter tag will also cause the same error.

how to assign a block of html code to a javascript variable

Greetings! I know this is an older post, but I found it through Google when searching for "javascript add large block of html as variable". I thought I'd post an alternate solution.

First, I'd recommend using single-quotes around the variable itself ... makes it easier to preserve double-quotes in the actual HTML code.

You can use a backslash to separate lines if you want to maintain a sense of formatting to the code:

var code = '<div class="my-class"> \
        <h1>The Header</h1> \
        <p>The paragraph of text</p> \
        <div class="my-quote"> \
            <p>The quote I\'d like to put in a div</p> \
        </div> \
    </div>';

Note: You'll obviously need to escape any single-quotes inside the code (e.g. inside the last 'p' tag)

Anyway, I hope that helps someone else that may be looking for the same answer I was ... Cheers!

Can we convert a byte array into an InputStream in Java?

Use ByteArrayInputStream:

InputStream is = new ByteArrayInputStream(decodedBytes);

Difference between if () { } and if () : endif;

At our company, the preferred way for handling HTML is:

<? if($condition) { ?>
   HTML content here
<? } else { ?>
   Other HTML content here
<? } ?>

In the end, it really is a matter of choosing one and sticking with it.

Is log(n!) = T(n·log(n))?

Helping you further, where Mick Sharpe left you:

It's deriveration is quite simple: see http://en.wikipedia.org/wiki/Logarithm -> Group Theory

log(n!) = log(n * (n-1) * (n-2) * ... * 2 * 1) = log(n) + log(n-1) + ... + log(2) + log(1)

Think of n as infinitly big. What is infinite minus one? or minus two? etc.

log(inf) + log(inf) + log(inf) + ... = inf * log(inf)

And then think of inf as n.

Convert date field into text in Excel

You don't need to convert the original entry - you can use TEXT function in the concatenation formula, e.g. with date in A1 use a formula like this

="Today is "&TEXT(A1,"dd-mm-yyyy")

You can change the "dd-mm-yyyy" part as required

Using Mysql in the command line in osx - command not found?

You can just modified the .bash_profile by adding the MySQL $PATH as the following:
export PATH=$PATH:/usr/local/mysql/bin.

I did the following:

1- Open Terminal then $ nano .bash_profile or $ vim .bash_profile

2- Add the following PATH code to the .bash_profile

# Set architecture flags
export ARCHFLAGS="-arch x86_64"
# Ensure user-installed binaries take precedence
export PATH=/usr/local/mysql/bin:$PATH
# Load .bashrc if it exists
test -f ~/.bashrc && source ~/.bashrc 

3- Save the file.

4- Refresh Terminal using $ source ~/.bash_profile

5- To verify, type in Terminal $ mysql --version

6- It should print the output something like this:

$ mysql Ver 14.14 Distrib 5.7.17, for macos10.12 (x86_64)

The Terminal is now configured to read the MySQL commands from $PATH which is placed in the .bash_profile .

How to rename a single column in a data.frame?

This is likely already out there, but I was playing with renaming fields while searching out a solution and tried this on a whim. Worked for my purposes.

Table1$FieldNewName <- Table1$FieldOldName
Table1$FieldOldName <- NULL

Edit begins here....

This works as well.

df <- rename(df, c("oldColName" = "newColName"))

How to loop in excel without VBA or macros?

@Nat gave a good answer. But since there is no way to shorten a code, why not use contatenate to 'generate' the code you need. It works for me when I'm lazy (at typing the whole code in the cell).

So what we need is just identify the pattern > use excel to built the pattern 'structure' > add " = " and paste it in the intended cell.

For example, you want to achieve (i mean, enter in the cell) :

=IF('testsheet'!$C$1 <= 99,'testsheet'!$A$1,"") &IF('testsheet'!$C$2 <= 99,'testsheet'!$A$2,"") &IF('testsheet'!$C$3 <= 99,'testsheet'!$A$3,"") &IF('testsheet'!$C$4 <= 99,'testsheet'!$A$4,"") &IF('testsheet'!$C$5 <= 99,'testsheet'!$A$5,"") &IF('testsheet'!$C$6 <= 99,'testsheet'!$A$6,"") &IF('testsheet'!$C$7 <= 99,'testsheet'!$A$7,"") &IF('testsheet'!$C$8 <= 99,'testsheet'!$A$8,"") &IF('testsheet'!$C$9 <= 99,'testsheet'!$A$9,"") &IF('testsheet'!$C$10 <= 99,'testsheet'!$A$10,"") &IF('testsheet'!$C$11 <= 99,'testsheet'!$A$11,"") &IF('testsheet'!$C$12 <= 99,'testsheet'!$A$12,"") &IF('testsheet'!$C$13 <= 99,'testsheet'!$A$13,"") &IF('testsheet'!$C$14 <= 99,'testsheet'!$A$14,"") &IF('testsheet'!$C$15 <= 99,'testsheet'!$A$15,"") &IF('testsheet'!$C$16 <= 99,'testsheet'!$A$16,"") &IF('testsheet'!$C$17 <= 99,'testsheet'!$A$17,"") &IF('testsheet'!$C$18 <= 99,'testsheet'!$A$18,"") &IF('testsheet'!$C$19 <= 99,'testsheet'!$A$19,"") &IF('testsheet'!$C$20 <= 99,'testsheet'!$A$20,"") &IF('testsheet'!$C$21 <= 99,'testsheet'!$A$21,"") &IF('testsheet'!$C$22 <= 99,'testsheet'!$A$22,"") &IF('testsheet'!$C$23 <= 99,'testsheet'!$A$23,"") &IF('testsheet'!$C$24 <= 99,'testsheet'!$A$24,"") &IF('testsheet'!$C$25 <= 99,'testsheet'!$A$25,"") &IF('testsheet'!$C$26 <= 99,'testsheet'!$A$26,"") &IF('testsheet'!$C$27 <= 99,'testsheet'!$A$27,"") &IF('testsheet'!$C$28 <= 99,'testsheet'!$A$28,"") &IF('testsheet'!$C$29 <= 99,'testsheet'!$A$29,"") &IF('testsheet'!$C$30 <= 99,'testsheet'!$A$30,"") &IF('testsheet'!$C$31 <= 99,'testsheet'!$A$31,"") &IF('testsheet'!$C$32 <= 99,'testsheet'!$A$32,"") &IF('testsheet'!$C$33 <= 99,'testsheet'!$A$33,"") &IF('testsheet'!$C$34 <= 99,'testsheet'!$A$34,"") &IF('testsheet'!$C$35 <= 99,'testsheet'!$A$35,"") &IF('testsheet'!$C$36 <= 99,'testsheet'!$A$36,"") &IF('testsheet'!$C$37 <= 99,'testsheet'!$A$37,"") &IF('testsheet'!$C$38 <= 99,'testsheet'!$A$38,"") &IF('testsheet'!$C$39 <= 99,'testsheet'!$A$39,"") &IF('testsheet'!$C$40 <= 99,'testsheet'!$A$40,"") 

I didn't type it, I just use "&" symbol to combine arranged cell in excel (another file, not the file we are working on).

Notice that :

part1 > IF('testsheet'!$C$

part2 > 1 to 40

part3 > <= 99,'testsheet'!$A$

part4 > 1 to 40

part5 > ,"") &

  • Enter part1 to A1, part3 to C1, part to E1.
  • Enter " = A1 " in A2, " = C1 " in C2, " = E1 " in E2.
  • Enter " = B1+1 " in B2, " = D1+1 " in D2.
  • Enter " =A2&B2&C2&D2&E2 " in G2
  • Enter " =I1&G2 " in I2

Now select A2:I2 , and drag it down. Notice that the number did the increament per row added, and the generated text is combined, cell by cell and line by line.

  • Copy I41 content,
  • paste it somewhere, add " = " in front, remove the extra & and the back.

Result = code as you intended.

I've use excel/OpenOfficeCalc to help me generate code for my projects. Works for me, hope it helps for others. (:

How to pass multiple values to single parameter in stored procedure

Either use a User Defined Table

Or you can use CSV by defining your own CSV function as per This Post.

I'd probably recommend the second method, as your stored proc is already written in the correct format and you'll find it handy later on if you need to do this down the road.

Cheers!

Bash write to file without echo?

I've a solution for bash purists.

The function 'define' helps us to assign a multiline value to a variable. This one takes one positional parameter: the variable name to assign the value.

In the heredoc, optionally there're parameter expansions too!

#!/bin/bash

define ()
{
  IFS=$'\n' read -r -d '' $1
}

BUCH="Matthäus 1"

define TEXT<<EOT
Aus dem Buch: ${BUCH}

1 Buch des Geschlechts Jesu Christi, des Sohnes Davids, des Sohnes Abrahams.
2 Abraham zeugte Isaak; Isaak aber zeugte Jakob, Jakob aber zeugte Juda und seine Brüder;
3 Juda aber zeugte Phares und Zara von der Thamar; Phares aber zeugte Esrom, Esrom aber zeugte Aram,

4 Aram aber zeugte Aminadab, Aminadab aber zeugte Nahasson, Nahasson aber zeugte Salmon,
5 Salmon aber zeugte Boas von der Rahab; Boas aber zeugte Obed von der Ruth; Obed aber zeugte Isai,
6 Isai aber zeugte David, den König. David aber zeugte Salomon von der, die Urias Weib gewesen; 

EOT

define TEXTNOEXPAND<<"EOT" # or define TEXTNOEXPAND<<'EOT'
Aus dem Buch: ${BUCH}

1 Buch des Geschlechts Jesu Christi, des Sohnes Davids, des Sohnes Abrahams.
2 Abraham zeugte Isaak; Isaak aber zeugte Jakob, Jakob aber zeugte Juda und seine Brüder;
3 Juda aber zeugte Phares und Zara von der Thamar; Phares aber zeugte Esrom, Esrom aber zeugte Aram,


4 Aram aber zeugte Aminadab, Aminadab aber zeugte Nahasson, Nahasson aber zeugte Salmon,
5 Salmon aber zeugte Boas von der Rahab; Boas aber zeugte Obed von der Ruth; Obed aber zeugte Isai,
6 Isai aber zeugte David, den König. David aber zeugte Salomon von der, die Urias Weib gewesen; 

EOT

OUTFILE="/tmp/matthäus_eins"

# Create file
>"$OUTFILE"

# Write contents
{
   printf "%s\n" "$TEXT"
   printf "%s\n" "$TEXTNOEXPAND"
} >>"$OUTFILE" 

Be lucky!

Please add a @Pipe/@Directive/@Component annotation. Error

In my case, I accidentally added the package in the declaration but it should be in imports.

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

In my case it was because the file was minified with wrong scope. Use Array!

app.controller('StoreController', ['$http', function($http) {
    ...
}]);

Coffee syntax:

app.controller 'StoreController', Array '$http', ($http) ->
  ...

Internet Access in Ubuntu on VirtualBox

it could be a problem with your specific network adapter. I have a Dell 15R and there are no working drivers for ubuntu or ubuntu server; I even tried compiling wireless drivers myself, but to no avail.

However, in virtualbox, I was able to get wireless working by using the default configuration. It automatically bridged my internal wireless adapter and hence used my native OS's wireless connection for wireless.

If you are trying to get a separate wireless connection from within ubuntu in virtualbox, then it would take more configuring. If so, let me know, if not, I will not bother typing up instructions to something you are not looking to do, as it is quite complicated in some instances.

p.s. you should be using Windows 7 if you have any technical inclination. Do you live under a rock? No offense intended.

How can I write an anonymous function in Java?

With the introduction of lambda expression in Java 8 you can now have anonymous methods.

Say I have a class Alpha and I want to filter Alphas on a specific condition. To do this you can use a Predicate<Alpha>. This is a functional interface which has a method test that accepts an Alpha and returns a boolean.

Assuming that the filter method has this signature:

List<Alpha> filter(Predicate<Alpha> filterPredicate)

With the old anonymous class solution you would need to something like:

filter(new Predicate<Alpha>() {
   boolean test(Alpha alpha) {
      return alpha.centauri > 1;
   }
});

With the Java 8 lambdas you can do:

filter(alpha -> alpha.centauri > 1);

For more detailed information see the Lambda Expressions tutorial

How to install a gem or update RubyGems if it fails with a permissions error

This worked for me. Plus, if you installed gems as root before, it fixes that problem by changing ownership back to you (better security-wise).

sudo chown -R `whoami` /Library/Ruby/Gems

How to remove a build from itunes connect?

I had this problem. I'll share my ride on the learning curve.

First, I couldn't find how to reject the binary but remembered seeing it earlier today in the iTunesConnect App. So using the App I rejected the binary.

If you "mouse over" the rejected binary under the "Build" section you'll notice that a red circle icon with a - (i.e. a delete button) appears. Tap on this and then hit the save button at the top of the screen. Submitted binary is now gone.

You should now get all the notifications for the app being in state "Prepare for Upload" (email, App notification etc).

Xcode organiser was still giving me "Redundant Binary". After a bit of research I now understand the difference between "Version" & "Build". Version is what iTunes displays and the user sees. Build is just the internal tracking number. I had both at 2.3.0, I changed build to 2.3.0.1 and re-Archive. Now it validates and I can upload the new binary and re-submit. Hope that helps others!

Javascript close alert box

You actually can do this you can basically listen for this pop up to happen and then confirm true before it ever "pops up",

if(window.alert){
  return true
}

Unstage a deleted file in git

Assuming you're wanting to undo the effects of git rm <file> or rm <file> followed by git add -A or something similar:

# this restores the file status in the index
git reset -- <file>
# then check out a copy from the index
git checkout -- <file>

To undo git add <file>, the first line above suffices, assuming you haven't committed yet.

How to change button background image on mouseOver?

You can create a class based on a Button with specific images for MouseHover and MouseDown like this:

public class AdvancedImageButton : Button {

public Image HoverImage { get; set; }
public Image PlainImage { get; set; }
public Image PressedImage { get; set; }

protected override void OnMouseEnter(System.EventArgs e)
{
  base.OnMouseEnter(e);
  if (HoverImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = HoverImage;
}

protected override void OnMouseLeave(System.EventArgs e)
{
  base.OnMouseLeave(e);
  if (HoverImage == null) return;
  base.Image = PlainImage;
}

protected override void OnMouseDown(MouseEventArgs e)
{
  base.OnMouseDown(e);
  if (PressedImage == null) return;
  if (PlainImage == null) PlainImage = base.Image;
  base.Image = PressedImage;
}

}

This solution has a small drawback that I am sure can be fixed: when you need for some reason change the Image property, you will also have to change the PlainImage property also.

How to download python from command-line?

apt-get install python2.7 will work on debian-like linuxes. The python website describes a whole bunch of other ways to get Python.

BasicHttpBinding vs WsHttpBinding vs WebHttpBinding

You're comparing apples to oranges here:

  • webHttpBinding is the REST-style binding, where you basically just hit a URL and get back a truckload of XML or JSON from the web service

  • basicHttpBinding and wsHttpBinding are two SOAP-based bindings which is quite different from REST. SOAP has the advantage of having WSDL and XSD to describe the service, its methods, and the data being passed around in great detail (REST doesn't have anything like that - yet). On the other hand, you can't just browse to a wsHttpBinding endpoint with your browser and look at XML - you have to use a SOAP client, e.g. the WcfTestClient or your own app.

So your first decision must be: REST vs. SOAP (or you can expose both types of endpoints from your service - that's possible, too).

Then, between basicHttpBinding and wsHttpBinding, there differences are as follows:

  • basicHttpBinding is the very basic binding - SOAP 1.1, not much in terms of security, not much else in terms of features - but compatible to just about any SOAP client out there --> great for interoperability, weak on features and security

  • wsHttpBinding is the full-blown binding, which supports a ton of WS-* features and standards - it has lots more security features, you can use sessionful connections, you can use reliable messaging, you can use transactional control - just a lot more stuff, but wsHttpBinding is also a lot *heavier" and adds a lot of overhead to your messages as they travel across the network

For an in-depth comparison (including a table and code examples) between the two check out this codeproject article: Differences between BasicHttpBinding and WsHttpBinding

What is the difference between Left, Right, Outer and Inner Joins?

There are only 4 kinds:

  1. Inner join: The most common type. An output row is produced for every pair of input rows that match on the join conditions.
  2. Left outer join: The same as an inner join, except that if there is any row for which no matching row in the table on the right can be found, a row is output containing the values from the table on the left, with NULL for each value in the table on the right. This means that every row from the table on the left will appear at least once in the output.
  3. Right outer join: The same as a left outer join, except with the roles of the tables reversed.
  4. Full outer join: A combination of left and right outer joins. Every row from both tables will appear in the output at least once.

A "cross join" or "cartesian join" is simply an inner join for which no join conditions have been specified, resulting in all pairs of rows being output.

Thanks to RusselH for pointing out FULL joins, which I'd omitted.

"A namespace cannot directly contain members such as fields or methods"

The snippet you're showing doesn't seem to be directly responsible for the error.

This is how you can CAUSE the error:

namespace MyNameSpace
{
   int i; <-- THIS NEEDS TO BE INSIDE THE CLASS

   class MyClass
   {
      ...
   }
}

If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }.

How to get the GL library/headers?

If you're on Windows, they are installed with the platform SDK (or Visual Studio). However the header files are only compatible with OpenGL 1.1. You need to create function pointers for new functionality it later versions. Can you please clarify what version of OpenGL you're trying to use.

How do I reverse a commit in git?

I think you need to push a revert commit. So pull from github again, including the commit you want to revert, then use git revert and push the result.

If you don't care about other people's clones of your github repository being broken, you can also delete and recreate the master branch on github after your reset: git push origin :master.

Pointer to class data member "::*"

Another application are intrusive lists. The element type can tell the list what its next/prev pointers are. So the list does not use hard-coded names but can still use existing pointers:

// say this is some existing structure. And we want to use
// a list. We can tell it that the next pointer
// is apple::next.
struct apple {
    int data;
    apple * next;
};

// simple example of a minimal intrusive list. Could specify the
// member pointer as template argument too, if we wanted:
// template<typename E, E *E::*next_ptr>
template<typename E>
struct List {
    List(E *E::*next_ptr):head(0), next_ptr(next_ptr) { }

    void add(E &e) {
        // access its next pointer by the member pointer
        e.*next_ptr = head;
        head = &e;
    }

    E * head;
    E *E::*next_ptr;
};

int main() {
    List<apple> lst(&apple::next);

    apple a;
    lst.add(a);
}

MySQL Creating tables with Foreign Keys giving errno: 150

execute below line before creating table : SET FOREIGN_KEY_CHECKS = 0;

FOREIGN_KEY_CHECKS option specifies whether or not to check foreign key constraints for InnoDB tables.

-- Specify to check foreign key constraints (this is the default)

SET FOREIGN_KEY_CHECKS = 1;

 

-- Do not check foreign key constraints

SET FOREIGN_KEY_CHECKS = 0;

When to Use : Temporarily disabling referential constraints (set FOREIGN_KEY_CHECKS to 0) is useful when you need to re-create the tables and load data in any parent-child order

How to include files outside of Docker's build context?

I believe the simpler workaround would be to change the 'context' itself.

So, for example, instead of giving:

docker build -t hello-demo-app .

which sets the current directory as the context, let's say you wanted the parent directory as the context, just use:

docker build -t hello-demo-app ..

What's the difference between ViewData and ViewBag?

ViewBag and ViewData are two means which are used to pass information from controller to view in ASP.Net MVC. The goal of using both mechanism is to provide the communicaton between controller and View. Both have short life that is the value of both becomes null once the redirection has occured ie, once the page has redirected from the source page (where we set the value of ViewBag or ViewData) to the target page , both ViewBag as well as ViewData becomes null.

Despite having these similarities both (ViewBag and ViewData) are two different things if we talk about the implementation of both. The differences are as follows :

1.) If we analyse both implementation wise then we will find that ViewData is a dictionary data structure - Dictionary of Objects derived from ViewDataDictionary and accessible using strings as Keys to these values while ViewBag makes use of the dynamic features introduced in C#4.0 and is a dynamic property.

2.) While accessing the values form ViewData , we need to typecast the values (datatypes) as they are stored as Objects in the ViewData dictionary but there is no such need if we are accessing th value in case of ViewBag.

3.) In ViewBag we can set the value like this :

      ViewBag.Name = "Value"; 

and can access as follows:

          @ViewBag.Name

While in case of ViewData the values can be set and accessed as follows: Setting ViewData as follows :

ViewData["Name"] = "Value";

and accessing value like this

 @ViewData["Name"] 

For more details click here:

Create a view with ORDER BY clause

As one of the comments in this posting suggests using stored procedures to return the data... I think that is the best answer. In my case what I did is wrote a View to encapsulate the query logic and joins, then I wrote a Stored Proc to return the data sorted and the proc also includes other enhancement features such as parameters for filtering the data.

Now you have to option to query the view, which allows you to manipulate the data further. Or you have the option to execute the stored proc, which is quicker and more precise output.

STORED PROC Execution to query data

exec [olap].[uspUsageStatsLogSessionsRollup]

VIEW Definition

USE [DBA]
GO

/****** Object:  View [olap].[vwUsageStatsLogSessionsRollup]    Script Date: 2/19/2019 10:10:06 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


--USE DBA
-- select * from olap.UsageStatsLog_GCOP039 where CubeCommand='[ORDER_HISTORY]'
;

ALTER VIEW [olap].[vwUsageStatsLogSessionsRollup] as
(
    SELECT --*
        t1.UsageStatsLogDate
        , COALESCE(CAST(t1.UsageStatsLogDate AS nvarchar(100)), 'TOTAL- DATES:') AS UsageStatsLogDate_Totals
        , t1.ADUserNameDisplayNEW
        , COALESCE(t1.ADUserNameDisplayNEW, 'TOTAL- USERS:') AS ADUserNameDisplay_Totals
        , t1.CubeCommandNEW
        , COALESCE(t1.CubeCommandNEW, 'TOTAL- CUBES:') AS CubeCommand_Totals
        , t1.SessionsCount
        , t1.UsersCount
        , t1.CubesCount
    FROM
    (
        select 
            CAST(olapUSL.UsageStatsLogTime as date) as UsageStatsLogDate
            , olapUSL.ADUserNameDisplayNEW
            , olapUSL.CubeCommandNEW
            , count(*) SessionsCount
            , count(distinct olapUSL.ADUserNameDisplayNEW) UsersCount
            , count(distinct olapUSL.CubeCommandNEW) CubesCount
        from 
            olap.vwUsageStatsLog olapUSL
        where CubeCommandNEW != '[]'
        GROUP BY CUBE(CAST(olapUSL.UsageStatsLogTime as date), olapUSL.ADUserNameDisplayNEW, olapUSL.CubeCommandNEW )
            ----GROUP BY 
            ------GROUP BY GROUPING SETS
            --------GROUP BY ROLLUP
    ) t1

    --ORDER BY
    --  t1.UsageStatsLogDate DESC
    --  , t1.ADUserNameDisplayNEW
    --  , t1.CubeCommandNEW
)
;


GO

STORED PROC Definition

USE [DBA]
GO

/****** Object:  StoredProcedure [olap].[uspUsageStatsLogSessionsRollup]    Script Date: 2/19/2019 9:39:31 AM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO


-- =============================================
-- Author:      BRIAN LOFTON
-- Create date: 2/19/2019
-- Description: This proceedured returns data from a view with sorted results and an optional date range filter.
-- =============================================
ALTER PROCEDURE [olap].[uspUsageStatsLogSessionsRollup]
    -- Add the parameters for the stored procedure here
    @paramStartDate date = NULL,
    @paramEndDate date = NULL,
    @paramDateTotalExcluded as int = 0,
    @paramUserTotalExcluded as int = 0,
    @paramCubeTotalExcluded as int = 0
AS

BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from interfering with SELECT statements.
    SET NOCOUNT ON;

    DECLARE @varStartDate as date 
        = CASE  
            WHEN @paramStartDate IS NULL THEN '1900-01-01' 
            ELSE @paramStartDate 
        END
    DECLARE @varEndDate as date 
        = CASE  
            WHEN @paramEndDate IS NULL THEN '2100-01-01' 
            ELSE @paramStartDate 
        END

    -- Return Data from this statement
    SELECT 
        t1.UsageStatsLogDate_Totals
        , t1.ADUserNameDisplay_Totals
        , t1.CubeCommand_Totals
        , t1.SessionsCount
        , t1.UsersCount
        , t1.CubesCount
        -- Fields with NULL in the totals
            --  , t1.CubeCommandNEW
            --  , t1.ADUserNameDisplayNEW
            --  , t1.UsageStatsLogDate
    FROM 
        olap.vwUsageStatsLogSessionsRollup t1
    WHERE

        (
            --t1.UsageStatsLogDate BETWEEN @varStartDate AND @varEndDate
            t1.UsageStatsLogDate BETWEEN '1900-01-01' AND '2100-01-01'
            OR t1.UsageStatsLogDate IS NULL
        )
        AND
        (
            @paramDateTotalExcluded=0
            OR (@paramDateTotalExcluded=1 AND UsageStatsLogDate_Totals NOT LIKE '%TOTAL-%')
        )
        AND
        (
            @paramDateTotalExcluded=0
            OR (@paramUserTotalExcluded=1 AND ADUserNameDisplay_Totals NOT LIKE '%TOTAL-%')
        )
        AND
        (
            @paramCubeTotalExcluded=0
            OR (@paramCubeTotalExcluded=1 AND CubeCommand_Totals NOT LIKE '%TOTAL-%')
        )
    ORDER BY
            t1.UsageStatsLogDate DESC
            , t1.ADUserNameDisplayNEW
            , t1.CubeCommandNEW

END


GO

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

How to fix the session_register() deprecated issue?

Don't use it. The description says:

Register one or more global variables with the current session.

Two things that came to my mind:

  1. Using global variables is not good anyway, find a way to avoid them.
  2. You can still set variables with $_SESSION['var'] = "value".

See also the warnings from the manual:

If you want your script to work regardless of register_globals, you need to instead use the $_SESSION array as $_SESSION entries are automatically registered. If your script uses session_register(), it will not work in environments where the PHP directive register_globals is disabled.

This is pretty important, because the register_globals directive is set to False by default!

Further:

This registers a global variable. If you want to register a session variable from within a function, you need to make sure to make it global using the global keyword or the $GLOBALS[] array, or use the special session arrays as noted below.

and

If you are using $_SESSION (or $HTTP_SESSION_VARS), do not use session_register(), session_is_registered(), and session_unregister().

Python import csv to list

Next is a piece of code which uses csv module but extracts file.csv contents to a list of dicts using the first line which is a header of csv table

import csv
def csv2dicts(filename):
  with open(filename, 'rb') as f:
    reader = csv.reader(f)
    lines = list(reader)
    if len(lines) < 2: return None
    names = lines[0]
    if len(names) < 1: return None
    dicts = []
    for values in lines[1:]:
      if len(values) != len(names): return None
      d = {}
      for i,_ in enumerate(names):
        d[names[i]] = values[i]
      dicts.append(d)
    return dicts
  return None

if __name__ == '__main__':
  your_list = csv2dicts('file.csv')
  print your_list

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag

The rules for turning on the carry flag in binary/integer math are two:

  1. The carry flag is set if the addition of two numbers causes a carry out of the most significant (leftmost) bits added. 1111 + 0001 = 0000 (carry flag is turned on)

  2. The carry (borrow) flag is also set if the subtraction of two numbers requires a borrow into the most significant (leftmost) bits subtracted. 0000 - 0001 = 1111 (carry flag is turned on) Otherwise, the carry flag is turned off (zero).

    • 0111 + 0001 = 1000 (carry flag is turned off [zero])
    • 1000 - 0001 = 0111 (carry flag is turned off [zero])

In unsigned arithmetic, watch the carry flag to detect errors.

In signed arithmetic, the carry flag tells you nothing interesting.

Overflow Flag

The rules for turning on the overflow flag in binary/integer math are two:

  1. If the sum of two numbers with the sign bits off yields a result number with the sign bit on, the "overflow" flag is turned on. 0100 + 0100 = 1000 (overflow flag is turned on)

  2. If the sum of two numbers with the sign bits on yields a result number with the sign bit off, the "overflow" flag is turned on. 1000 + 1000 = 0000 (overflow flag is turned on)

Otherwise the "overflow" flag is turned off

  • 0100 + 0001 = 0101 (overflow flag is turned off)
  • 0110 + 1001 = 1111 (overflow flag turned off)
  • 1000 + 0001 = 1001 (overflow flag turned off)
  • 1100 + 1100 = 1000 (overflow flag is turned off)

Note that you only need to look at the sign bits (leftmost) of the three numbers to decide if the overflow flag is turned on or off.

If you are doing two's complement (signed) arithmetic, overflow flag on means the answer is wrong - you added two positive numbers and got a negative, or you added two negative numbers and got a positive.

If you are doing unsigned arithmetic, the overflow flag means nothing and should be ignored.

For more clarification please refer: http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt

How do I escape double quotes in attributes in an XML String in T-SQL?

tSql escapes a double quote with another double quote. So if you wanted it to be part of your sql string literal you would do this:

declare @xml xml 
set @xml = "<transaction><item value=""hi"" /></transaction>"

If you want to include a quote inside a value in the xml itself, you use an entity, which would look like this:

declare @xml xml
set @xml = "<transaction><item value=""hi &quot;mom&quot; lol"" /></transaction>"

How to store and retrieve a dictionary with redis

you can pickle your dict and save as string.

import pickle
import redis

r = redis.StrictRedis('localhost')
mydict = {1:2,2:3,3:4}
p_mydict = pickle.dumps(mydict)
r.set('mydict',p_mydict)

read_dict = r.get('mydict')
yourdict = pickle.loads(read_dict)

How to show text on image when hovering?

In your HTML, try and put the text that you want to come up in the title part of the code:

<a  href="buzz.html" title="buzz hover text">

You can also do the same for the alt text of your image.

Removing X-Powered-By

I think that is controlled by the expose_php setting in PHP.ini:

expose_php = off

Decides whether PHP may expose the fact that it is installed on the server (e.g. by adding its signature to the Web server header). It is no security threat in any way, but it makes it possible to determine whether you use PHP on your server or not.

There is no direct security risk, but as David C notes, exposing an outdated (and possibly vulnerable) version of PHP may be an invitation for people to try and attack it.

How to get base url with jquery or javascript?

This one will help you...

var getUrl = window.location;
var baseUrl = getUrl .protocol + "//" + getUrl.host + "/" + getUrl.pathname.split('/')[1];

Superscript in Python plots

Alternatively, in python 3.6+, you can generate Unicode superscript and copy paste that in your code:

ax1.set_ylabel('Rate (min?¹)')

Unpivot with column name

Your query is very close. You should be able to use the following which includes the subject in the final select list:

select u.name, u.subject, u.marks
from student s
unpivot
(
  marks
  for subject in (Maths, Science, English)
) u;

See SQL Fiddle with demo

Count characters in textarea

Seems like the most reusable and elegant solution combines the abive to take MaxLength from the Input attribute and then reference the Span element with a predictable id....

Then to use, all you need to do is add '.countit' to the Input class and 'counter_' + [input-ID] to your span

HTML

<textarea class="countit" name="name" maxlength='6' id="post"></textarea>
<span>characters remaining: <span id="counter_name"></span></span>
<br>
<textarea class="countit" name="post" maxlength='20' id="post"></textarea>
<span>characters remaining: <span id="counter_post"></span></span>
<br>
<textarea class="countit" name="desc" maxlength='10' id="desc"></textarea>
<span>characters remaining: <span id="counter_desc"></span></span>

Jquery

$(".countit").keyup(function () {
  var maxlength = $(this).attr("maxlength");
  var currentLength = $(this).val().length;

  if( currentLength >= maxlength ){
    $("#counter_" + $(this).attr("id")).html(currentLength + ' / ' + maxlength);
    }else{
    $("#counter_" + $(this).attr("id")).html(maxlength - currentLength + " chars left");
  }
});

jquery - check length of input field?

That doesn't work because, judging by the rest of the code, the initial value of the text input is "Default text" - which is more than one character, and so your if condition is always true.

The simplest way to make it work, it seems to me, is to account for this case:

    var value = $(this).val();
    if ( value.length > 0 && value != "Default text" ) ...

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

It is not the asker's problem in this instance but the first troubleshooting step for a generic "AttributeError: __exit__" should be making sure the brackets are there, e.g.

with SomeContextManager() as foo:
    #works because a new object is referenced...

not

with SomeContextManager as foo:
    #AttributeError because the class is referenced

Catches me out from time to time and I end up here -__-

change type of input field with jQuery

I received the same error message while attempting to do this in Firefox 5.

I solved it using the code below:

<script type="text/javascript" language="JavaScript">

$(document).ready(function()
{
    var passfield = document.getElementById('password_field_id');
    passfield.type = 'text';
});

function focusCheckDefaultValue(field, type, defaultValue)
{
    if (field.value == defaultValue)
    {
        field.value = '';
    }
    if (type == 'pass')
    {
        field.type = 'password';
    }
}
function blurCheckDefaultValue(field, type, defaultValue)
{
    if (field.value == '')
    {
        field.value = defaultValue;
    }
    if (type == 'pass' && field.value == defaultValue)
    {
        field.type = 'text';
    }
    else if (type == 'pass' && field.value != defaultValue)
    {
        field.type = 'password';
    }
}

</script>

And to use it, just set the onFocus and onBlur attributes of your fields to something like the following:

<input type="text" value="Username" name="username" id="username" 
    onFocus="javascript:focusCheckDefaultValue(this, '', 'Username -OR- Email Address');"
    onBlur="javascript:blurCheckDefaultValue(this, '', 'Username -OR- Email Address');">

<input type="password" value="Password" name="pass" id="pass"
    onFocus="javascript:focusCheckDefaultValue(this, 'pass', 'Password');"
    onBlur="javascript:blurCheckDefaultValue(this, 'pass', 'Password');">

I use this for a username field as well, so it toggles a default value. Just set the second parameter of the function to '' when you call it.

Also it might be worth noting that the default type of my password field is actually password, just in case a user doesn't have javascript enabled or if something goes wrong, that way their password is still protected.

The $(document).ready function is jQuery, and loads when the document has finished loading. This then changes the password field to a text field. Obviously you'll have to change 'password_field_id' to your password field's id.

Feel free to use and modify the code!

Hope this helps everyone who had the same problem I did :)

-- CJ Kent

EDIT: Good solution but not absolute. Works on on FF8 and IE8 BUT not fully on Chrome(16.0.912.75 ver). Chrome does not display the Password text when the page loads. Also - FF will display your password when autofill is switched on.

How to open an Excel file in C#?

It's easier to help you if you say what's wrong as well, or what fails when you run it.

But from a quick glance you've confused a few things.

The following doesn't work because of a couple of issues.

if (Directory("C:\\csharp\\error report1.xls") = "")

What you are trying to do is creating a new Directory object that should point to a file and then check if there was any errors.

What you are actually doing is trying to call a function named Directory() and then assign a string to the result. This won't work since 1/ you don't have a function named Directory(string str) and you cannot assign to the result from a function (you can only assign a value to a variable).

What you should do (for this line at least) is the following

FileInfo fi = new FileInfo("C:\\csharp\\error report1.xls");
if(!fi.Exists)
{
    // Create the xl file here
}
else
{
    // Open file here
}

As to why the Excel code doesn't work, you have to check the documentation for the Excel library which google should be able to provide for you.

Setting up SSL on a local xampp/apache server

Apache part - enabling you to open https://localhost/xyz

There is the config file xampp/apache/conf/extra/httpd-ssl.conf which contains all the ssl specific configuration. It's fairly well documented, so have a read of the comments and take look at http://httpd.apache.org/docs/2.2/ssl/. The files starts with <IfModule ssl_module>, so it only has an effect if the apache has been started with its mod_ssl module.

Open the file xampp/apache/conf/httpd.conf in an editor and search for the line

#LoadModule ssl_module modules/mod_ssl.so

remove the hashmark, save the file and re-start the apache. The webserver should now start with xampp's basic/default ssl confguration; good enough for testing but you might want to read up a bit more about mod_ssl in the apache documentation.


PHP part - enabling adldap to use ldap over ssl

adldap needs php's openssl extension to use "ldap over ssl" connections. The openssl extension ships as a dll with xampp. You must "tell" php to load this dll, e.g. by having an extension=nameofmodule.dll in your php.ini
Run

echo 'ini: ', get_cfg_var('cfg_file_path');

It should show you which ini file your php installation uses (may differ between the php-apache-module and the php-cli version).
Open this file in an editor and search for

;extension=php_openssl.dll

remove the semicolon, save the file and re-start the apache.

see also: http://docs.php.net/install.windows.extensions

Pass multiple values with onClick in HTML link

A few things here...

If you want to call a function when the onclick event happens, you'll just want the function name plus the parameters.

Then if your parameters are a variable (which they look like they are), then you won't want quotes around them. Not only that, but if these are global variables, you'll want to add in "window." before that, because that's the object that holds all global variables.

Lastly, if these parameters aren't variables, you'll want to exclude the slashes to escape those characters. Since the value of onclick is wrapped by double quotes, single quotes won't be an issue. So your answer will look like this...

<a href=# onclick="ReAssign('valuationId', window.user)">Re-Assign</a>

There are a few extra things to note here, if you want more than a quick solution.

You looked like you were trying to use the + operator to combine strings in HTML. HTML is a scripting language, so when you're writing it, the whole thing is just a string itself. You can just skip these from now on, because it's not code your browser will be running (just a whole bunch of stuff, and anything that already exists is what has special meaning by the browser).

Next, you're using an anchor tag/link that doesn't actually take the user to another website, just runs some code. I'd use something else other than an anchor tag, with the appropriate CSS to format it to look the way you want. It really depends on the setting, but in many cases, a span tag will do. Give it a class (like class="runjs") and have a rule of CSS for that. To get it to imitate a link's behavior, use this:

.runjs {
    cursor: pointer;
    text-decoration: underline;
    color: blue;
}

This lets you leave out the href attribute which you weren't using anyways.

Last, you probably want to use JavaScript to set the value of this link's onclick attribute instead of hand writing it. It keeps your page cleaner by keeping the code of your page separate from what the structure of your page. In your class, you could change all these links like this...

var links = document.getElementsByClassName('runjs');
for(var i = 0; i < links.length; i++)
    links[i].onclick = function() { ReAssign('valuationId', window.user); };

While this won't work in some older browsers (because of the getElementsByClassName method), it's just three lines and does exactly what you're looking for. Each of these links has an anonymous function tied to them meaning they don't have any variable tied to them except that tag's onclick value. Plus if you wanted to, you could include more lines of code this way, all grouped up in one tidy location.

Automatic confirmation of deletion in powershell

The default is: no prompt.

You can enable it with -Confirm or disable it with -Confirm:$false

However, it will still prompt, when the target:

  • is a directory
  • and it is not empty
  • and the -Recurse parameter is not specified.

-Force is required to also remove hidden and read-only items etc.

To sum it up:

Remove-Item -Recurse -Force -Confirm:$false

...should cover all scenarios.

Count the cells with same color in google spreadsheet

here is a working version :

function countbackgrounds() {
 var book = SpreadsheetApp.getActiveSpreadsheet();
 var range_input = book.getRange("B3:B4");
 var range_output = book.getRange("B6");
 var cell_colors = range_input.getBackgroundColors();
 var color = "#58FA58";
 var count = 0;

 for( var i in cell_colors ){
 Logger.log(cell_colors[i][0])
  if( cell_colors[i][0] == color ){ ++count }
  }
range_output.setValue(count);
 }  

Make install, but not to default directories?

Since don't know which version of automake you can use DESTDIR environment variable.
See Makefile to be sure.

For example:

 export DESTDIR="$HOME/Software/LocalInstall" && make -j4 install

Assert an object is a specific type

Solution for JUnit 5 for Kotlin!

Example for Hamcrest:

import org.hamcrest.CoreMatchers
import org.hamcrest.MatcherAssert
import org.junit.jupiter.api.Test

class HamcrestAssertionDemo {

    @Test
    fun assertWithHamcrestMatcher() {
        val subClass = SubClass()
        MatcherAssert.assertThat(subClass, CoreMatchers.instanceOf<Any>(BaseClass::class.java))
    }

}

Example for AssertJ:

import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test

class AssertJDemo {

    @Test
    fun assertWithAssertJ() {
        val subClass = SubClass()
        assertThat(subClass).isInstanceOf(BaseClass::class.java)
    }

}

How to install wkhtmltopdf on a linux based (shared hosting) web server

Place the wkhtmltopdf executable on the server and chmod it +x.

Create an executable shell script wrap.sh containing:

#!/bin/sh
export HOME="$PWD"
export LD_LIBRARY_PATH="$PWD/lib/"
exec $@ 2>/dev/null
#exec $@ 2>&1 # debug mode

Download needed shared objects for that architecture and place them an a folder named "lib":

  • lib/libfontconfig.so.1
  • lib/libfontconfig.so.1.3.0
  • lib/libfreetype.so.6
  • lib/libfreetype.so.6.3.18
  • lib/libX11.so.6 lib/libX11.so.6.2.0
  • lib/libXau.so.6 lib/libXau.so.6.0.0
  • lib/libxcb.so.1 lib/libxcb.so.1.0.0
  • lib/libxcb-xlib.so.0
  • lib/libxcb-xlib.so.0.0.0
  • lib/libXdmcp.so.6
  • lib/libXdmcp.so.6.0.0
  • lib/libXext.so.6 lib/libXext.so.6.4.0

(some of them are symlinks)

… and you're ready to go:

./wrap.sh ./wkhtmltopdf-amd64 --page-size A4 --disable-internal-links --disable-external-links "http://www.example.site/" out.pdf

If you experience font problems like squares for all the characters, define TrueType fonts explicitly:

@font-face {
  font-family:Trebuchet MS;
  font-style:normal;
  font-weight:normal;
  src:url("http://www.yourserver.tld/fonts/Trebuchet_MS.ttf");
  format(TrueType);
}

how to get all child list from Firebase android

mDatabase.child("token").addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
              for (DataSnapshot snapshot:dataSnapshot.getChildren())
              {
                 String key= snapshot.getKey();
                 String value=snapshot.getValue().toString();
              }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(ListUser.this,databaseError.toString(),Toast.LENGTH_SHORT).show();
            }
        });

Only work If child have no SubChild

enter image description here

css padding is not working in outlook

To create HTML in email template that is emailer/newsletter, padding/margin is not supporting on email clients. You can take 1x1 size of blank gif image and use it.

<tr>
  <td align="left" valign="top" style="background-color:#7d9aaa;">
    <table width="640" cellspacing="0" cellpadding="0" border="0">
      <tr>
        <td align="left" valign="top" colspan="5"><img style="display:block;" src="images/spacer.gif" width="1" height="10"  alt="" /></td>
      </tr>
      <tr>
        <td align="left" valign="top"><img style="display:block;" src="images/spacer.gif" width="20" height="1"  alt="" /></td>
        <td align="right" valign="top"><font face="arial" color="#ffffff" style="font-size:14px;"><a href="#" style="color:#ffffff; text-decoration:none; cursor:pointer;" target="_blank">Order Confirmation</a></font></td>
        <td align="left" valign="top" width="200"><img style="display:block;" src="images/spacer.gif" width="200" height="1"  alt="" /></td>
        <td align="left" valign="top"><font face="arial" color="#ffffff" style="font-size:14px;">Your Confirmation Number is 260556</font></td>
        <td align="left" valign="top"><img style="display:block;" src="images/spacer.gif" width="20" height="1"  alt="" /></td>
      </tr>
      <tr>
        <td align="left" valign="top" colspan="5"><img style="display:block;" src="images/spacer.gif" width="1" height="10"  alt="" /></td>
      </tr>
    </table>
</td>
</tr>

How do I remove javascript validation from my eclipse project?

Window -> Preferences -> JavaScript -> Validator (also per project settings possible)

or

Window -> Preferences -> Validation (disable validations and configure their settings)

How to get a table cell value using jQuery?

If you can, it might be worth using a class attribute on the TD containing the customer ID so you can write:

$('#mytable tr').each(function() {
    var customerId = $(this).find(".customerIDCell").html();    
 });

Essentially this is the same as the other solutions (possibly because I copy-pasted), but has the advantage that you won't need to change the structure of your code if you move around the columns, or even put the customer ID into a <span>, provided you keep the class attribute with it.

By the way, I think you could do it in one selector:

$('#mytable .customerIDCell').each(function() {
  alert($(this).html());
});

If that makes things easier.

pass post data with window.location.href

Have you considered simply using Local/Session Storage? -or- Depending on the complexity of what you're building; you could even use indexDB.

note:

Local storage and indexDB are not secure - so you want to avoid storing any sensitive / personal data (i.e names, addresses, emails addresses, DOB etc) in either of these.

Session Storage is a more secure option for anything sensitive, it's only accessible to the origin that set the items and also clears as soon as the browser / tab is closed.

IndexDB is a little more [but not much more] complicated and is a 30MB noSQL database built into every browser (but can be basically unlimited if the user opts in) -> next time you're using Google docs, open you DevTools -> application -> IndexDB and take a peak. [spoiler alert: it's encrypted].

Focusing on Local and Session Storage; these are both dead simple to use:

// To Set 
sessionStorage.setItem( 'key' , 'value' );

// e.g.
sessionStorage.setItem( 'formData' , { name: "Mr Manager", company: "Bluth's Frozen Bananas", ...  } );    

// Get The Data 
const fromData = sessionStorage.getItem( 'key' );     

// e.g. (after navigating to next location)
const fromData = sessionStorage.getItem( 'formData' );

// Remove 
sessionStorage.removeItem( 'key' );

// Remove _all_ saved data sessionStorage
sessionStorage.clear( ); 

If simple is not your thing -or- maybe you want to go off road and try a different approach all together -> you can probably use a shared web worker... y'know, just for kicks.

How to call javascript function from asp.net button click event

You're already prepending the hash sign in your showDialog() function, and you're missing single quotes in your second code snippet. You should also return false from the handler to prevent a postback from occurring. Try:

<asp:Button ID="ButtonAdd" runat="server" Text="Add"
    OnClientClick="showDialog('<%=addPerson.ClientID %>'); return false;" />

List only stopped Docker containers

docker container list -f "status=exited"

or

docker container ls -f "status=exited"

or

 docker ps -f "status=exited"

Get list of passed arguments in Windows batch script (.bat)

@echo off
:start

:: Insert your code here
echo.%%1 is now:%~1
:: End insert your code here

if "%~2" NEQ "" (
    shift
    goto :start
)

jackson deserialization json to java-objects

Your product class needs a parameterless constructor. You can make it private, but Jackson needs the constructor.

As a side note: You should use Pascal casing for your class names. That is Product, and not product.

Convert JSON to DataTable

You can make use of JSON.Net here. Take a look at JsonConvert.DeserializeObject method.

CSS word-wrapping in div

It's pretty hard to say definitively without seeing what the rendered html looks like and what styles are being applied to the elements within the treeview div, but the thing that jumps out at me right away is the

overflow-x: scroll;

What happens if you remove that?

In the shell, what does " 2>&1 " mean?

I found this very helpful if you are a beginner read this

Update:
In Linux or Unix System there are two places programs send output to: Standard output (stdout) and Standard Error (stderr).You can redirect these output to any file.

Like if you do this

ls -a > output.txt

Nothing will be printed in console all output (stdout) is redirected to output file.

And if you try print the content of any file that does not exits means output will be an error like if you print test.txt that not present in current directory

cat test.txt > error.txt

Output will be

cat: test.txt :No such file or directory

But error.txt file will be empty because we redirecting the stdout to a file not stderr.

so we need file descriptor( A file descriptor is nothing more that a positive integer that represents an open file. You can say descriptor is unique id of file) to tell shell which type of output we are sending to file .In Unix /Linux system 1 is for stdout and 2 for stderr.

so now if you do this

ls -a 1> output.txt means you are sending Standard output (stdout) to output.txt.

and if you do this

cat test.txt 2> error.txt means you are sending Standard Error (stderr) to error.txt .

&1 is used to reference the value of the file descriptor 1 (stdout).

Now to the point 2>&1 means “Redirect the stderr to the same place we are redirecting the stdout”

Now you can do this

cat maybefile.txt > output.txt 2>&1

both Standard output (stdout) and Standard Error (stderr) will redirected to output.txt.

Thanks to Ondrej K. for pointing out

How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7

On CYGwin, you can install this as a typical package in the first screen. Look for

libssl-devel

set default schema for a sql query

Another way of adding schema dynamically or if you want to change it to something else

DECLARE @schema AS VARCHAR(256) = 'dbo.'
--User can also use SELECT SCHEMA_NAME() to get the default schema name


DECLARE @ID INT

declare @SQL nvarchar(max) = 'EXEC ' + @schema +'spSelectCaseBookingDetails @BookingID = '  + CAST(@ID AS NVARCHAR(10))

No need to cast @ID if it is nvarchar or varchar

execute (@SQL)

calculating the difference in months between two dates

My take on this answer also uses an extension method, but it can return a positive or negative result.

public static int MonthsBefore(this DateTime dt1, DateTime dt2)
{
    (DateTime early, DateTime late, bool dt2After) = dt2 > dt1 ? (dt1,dt2,true) : (dt2,dt1,false);
    DateTime tmp; // Save the result so we don't repeat work
    int months = 1;
    while ((tmp = early.AddMonths(1)) <= late)
    {
        early = tmp;
        months++;
    }
    return (months-1)*(dt2After ? 1 : -1);
}

A couple tests:

// Just under 1 month's diff
Assert.AreEqual(0, new DateTime(2014, 1, 1).MonthsBefore(new DateTime(2014, 1, 31)));
// Just over 1 month's diff
Assert.AreEqual(1, new DateTime(2014, 1, 1).MonthsBefore(new DateTime(2014, 2, 2)));    
// Past date returns NEGATIVE
Assert.AreEqual(-6, new DateTime(2012, 1, 1).MonthsBefore(new DateTime(2011, 6, 10)));

Managing jQuery plugin dependency in webpack

For global access to jquery then several options exist. In my most recent webpack project, I wanted global access to jquery so I added the following to my plugins declarations:

 plugins: [
    new webpack.ProvidePlugin({
      $: "jquery",
      jQuery: "jquery"
    })
  ]

This then means that jquery is accessible from within the JavaScript source code via global references $ and jQuery.

Of course, you need to have also installed jquery via npm:

$ npm i jquery --save

For a working example of this approach please feel free to fork my app on github

What is the difference between printf() and puts() in C?

When comparing puts() and printf(), even though their memory consumption is almost the same, puts() takes more time compared to printf().

Change Bootstrap tooltip color

Important to note, as of Bootstrap 4 you can customize these styles directly in your Bootstrap Sass variables file, so in _variables.scss you have these options:

//== Tooltips
//
//##

// ** Tooltip max width
$tooltip-max-width:           200px !default;
// ** Tooltip text color
$tooltip-color:               #fff !default;
// ** Tooltip background color
$tooltip-bg:                  #000 !default;
$tooltip-opacity:             .9 !default;

// ** Tooltip arrow width
$tooltip-arrow-width:         5px !default;
// ** Tooltip arrow color
$tooltip-arrow-color:         $tooltip-bg !default;

See here: http://v4-alpha.getbootstrap.com/getting-started/options/

Best to work in Sass and compile as you go with Grunt or Gulp build tools.

how can select from drop down menu and call javascript function

<select name="aa" onchange="report(this.value)"> 
  <option value="">Please select</option>
  <option value="daily">daily</option>
  <option value="monthly">monthly</option>
</select>

using

function report(period) {
  if (period=="") return; // please select - possibly you want something else here

  const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
  loadXMLDoc(report,'responseTag');
  document.getElementById('responseTag').style.visibility='visible';
  document.getElementById('list_report').style.visibility='hidden';
  document.getElementById('formTag').style.visibility='hidden'; 
} 

Unobtrusive version:

<select id="aa" name="aa"> 
  <option value="">Please select</option>
  <option value="daily">daily</option>
  <option value="monthly">monthly</option>
</select>

using

window.addEventListener("load",function() {
  document.getElementById("aa").addEventListener("change",function() {
    const period = this.value;
    if (period=="") return; // please select - possibly you want something else here

    const report = "script/"+((period == "daily")?"d":"m")+"_report.php";
    loadXMLDoc(report,'responseTag');
    document.getElementById('responseTag').style.visibility='visible';
    document.getElementById('list_report').style.visibility='hidden';
    document.getElementById('formTag').style.visibility='hidden'; 
  }); 
});

jQuery version - same select with ID

$(function() {
  $("#aa").on("change",function() {
    const period = this.value;
    if (period=="") return; // please select - possibly you want something else here

    var report = "script/"+((period == "daily")?"d":"m")+"_report.php";
    loadXMLDoc(report,'responseTag');
    $('#responseTag').show();
    $('#list_report').hide();
    $('#formTag').hide(); 
  }); 
});

Using dig to search for SPF records

The dig utility is pretty convenient to use. The order of the arguments don't really matter.I'll show you some easy examples.
To get all root name servers use

# dig

To get a TXT record of a specific host use

# dig example.com txt
# dig host.example.com txt

To query a specific name server just add @nameserver.tld

# dig host.example.com txt @a.iana-servers.net

The SPF RFC4408 says that SPF records can be stored as SPF or TXT. However nearly all use only TXT records at the moment. So you are pretty safe if you only fetch TXT records.

I made a SPF checker for visualising the SPF records of a domain. It might help you to understand SPF records better. You can find it here: http://spf.myisp.ch

How to filter by IP address in Wireshark?

If you only care about that particular machine's traffic, use a capture filter instead, which you can set under Capture -> Options.

host 192.168.1.101

Wireshark will only capture packet sent to or received by 192.168.1.101. This has the benefit of requiring less processing, which lowers the chances of important packets being dropped (missed).

When do you use Git rebase instead of Git merge?

I just created a FAQ for my team in my own words which answers this question. Let me share:

What is a merge?

A commit, that combines all changes of a different branch into the current.

What is a rebase?

Re-comitting all commits of the current branch onto a different base commit.

What are the main differences between merge and rebase?

  1. merge executes only one new commit. rebase typically executes multiple (number of commits in current branch).
  2. merge produces a new generated commit (the so called merge-commit). rebase only moves existing commits.

In which situations should we use a merge?

Use merge whenever you want to add changes of a branched out branch back into the base branch.

Typically, you do this by clicking the "Merge" button on Pull/Merge Requests, e.g. on GitHub.

In which situations should we use a rebase?

Use rebase whenever you want to add changes of a base branch back to a branched out branch.

Typically, you do this in feature branches whenever there's a change in the main branch.

Why not use merge to merge changes from the base branch into a feature branch?

  1. The git history will include many unnecessary merge commits. If multiple merges were needed in a feature branch, then the feature branch might even hold more merge commits than actual commits!

  2. This creates a loop which destroys the mental model that Git was designed by which causes troubles in any visualization of the Git history.

    Imagine there's a river (e.g. the "Nile"). Water is flowing in one direction (direction of time in Git history). Now and then, imagine there's a branch to that river and suppose most of those branches merge back into the river. That's what the flow of a river might look like naturally. It makes sense.

    But then imagine there's a small branch of that river. Then, for some reason, the river merges into the branch and the branch continues from there. The river has now technically disappeared, it's now in the branch. But then, somehow magically, that branch is merged back into the river. Which river you ask? I don't know. The river should actually be in the branch now, but somehow it still continues to exist and I can merge the branch back into the river. So, the river is in the river. Kind of doesn't make sense.

    This is exactly what happens when you merge the base branch into a feature branch and then when the feature branch is done, you merge that back into the base branch again. The mental model is broken. And because of that, you end up with a branch visualization that's not very helpful.

Example Git History when using merge:

Example Git History when using merge

Note the many commits starting with Merge branch 'develop' into .... They don't even exist if you rebase (there, you will only have pull request merge commits). Also many visual branch merge loops (develop into feature into develop).

Example Git History when using rebase:

Example Git History when using rebase

Much cleaner Git history with much less merge commits and no cluttered visual branch merge loops whatsoever.

Are there any downsides / pitfalls with rebase?

Yes:

  1. Because a rebase moves commits (technically re-executes them), the commit date of all moved commits will be the time of the rebase and the git history loses the initial commit time. So, if the exact date of a commit is needed for some reason, then merge is the better option. But typically, a clean git history is much more useful than exact commit dates.
  2. If the rebased branch has multiple commits that change the same line and that line was also changed in the base branch, you might need to solve merge conflicts for that same line multiple times, which you never need to do when merging. So, on average, there's more merge conflicts to solve.

Tips to reduce merge conflicts when using rebase:

  1. Rebase often. I typically recommend doing it at least once a day.
  2. Try to squash changes on the same line into one commit as much as possible.

How can I read comma separated values from a text file in Java?

//lat=3434&lon=yy38&rd=1.0&| in that format o/p is displaying

public class ReadText {
    public static void main(String[] args) throws Exception {
        FileInputStream f= new FileInputStream("D:/workplace/sample/bookstore.txt");
        BufferedReader br = new BufferedReader(new InputStreamReader(f));
        String strline;
        StringBuffer sb = new StringBuffer();
        while ((strline = br.readLine()) != null)
        {
            String[] arraylist=StringUtils.split(strline, ",");
            if(arraylist.length == 2){
                sb.append("lat=").append(StringUtils.trim(arraylist[0])).append("&lon=").append(StringUtils.trim(arraylist[1])).append("&rt=1.0&|");

            } else {
                System.out.println("Error: "+strline);
            }
        }
        System.out.println("Data: "+sb.toString());
    }
}

Adding blur effect to background in swift

You can make an extension of UIImageView.

Swift 2.0

import Foundation
import UIKit

extension UIImageView
{
    func makeBlurImage(targetImageView:UIImageView?)
    {
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.Dark)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = targetImageView!.bounds

        blurEffectView.autoresizingMask = [.FlexibleWidth, .FlexibleHeight] // for supporting device rotation
        targetImageView?.addSubview(blurEffectView)
    }
}

Usage:

override func viewDidLoad()
{
    super.viewDidLoad()

    let sampleImageView = UIImageView(frame: CGRectMake(0, 200, 300, 325))
    let sampleImage:UIImage = UIImage(named: "ic_120x120")!
    sampleImageView.image =  sampleImage

    //Convert To Blur Image Here
    sampleImageView.makeBlurImage(sampleImageView)

    self.view.addSubview(sampleImageView)
}

Swift 3 Extension

import Foundation
import UIKit

extension UIImageView
{
    func addBlurEffect()
    {
        let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.light)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = self.bounds

        blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // for supporting device rotation
        self.addSubview(blurEffectView)
    }
}

Usage:

yourImageView.addBlurEffect()

Addendum:

extension UIView {
  
  /// Remove UIBlurEffect from UIView
  func removeBlurEffect() {
    let blurredEffectViews = self.subviews.filter{$0 is UIVisualEffectView}
    blurredEffectViews.forEach{ blurView in
      blurView.removeFromSuperview()
    }
  }

Swift 5.0:

import UIKit


extension UIImageView {
    func applyBlurEffect() {
        let blurEffect = UIBlurEffect(style: .light)
        let blurEffectView = UIVisualEffectView(effect: blurEffect)
        blurEffectView.frame = bounds
        blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        addSubview(blurEffectView)
    }
}

How to find where gem files are installed

gem env works just like gem environment. Saves some typing.

# gem env
RubyGems Environment:
  - RUBYGEMS VERSION: 2.0.14
  - RUBY VERSION: 2.0.0 (2014-02-24 patchlevel 451) [i686-linux]
  - INSTALLATION DIRECTORY: /usr/local/lib/ruby/gems/2.0.0
  - RUBY EXECUTABLE: /usr/local/bin/ruby
  - EXECUTABLE DIRECTORY: /usr/local/bin
  - RUBYGEMS PLATFORMS:
    - ruby
    - x86-linux
  - GEM PATHS:
     - /usr/local/lib/ruby/gems/2.0.0
     - /root/.gem/ruby/2.0.0
  - GEM CONFIGURATION:
     - :update_sources => true
     - :verbose => true
     - :backtrace => false
     - :bulk_threshold => 1000
  - REMOTE SOURCES:
     - https://rubygems.org/

How to ignore certain files in Git

By creating a .gitignore file. See here for details: Git Book - Ignoring files

Also check this one out: How do you make Git ignore files without using .gitignore?

How can I check if a scrollbar is visible?

Most of the answers presented got me close to where I needed to be, but not quite there.

We basically wanted to assess if the scroll bars -would- be visible in a normal situation, by that definition meaning that the size of the body element is larger than the view port. This was not a presented solution, which is why I am submitting it.

Hopefully it helps someone!

(function($) {
    $.fn.hasScrollBar = function() {
        return this.get(0).scrollHeight > $(window).height();
    }
})(jQuery);

Essentially, we have the hasScrollbar function, but returning if the requested element is larger than the view port. For view port size, we just used $(window).height(). A quick compare of that against the element size, yields the correct results and desirable behavior.

How to set session timeout in web.config

If it's not working from web.config, you need to set it from IIS.

Multiple argument IF statement - T-SQL

Seems to work fine.

If you have an empty BEGIN ... END block you might see

Msg 102, Level 15, State 1, Line 10 Incorrect syntax near 'END'.

Axios Delete request with body and headers?

I tried all of the above which did not work for me. I ended up just going with PUT (inspiration found here) and just changed my server side logic to perform a delete on this url call. (django rest framework function override).

e.g.

.put(`http://127.0.0.1:8006/api/updatetoken/20`, bayst)
      .then((response) => response.data)
      .catch((error) => { throw error.response.data; });

android image button

just use a Button with android:drawableRight properties like this:

<Button android:id="@+id/btnNovaCompra" android:layout_width="wrap_content"
        android:text="@string/btn_novaCompra"
        android:gravity="center"
        android:drawableRight="@drawable/shoppingcart"
        android:layout_height="wrap_content"/>