Programs & Examples On #Spreadsheetml

Part of the Office Open XML specification ECMA-376

How to save .xlsx data to file as a blob

This works as of: v0.14.0 of https://github.com/SheetJS/js-xlsx

/* generate array buffer */
var wbout = XLSX.write(wb, {type:"array", bookType:'xlsx'});
/* create data URL */
var url = URL.createObjectURL(new Blob([wbout], {type: 'application/octet-stream'}));
/* trigger download with chrome API */
chrome.downloads.download({ url: url, filename: "testsheet.xlsx", saveAs: true });

Writing an Excel file in EPPlus

If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection.

using (ExcelPackage package = new ExcelPackage(file))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");

    worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);

    package.Save();
}

HTML Input="file" Accept Attribute File Type (CSV)

After my test, on ?macOS 10.15.7 Catalina?, the answer of ?Dom / Rikin Patel? cannot recognize the [.xlsx] file normally.

I personally summarized the practice of most of the existing answers and passed personal tests. Sum up the following answers:

accept=".csv, .xls, .xlsx, text/csv, application/csv,
text/comma-separated-values, application/csv, application/excel,
application/vnd.msexcel, text/anytext, application/vnd. ms-excel,
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

Setting mime type for excel document

You should always use below MIME type if you want to serve excel file in xlsx format

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 

How can I use pickle to save a dict?

Simple way to dump a Python data (e.g. dictionary) to a pickle file.

import pickle

your_dictionary = {}

pickle.dump(your_dictionary, open('pickle_file_name.p', 'wb'))

cannot call member function without object

just add static keyword at the starting of the function return type.. and then you can access the member function of the class without object:) for ex:

static void Name_pairs::read_names()
{
   cout << "Enter name: ";
   cin >> name;
   names.push_back(name);
   cout << endl;
}

POST unchecked HTML checkboxes

The problem with checkboxes is that if they are not checked then they are not posted with your form. If you check a checkbox and post a form you will get the value of the checkbox in the $_POST variable which you can use to process a form, if it's unchecked no value will be added to the $_POST variable.

In PHP you would normally get around this problem by doing an isset() check on your checkbox element. If the element you are expecting isn't set in the $_POST variable then we know that the checkbox is not checked and the value can be false.

if(!isset($_POST['checkbox1']))
{
     $checkboxValue = false;
} else {
     $checkboxValue = $_POST['checkbox1'];
}

But if you have created a dynamic form then you won't always know the name attribute of your checkboxes, if you don't know the name of the checkbox then you can't use the isset function to check if this has been sent with the $_POST variable.

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

For anyone looking for a full solution, I got this working with the following code based on maximdim's answer:

import javax.mail.*
import javax.mail.internet.*

private class SMTPAuthenticator extends Authenticator
{
    public PasswordAuthentication getPasswordAuthentication()
    {
        return new PasswordAuthentication('[email protected]', 'test1234');
    }
}

def  d_email = "[email protected]",
        d_uname = "email",
        d_password = "password",
        d_host = "smtp.gmail.com",
        d_port  = "465", //465,587
        m_to = "[email protected]",
        m_subject = "Testing",
        m_text = "Hey, this is the testing email."

def props = new Properties()
props.put("mail.smtp.user", d_email)
props.put("mail.smtp.host", d_host)
props.put("mail.smtp.port", d_port)
props.put("mail.smtp.starttls.enable","true")
props.put("mail.smtp.debug", "true");
props.put("mail.smtp.auth", "true")
props.put("mail.smtp.socketFactory.port", d_port)
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory")
props.put("mail.smtp.socketFactory.fallback", "false")

def auth = new SMTPAuthenticator()
def session = Session.getInstance(props, auth)
session.setDebug(true);

def msg = new MimeMessage(session)
msg.setText(m_text)
msg.setSubject(m_subject)
msg.setFrom(new InternetAddress(d_email))
msg.addRecipient(Message.RecipientType.TO, new InternetAddress(m_to))

Transport transport = session.getTransport("smtps");
transport.connect(d_host, 465, d_uname, d_password);
transport.sendMessage(msg, msg.getAllRecipients());
transport.close();

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

You certainly can define functions in script files (I then tend to load them through my Powershell profile on load).

First you need to check to make sure the function is loaded by running:

ls function:\ | where { $_.Name -eq "A1"  }

And check that it appears in the list (should be a list of 1!), then let us know what output you get!

Android sqlite how to check if a record exists

You can use SELECT EXISTS command and execute it for a cursor using a rawQuery, from the documentation

The EXISTS operator always evaluates to one of the integer values 0 and 1. If executing the SELECT statement specified as the right-hand operand of the EXISTS operator would return one or more rows, then the EXISTS operator evaluates to 1. If executing the SELECT would return no rows at all, then the EXISTS operator evaluates to 0.

Creating java date object from year,month,day

That's my favorite way prior to Java 8:

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

I'd say this is a cleaner approach than:

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

Broadcast Receiver within a Service

as your service is already setup, simply add a broadcast receiver in your service:

private final BroadcastReceiver receiver = new BroadcastReceiver() {
   @Override
   public void onReceive(Context context, Intent intent) {
      String action = intent.getAction();
      if(action.equals("android.provider.Telephony.SMS_RECEIVED")){
        //action for sms received
      }
      else if(action.equals(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED)){
           //action for phone state changed
      }     
   }
};

in your service's onCreate do this:

IntentFilter filter = new IntentFilter();
filter.addAction("android.provider.Telephony.SMS_RECEIVED");
filter.addAction(android.telephony.TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction("your_action_strings"); //further more
filter.addAction("your_action_strings"); //further more

registerReceiver(receiver, filter);

and in your service's onDestroy:

unregisterReceiver(receiver);

and you are good to go to receive broadcast for what ever filters you mention in onCreate. Make sure to add any permission if required. for e.g.

<uses-permission android:name="android.permission.RECEIVE_SMS" />

Pass in an array of Deferreds to $.when()

I had a case very similar where I was posting in an each loop and then setting the html markup in some fields from numbers received from the ajax. I then needed to do a sum of the (now-updated) values of these fields and place in a total field.

Thus the problem was that I was trying to do a sum on all of the numbers but no data had arrived back yet from the async ajax calls. I needed to complete this functionality in a few functions to be able to reuse the code. My outer function awaits the data before I then go and do some stuff with the fully updated DOM.

    // 1st
    function Outer() {
        var deferreds = GetAllData();

        $.when.apply($, deferreds).done(function () {
            // now you can do whatever you want with the updated page
        });
    }

    // 2nd
    function GetAllData() {
        var deferreds = [];
        $('.calculatedField').each(function (data) {
            deferreds.push(GetIndividualData($(this)));
        });
        return deferreds;
    }

    // 3rd
    function GetIndividualData(item) {
        var def = new $.Deferred();
        $.post('@Url.Action("GetData")', function (data) {
            item.html(data.valueFromAjax);
            def.resolve(data);
        });
        return def;
    }

Run PHP function on html button click

Use an AJAX Request on your PHP file, then display the result on your page, without any reloading.

http://api.jquery.com/load/ This is a simple solution if you don't need any POST data.

Defining lists as global variables in Python

Yes, you need to use global foo if you are going to write to it.

foo = []

def bar():
    global foo
    ...
    foo = [1]

html5 audio player - jquery toggle click play/pause?

Here is my solution (if you want to click another element on the page):

$("#button").click(function() {
        var bool = $("#player").prop("muted");
        $("#player").prop("muted",!bool);
        if (bool) {
            $("#player").prop("currentTime",0);
        }
});

Clear and reset form input fields

To clear your form, admitted that your form's elements values are saved in your state, you can map through your state like that :

  // clear all your form
  Object.keys(this.state).map((key, index) => {
      this.setState({[key] : ""});
   });

If your form is among other fields, you can simply insert them in a particular field of the state like that:

 state={ 
        form: {
        name:"",
        email:""}
      }

      // handle set in nested objects
      handleChange = (e) =>{ 
        e.preventDefault(); 

        const newState = Object.assign({}, this.state);
        newState.form[e.target.name] = e.target.value;
        this.setState(newState);
      }

      // submit and clear state in nested object 
      onSubmit = (e) =>{ 
        e.preventDefault(); 

       var form =   Object.assign({}, this.state.form);
       Object.keys(form).map((key, index) => {
          form[key] = "" ;
        });

       this.setState({form})
      } 

Vertical and horizontal align (middle and center) with CSS

This blog post describes two methods of centering a div both horizontally and vertically. One uses only CSS and will work with divs that have a fixed size; the other uses jQuery and will work divs for which you do not know the size in advance.

I've duplicated the CSS and jQuery examples from the blog post's demo here:

CSS

Assuming you have a div with a class of .classname, the css below should work.

The left:50%; top:50%; sets the top left corner of the div to the center of the screen; the margin:-75px 0 0 -135px; moves it to the left and up by half of the width and height of the fixed-size div respectively.

.className{
    width:270px;
    height:150px;
    position:absolute;
    left:50%;
    top:50%;
    margin:-75px 0 0 -135px;
}

jQuery

$(document).ready(function(){
    $(window).resize(function(){
        $('.className').css({
            position:'absolute',
            left: ($(window).width() - $('.className').outerWidth())/2,
            top: ($(window).height() - $('.className').outerHeight())/2
        });
    });
    // To initially run the function:
    $(window).resize();
});

Here's a demo of the techniques in practice.

Difference between numpy dot() and Python 3.5+ matrix multiplication @

Just FYI, @ and its numpy equivalents dot and matmul are all equally fast. (Plot created with perfplot, a project of mine.)

enter image description here

Code to reproduce the plot:

import perfplot
import numpy


def setup(n):
    A = numpy.random.rand(n, n)
    x = numpy.random.rand(n)
    return A, x


def at(data):
    A, x = data
    return A @ x


def numpy_dot(data):
    A, x = data
    return numpy.dot(A, x)


def numpy_matmul(data):
    A, x = data
    return numpy.matmul(A, x)


perfplot.show(
    setup=setup,
    kernels=[at, numpy_dot, numpy_matmul],
    n_range=[2 ** k for k in range(15)],
)

Help with packages in java - import does not work

Just add classpath entry ( I mean your parent directory location) under System Variables and User Variables menu ... Follow : Right Click My Computer>Properties>Advanced>Environment Variables

Pandas group-by and sum

You can set the groupby column to index then using sum with level

df.set_index(['Fruit','Name']).sum(level=[0,1])
Out[175]: 
               Number
Fruit   Name         
Apples  Bob        16
        Mike        9
        Steve      10
Oranges Bob        67
        Tom        15
        Mike       57
        Tony        1
Grapes  Bob        35
        Tom        87
        Tony       15

JRE 1.7 - java version - returns: java/lang/NoClassDefFoundError: java/lang/Object

You cannot install just the 64bit, you must first install the 32bit and then add the 64bit components.

From java.com:

Installing the JRE on a 64-bit system that allows a 32-bit JVM is a two-step process: first install the 32-bit JRE and then install the additional support for 64-bit operations. The file names are as follows:

Using Excel OleDb to get sheet names IN SHEET ORDER

Can't find this in actual MSDN documentation, but a moderator in the forums said

I am afraid that OLEDB does not preserve the sheet order as they were in Excel

Excel Sheet Names in Sheet Order

Seems like this would be a common enough requirement that there would be a decent workaround.

CSS horizontal centering of a fixed div?

left: 50%;
margin-left: -400px; /* Half of the width */

java.io.StreamCorruptedException: invalid stream header: 54657374

Clearly you aren't sending the data with ObjectOutputStream: you are just writing the bytes.

  • If you read with readObject() you must write with writeObject().
  • If you read with readUTF() you must write with writeUTF().
  • If you read with readXXX() you must write with writeXXX(), for most values of XXX.

How to correctly set Http Request Header in Angular 2

The simpler and current approach for adding header to a single request is:

// Step 1

const yourHeader: HttpHeaders = new HttpHeaders({
    Authorization: 'Bearer JWT-token'
});

// POST request

this.http.post(url, body, { headers: yourHeader });

// GET request

this.http.get(url, { headers: yourHeader });

"Please provide a valid cache path" error in laravel

/path/to/laravel/storage/framework/

sessions views cache

Above is working solution

Receiving JSON data back from HTTP request

Install this nuget package from Microsoft System.Net.Http.Json. It contains extension methods.

Then add using System.Net.Http.Json

Now, you'll be able to see these methods:

enter image description here

So you can now do this:

await httpClient.GetFromJsonAsync<IList<WeatherForecast>>("weatherforecast");

Source: https://www.stevejgordon.co.uk/sending-and-receiving-json-using-httpclient-with-system-net-http-json

calling server side event from html button control

You may use event handler serverclick as below

//cmdAction is the id of HTML button as below

<body>
    <form id="form1" runat="server">
        <button type="submit" id="cmdAction" text="Button1" runat="server">
            Button1
        </button>
    </form>
</body>

//cs code

public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
                cmdAction.ServerClick += new EventHandler(submit_click);  
        }

        protected void submit_click(object sender, EventArgs e)
        {
            Response.Write("HTML Server Button Control");
        }
    }

Checking if jquery is loaded using Javascript

Just a small modification that might actually solve the problem:

window.onload = function() {
   if (window.jQuery) {  
       // jQuery is loaded  
       alert("Yeah!");
   } else {
    location.reload();
   }
}

Instead of $(document).Ready(function() use window.onload = function().

Extract a substring from a string in Ruby using a regular expression

"<name> <substring>"[/.*<([^>]*)/,1]
=> "substring"

No need to use scan, if we need only one result.
No need to use Python's match, when we have Ruby's String[regexp,#].

See: http://ruby-doc.org/core/String.html#method-i-5B-5D

Note: str[regexp, capture] ? new_str or nil

Angular 2 TypeScript how to find element in Array

Assume I have below array:

Skins[
    {Id: 1, Name: "oily skin"}, 
    {Id: 2, Name: "dry skin"}
];

If we want to get item with Id = 1 and Name = "oily skin", We'll try as below:

var skinName = skins.find(x=>x.Id == "1").Name;

The result will return the skinName is "Oily skin".

enter image description here

Is there a naming convention for MySQL?

as @fabrizio-valencia said use lower case. in windows if you export mysql database (phpmyadmin) the tables name will converted to lower case and this lead to all sort of problems. see Are table names in MySQL case sensitive?

failed to open stream: No such file or directory in

you can use:

define("PATH_ROOT", dirname(__FILE__));
include_once PATH_ROOT . "/PoliticalForum/headerSite.php";

Set Background cell color in PHPExcel

This code should work for you:

 $PHPExcel->getActiveSheet()
        ->getStyle('A1')
        ->getFill()
        ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
        ->getStartColor()
        ->setRGB('FF0000')

But if you bother using this over and over again, I recommend using applyFromArray.

Strangest language feature

JavaScript:

( {} == {} ) == false

Where does npm install packages?

From the docs:

Packages are dropped into the node_modules folder under the prefix. When installing locally, this means that you can require("packagename") to load its main module, or require("packagename/lib/path/to/sub/module") to load other modules.

Global installs on Unix systems go to {prefix}/lib/node_modules. Global installs on Windows go to {prefix}/node_modules (that is, no lib folder.)

Scoped packages are installed the same way, except they are grouped together in a sub-folder of the relevant node_modules folder with the name of that scope prefix by the @ symbol, e.g. npm install @myorg/package would place the package in {prefix}/node_modules/@myorg/package. See scope for more details.

If you wish to require() a package, then install it locally.

You can get your {prefix} with npm config get prefix. (Useful when you installed node with nvm).

Read about locally.
Read about globally.

Passing just a type as a parameter in C#

foo.GetColumnValues(dm.mainColumn, typeof(string))

Alternatively, you could use a generic method:

public void GetColumnValues<T>(object mainColumn)
{
    GetColumnValues(mainColumn, typeof(T));
}

and you could then use it like:

foo.GetColumnValues<string>(dm.mainColumn);

How do I exit a foreach loop in C#?

Just use the statement:

break;

Zip folder in C#

"Where should I copy ICSharpCode.SharpZipLib.dll to see that namespace in Visual Studio?"

You need to add the dll file as a reference in your project. Right click on References in the Solution Explorer->Add Reference->Browse and then select the dll.

Finally you'll need to add it as a using statement in whatever files you want to use it in.

Comments in Android Layout xml

click the

ctrl+shift+/

and write anything you and evrything will be in comments

how to overlap two div in css?

add to second div bottomDiv

and add this to css.

 .bottomDiv{
       position:relative;
       bottom:150px;
       left:150px;
    }

http://jsfiddle.net/aw8RD/1/

Eclipse keyboard shortcut to indent source code to the left?

On Mac (on french keyboard its) cmd + shift + F

Error: 'int' object is not subscriptable - Python

'int' object is not subscriptable is TypeError in Python. To better understand how this error occurs, let us consider the following example:

list1 = [1, 2, 3]
print(list1[0][0])

If we run the code, you will receive the same TypeError in Python3.

TypeError: 'int' object is not subscriptable

Here the index of the list is out of range. If the code was modified to:

print(list1[0])

The output will be 1(as indexing in Python Lists starts at zero), as now the index of the list is in range.

1

When the code(given alongside the question) is run, the TypeError occurs and it points to line 4 of the code :

int([x[age1]])

The intention may have been to create a list of an integer number(although creating a list for a single number was not at all required). What was required was that to just assign the input(which in turn converted to integer) to a variable.

Hence, it's better to code this way:

name = input("What's your name? ")
age = int(input('How old are you? '))
twenty_one = 21 - age
if(twenty_one < 0):
    print('Hi {0}, you are above 21 years' .format(name))
elif(twenty_one == 0):
    print('Hi {0}, you are 21 years old' .format(name))
else:
    print('Hi {0}, you will be 21 years in {1} year(s)' .format(name, twenty_one))

The output:

What's your name? Steve
How old are you? 21
Hi Steve, you are 21 years old

JQuery .hasClass for multiple values in an if statement

Try this:

if ($('html').hasClass('class1 class2')) {

// do stuff 

}

How to set some xlim and ylim in Seaborn lmplot facetgrid

You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:

lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)

Then you can get hold of the axes objects (an array of axes):

axes = lm.axes

After that you can tweak the axes properties

axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)

creates:

enter image description here

What's the right way to decode a string that has special HTML entities in it?

This is my favourite way of decoding HTML characters. The advantage of using this code is that tags are also preserved.

function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}

Example: http://jsfiddle.net/k65s3/

Input:

Entity:&nbsp;Bad attempt at XSS:<script>alert('new\nline?')</script><br>

Output:

Entity: Bad attempt at XSS:<script>alert('new\nline?')</script><br>

Not equal <> != operator on NULL

NULL is not anything...it is unknown. NULL does not equal anything. That is why you have to use the magic phrase IS NULL instead of = NULL in your SQL queries

You can refer this: http://weblogs.sqlteam.com/markc/archive/2009/06/08/60929.aspx

Why use getters and setters/accessors?

Getter and setter methods are accessor methods, meaning that they are generally a public interface to change private class members. You use getter and setter methods to define a property. You access getter and setter methods as properties outside the class, even though you define them within the class as methods. Those properties outside the class can have a different name from the property name in the class.

There are some advantages to using getter and setter methods, such as the ability to let you create members with sophisticated functionality that you can access like properties. They also let you create read-only and write-only properties.

Even though getter and setter methods are useful, you should be careful not to overuse them because, among other issues, they can make code maintenance more difficult in certain situations. Also, they provide access to your class implementation, like public members. OOP practice discourages direct access to properties within a class.

When you write classes, you are always encouraged to make as many as possible of your instance variables private and add getter and setter methods accordingly. This is because there are several times when you may not want to let users change certain variables within your classes. For example, if you have a private static method that tracks the number of instances created for a specific class, you don't want a user to modify that counter using code. Only the constructor statement should increment that variable whenever it's called. In this situation, you might create a private instance variable and allow a getter method only for the counter variable, which means users are able to retrieve the current value only by using the getter method, and they won't be able to set new values using the setter method. Creating a getter without a setter is a simple way of making certain variables in your class read-only.

How can I store HashMap<String, ArrayList<String>> inside a list?

First, let me fix a little bit your declaration:

List<Map<String, List<String>>> listOfMapOfList = 
    new HashList<Map<String, List<String>>>();

Please pay attention that I used concrete class (HashMap) only once. It is important to use interface where you can to be able to change the implementation later.

Now you want to add element to the list, don't you? But the element is a map, so you have to create it:

Map<String, List<String>> mapOfList = new HashMap<String, List<String>>();

Now you want to populate the map. Fortunately you can use utility that creates lists for you, otherwise you have to create list separately:

mapOfList.put("mykey", Arrays.asList("one", "two", "three"));

OK, now we are ready to add the map into the list:

listOfMapOfList.add(mapOfList);

BUT:

Stop creating complicated collections right now! Think about the future: you will probably have to change the internal map to something else or list to set etc. This will probably cause you to re-write significant parts of your code. Instead define class that contains you data and then add it to one-dimentional collection:

Let's call your class Student (just as example):

public Student {
    private String firstName;
    private String lastName;
    private int studentId;

    private Colectiuon<String> courseworks = Collections.emtpyList();

    //constructors, getters, setters etc
}

Now you can define simple collection:

Collection<Student> students = new ArrayList<Student>();

If in future you want to put your students into map where key is the studentId, do it:

Map<Integer, Student> students = new HashMap<Integer, Student>();

Average of multiple columns

You don't mention if the columns are nullable. If they are and you want the same semantics that the AVG aggregate provides you can do (2008)

SELECT *,
       (SELECT AVG(c)
        FROM   (VALUES(R1),
                      (R2),
                      (R3),
                      (R4),
                      (R5)) T (c)) AS [Average]
FROM   Request  

The 2005 version is a bit more tedious

SELECT *,
       (SELECT AVG(c)
        FROM   (SELECT R1
                UNION ALL
                SELECT R2
                UNION ALL
                SELECT R3
                UNION ALL
                SELECT R4
                UNION ALL
                SELECT R5) T (c)) AS [Average]
FROM   Request

How do I install soap extension?

For Windows

  1. Find extension=php_soap.dll or extension=soap in php.ini and remove the commenting semicolon at the beginning of the line. Eventually check for soap.ini under the conf.d directory.

  2. Restart your server.

For Linux

Ubuntu:

PHP7

Apache

sudo apt-get install php7.0-soap 
sudo systemctl restart apache2

PHP5

sudo apt-get install php-soap
sudo systemctl restart apache2

OpenSuse:

PHP7

Apache

sudo zypper in php7-soap
sudo systemctl restart apache2

Nginx

sudo zypper in php7-soap
sudo systemctl restart nginx

Difference between map and collect in Ruby?

Ruby aliases the method Array#map to Array#collect; they can be used interchangeably. (Ruby Monk)

In other words, same source code :

               static VALUE
rb_ary_collect(VALUE ary)
{
long i;
VALUE collect;

RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
collect = rb_ary_new2(RARRAY_LEN(ary));
for (i = 0; i < RARRAY_LEN(ary); i++) {
    rb_ary_push(collect, rb_yield(RARRAY_AREF(ary, i)));
}
return collect;
}

http://ruby-doc.org/core-2.2.0/Array.html#method-i-map

Visual Studio SignTool.exe Not Found

I have a windows 7 and installing the ClickOnce Tools was not enough.

The signtool.exe appeared after also installing the sdk:

selection in vs 2015

postgreSQL - psql \i : how to execute script in a given path

Have you tried using Unix style slashes (/ instead of \)?

\ is often an escape or command character, and may be the source of confusion. I have never had issues with this, but I also do not have Windows, so I cannot test it.

Additionally, the permissions may be based on the user running psql, or maybe the user executing the postmaster service, check that both have read to that file in that directory.

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

Spring cannot instantiate your TestController because its only constructor requires a parameter. You can add a no-arg constructor or you add @Autowired annotation to the constructor:

@Autowired
public TestController(KeeperClient testClient) {
    TestController.testClient = testClient;
}

In this case, you are explicitly telling Spring to search the application context for a KeeperClient bean and inject it when instantiating the TestControlller.

PHPExcel auto size column width

you also need to identify the columns to set dimensions:

foreach (range('A', $phpExcelObject->getActiveSheet()->getHighestDataColumn()) as $col) {
$phpExcelObject
        ->getActiveSheet()
        ->getColumnDimension($col)
        ->setAutoSize(true);
}

writing integer values to a file using out.write()

Also you can use f-string formatting to write integer to file

For appending use following code, for writing once replace 'a' with 'w'.

for i in s_list:
    with open('path_to_file','a') as file:
        file.write(f'{i}\n')

file.close()

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

Adding the primary key worked for me too !

Once that is done, here's how to update the data model without deleting it -

Right click on the edmx Entity designer page and 'Update Model from Database'.

How do I "Add Existing Item" an entire directory structure in Visual Studio?

In Solution Explorer:

  1. Click Show All Files (second icon from the left at the top of Solution Explorer).
  2. Locate the folder you want to add.
  3. Right-click and select "Include in Project"

I use this to install add-ons like HTML editors and third-party file browsers.

Read all contacts' phone numbers in android

In case it helps, I've got an example that uses the ContactsContract API to first find a contact by name, then it iterates through the details looking for specific number types:

How to use ContactsContract to retrieve phone numbers and email addresses

How can I get the DateTime for the start of the week?

Same for end of week (in style of @Compile This's answer):

    public static DateTime EndOfWeek(this DateTime dt)
    {
        int diff = 7 - (int)dt.DayOfWeek;

        diff = diff == 7 ? 0 : diff;

        DateTime eow = dt.AddDays(diff).Date;

        return new DateTime(eow.Year, eow.Month, eow.Day, 23, 59, 59, 999) { };
    }

Git mergetool generates unwanted .orig files

Or just add

*.orig

to your global gitignore

How to Completely Uninstall Xcode and Clear All Settings

  1. Open Storage Management

    • Go to ? > About This Mac > Window > Storage Management
    • Or, hit ? + Space to open Spotlight and search for Storage Management.
  2. Select Applications on left pane.

  3. Right click on Xcode on the right pane and select delete.

This will remove XCode from the installed applications list of your Mac's App Store.

Update: This worked for me on macOS Sierra 10.12.1.

perform an action on checkbox checked or unchecked event on html form

The problem is how you've attached the listener:

<input type="checkbox" ...  onchange="doalert(this.id)">

Inline listeners are effectively wrapped in a function which is called with the element as this. That function then calls the doalert function, but doesn't set its this so it will default to the global object (window in a browser).

Since the window object doesn't have a checked property, this.checked always resolves to false.

If you want this within doalert to be the element, attach the listener using addEventListener:

window.onload = function() {
  var input = document.querySelector('#g01-01');
  if (input) {   
    input.addEventListener('change', doalert, false);
  }
}

Or if you wish to use an inline listener:

<input type="checkbox" ...  onchange="doalert.call(this, this.id)">

NoClassDefFoundError for code in an Java library on Android

Solutions:

  1. List item
  2. Check Exports Order
  3. Enable Multi Dex
  4. Check api level of views in layout. I faced same problem with searchView. I have check api level while adding searchview but added implements SearchView.OnQueryTextListener to class file.

How do I get indices of N maximum values in a NumPy array?

If you happen to be working with a multidimensional array then you'll need to flatten and unravel the indices:

def largest_indices(ary, n):
    """Returns the n largest indices from a numpy array."""
    flat = ary.flatten()
    indices = np.argpartition(flat, -n)[-n:]
    indices = indices[np.argsort(-flat[indices])]
    return np.unravel_index(indices, ary.shape)

For example:

>>> xs = np.sin(np.arange(9)).reshape((3, 3))
>>> xs
array([[ 0.        ,  0.84147098,  0.90929743],
       [ 0.14112001, -0.7568025 , -0.95892427],
       [-0.2794155 ,  0.6569866 ,  0.98935825]])
>>> largest_indices(xs, 3)
(array([2, 0, 0]), array([2, 2, 1]))
>>> xs[largest_indices(xs, 3)]
array([ 0.98935825,  0.90929743,  0.84147098])

Invoking a jQuery function after .each() has completed

what about

$(parentSelect).nextAll().fadeOut(200, function() { 
    $(this).remove(); 
}).one(function(){
    myfunction();
}); 

How do I run Python code from Sublime Text 2?

To RUN press CtrlB (answer by matiit)

But when CtrlB does not work, Sublime Text probably can't find the Python Interpreter. When trying to run your program, see the log and find the reference to Python in path.

[cmd:  [u'python', u'-u', u'C:\\scripts\\test.py']]
[path: ...;C:\Python27 32bit;...]

The point is that it tries to run python via command line, the cmd looks like:

python -u C:\scripts\test.py

If you can't run python from cmd, Sublime Text can't too.
(Try it yourself in cmd, type python in it and run it, python commandline should appear)

SOLUTION

You can either change the Sublime Text build formula or the System %PATH%.

  • To set your %PATH%:
    *You will need to restart your editor to load new %PATH%

    • Run Command Line* and enter this command: *needs to be run as administrator
      SETX /M PATH "%PATH%;<python_folder>"
      for example: SETX /M PATH "%PATH%;C:\Python27;C:\Python27\Scripts"

    • OR manually: (preferable)
      Add ;C:\Python27;C:\Python27\Scripts at the end of the string. Setting Path in Win7

  • To set the interpreter's path without messing with System %PATH% see this answer by ppy.

GROUP BY to combine/concat a column

SELECT
     [User], Activity,
     STUFF(
         (SELECT DISTINCT ',' + PageURL
          FROM TableName
          WHERE [User] = a.[User] AND Activity = a.Activity
          FOR XML PATH (''))
          , 1, 1, '')  AS URLList
FROM TableName AS a
GROUP BY [User], Activity

How can I list the scheduled jobs running in my database?

The DBA views are restricted. So you won't be able to query them unless you're connected as a DBA or similarly privileged user.

The ALL views show you the information you're allowed to see. Normally that would be jobs you've submitted, unless you have additional privileges.

The privileges you need are defined in the Admin Guide. Find out more.

So, either you need a DBA account or you need to chat with your DBA team about getting access to the information you need.

NameError: global name is not defined

try

from sqlitedbx import SqliteDBzz

Parse JSON String to JSON Object in C#.NET

I see that this question is very old, but this is the solution I used for the same problem, and it seems to require a bit less code than the others.

As @Maloric mentioned in his answer to this question:

var jo = JObject.Parse(myJsonString);

To use JObject, you need the following in your class file

using Newtonsoft.Json.Linq;

How do I convert an array object to a string in PowerShell?

$a = 'This', 'Is', 'a', 'cat'

Using double quotes (and optionally use the separator $ofs)

# This Is a cat
"$a"

# This-Is-a-cat
$ofs = '-' # after this all casts work this way until $ofs changes!
"$a"

Using operator join

# This-Is-a-cat
$a -join '-'

# ThisIsacat
-join $a

Using conversion to [string]

# This Is a cat
[string]$a

# This-Is-a-cat
$ofs = '-'
[string]$a

How do I print an IFrame from javascript in Safari/Chrome

You can also use

top.iframeName.print();

or

parent.iframeName.print();

How do I send an HTML email?

Since JavaMail version 1.4, there is an overload of setText method that accepts the subtype.

// Passing null for second argument in order for the method to determine
// the actual charset on-the fly.
// If you know the charset, pass it. "utf-8" should be fine
msg.setText( message, null, "html" );

How do I limit the number of rows returned by an Oracle query after ordering?

(untested) something like this may do the job

WITH
base AS
(
    select *                   -- get the table
    from sometable
    order by name              -- in the desired order
),
twenty AS
(
    select *                   -- get the first 30 rows
    from base
    where rownum < 30
    order by name              -- in the desired order
)
select *                       -- then get rows 21 .. 30
from twenty
where rownum > 20
order by name                  -- in the desired order

There is also the analytic function rank, that you can use to order by.

Display two fields side by side in a Bootstrap Form

For Bootstrap 4

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<div class="input-group">_x000D_
    <input type="text" class="form-control" placeholder="Start"/>_x000D_
    <div class="input-group-prepend">_x000D_
        <span class="input-group-text" id="">-</span>_x000D_
    </div>_x000D_
    <input type="text" class="form-control" placeholder="End"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Floating point vs integer calculations on modern hardware

Addition is much faster than rand, so your program is (especially) useless.

You need to identify performance hotspots and incrementally modify your program. It sounds like you have problems with your development environment that will need to be solved first. Is it impossible to run your program on your PC for a small problem set?

Generally, attempting FP jobs with integer arithmetic is a recipe for slow.

Event system in Python

I made a variation of Longpoke's minimalistic approach that also ensures the signatures for both callees and callers:

class EventHook(object):
    '''
    A simple implementation of the Observer-Pattern.
    The user can specify an event signature upon inizializazion,
    defined by kwargs in the form of argumentname=class (e.g. id=int).
    The arguments' types are not checked in this implementation though.
    Callables with a fitting signature can be added with += or removed with -=.
    All listeners can be notified by calling the EventHook class with fitting
    arguments.

    >>> event = EventHook(id=int, data=dict)
    >>> event += lambda id, data: print("%d %s" % (id, data))
    >>> event(id=5, data={"foo": "bar"})
    5 {'foo': 'bar'}

    >>> event = EventHook(id=int)
    >>> event += lambda wrong_name: None
    Traceback (most recent call last):
        ...
    ValueError: Listener must have these arguments: (id=int)

    >>> event = EventHook(id=int)
    >>> event += lambda id: None
    >>> event(wrong_name=0)
    Traceback (most recent call last):
        ...
    ValueError: This EventHook must be called with these arguments: (id=int)
    '''
    def __init__(self, **signature):
        self._signature = signature
        self._argnames = set(signature.keys())
        self._handlers = []

    def _kwargs_str(self):
        return ", ".join(k+"="+v.__name__ for k, v in self._signature.items())

    def __iadd__(self, handler):
        params = inspect.signature(handler).parameters
        valid = True
        argnames = set(n for n in params.keys())
        if argnames != self._argnames:
            valid = False
        for p in params.values():
            if p.kind == p.VAR_KEYWORD:
                valid = True
                break
            if p.kind not in (p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY):
                valid = False
                break
        if not valid:
            raise ValueError("Listener must have these arguments: (%s)"
                             % self._kwargs_str())
        self._handlers.append(handler)
        return self

    def __isub__(self, handler):
        self._handlers.remove(handler)
        return self

    def __call__(self, *args, **kwargs):
        if args or set(kwargs.keys()) != self._argnames:
            raise ValueError("This EventHook must be called with these " +
                             "keyword arguments: (%s)" % self._kwargs_str())
        for handler in self._handlers[:]:
            handler(**kwargs)

    def __repr__(self):
        return "EventHook(%s)" % self._kwargs_str()

How to change line color in EditText

I don't like previous answers. The best solution is to use:

<android.support.v7.widget.AppCompatEditText

      app:backgroundTint="@color/blue_gray_light" />

android:backgroundTint for EditText works only on API21+ . Because of it, we have to use the support library and AppCompatEditText.

Note: we have to use app:backgroundTint instead of android:backgroundTint

AndroidX version

<androidx.appcompat.widget.AppCompatEditText

      app:backgroundTint="@color/blue_gray_light" />

How to disable keypad popup when on edittext?

I found the following pattern to work well for me in code where I want to show a dialog to get the input (e.g., the string displayed in the text field is the result of selections made from a list of checkboxes in a dialog, rather than text entered via the keyboard).

  1. Disable soft input focus on the edit field. I can't disable for the entire activity, as there are edit fields I do want the keyboard to be used for in the same layout.
  2. Initial clicks in the text field yield a focus change, a repeated click yields a click event. So I override both (here I don't refactor the code out to illustrate both handlers do the same thing):

    tx = (TextView) m_activity.findViewById(R.id.allergymeds);
    if (tx != null) {
        tx.setShowSoftInputOnFocus(false);
        tx.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean hasFocus) {
                if (hasFocus) {
                    MedicationsListDialogFragment mld = new MedicationsListDialogFragment();
                    mld.setPatientId(m_sess.getActivePatientId());
                    mld.show(getFragmentManager(), "Allergy Medications Dialog");
                }
            }
        });
        tx.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                MedicationsListDialogFragment mld = new MedicationsListDialogFragment();
                mld.setPatientId(m_sess.getActivePatientId());
                mld.show(getFragmentManager(), "Allergy Medications Dialog");
            }
        });
    }
    

How to find the privileges and roles granted to a user in Oracle?

IF privileges are given to a user through some roles, then below SQL can be used

select * from ROLE_ROLE_PRIVS where ROLE = 'ROLE_NAME';
select * from ROLE_TAB_PRIVS  where ROLE = 'ROLE_NAME';
select * from ROLE_SYS_PRIVS  where ROLE = 'ROLE_NAME';

Laravel password validation rule

I have had a similar scenario in Laravel and solved it in the following way.

The password contains characters from at least three of the following five categories:

  • English uppercase characters (A – Z)
  • English lowercase characters (a – z)
  • Base 10 digits (0 – 9)
  • Non-alphanumeric (For example: !, $, #, or %)
  • Unicode characters

First, we need to create a regular expression and validate it.

Your regular expression would look like this:

^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$

I have tested and validated it on this site. Yet, perform your own in your own manner and adjust accordingly. This is only an example of regex, you can manipluated the way you want.

So your final Laravel code should be like this:

'password' => 'required|
               min:6|
               regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$/|
               confirmed',

Update As @NikK in the comment mentions, in Laravel 5.5 and newer the the password value should encapsulated in array Square brackets like

'password' => ['required', 
               'min:6', 
               'regex:/^.*(?=.{3,})(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[\d\x])(?=.*[!$#%]).*$/', 
               'confirmed']

I have not testing it on Laravel 5.5 so I am trusting @NikK hence I have moved to working with c#/.net these days and have no much time for Laravel.

Note:

  1. I have tested and validated it on both the regular expression site and a Laravel 5 test environment and it works.
  2. I have used min:6, this is optional but it is always a good practice to have a security policy that reflects different aspects, one of which is minimum password length.
  3. I suggest you to use password confirmed to ensure user typing correct password.
  4. Within the 6 characters our regex should contain at least 3 of a-z or A-Z and number and special character.
  5. Always test your code in a test environment before moving to production.
  6. Update: What I have done in this answer is just example of regex password

Some online references

Regarding your custom validation message for the regex rule in Laravel, here are a few links to look at:

how to pass data in an hidden field from one jsp page to another?

To pass the value you must included the hidden value value="hiddenValue" in the <input> statement like so:

<input type="hidden" id="thisField" name="inputName" value="hiddenValue">

Then you recuperate the hidden form value in the same way that you recuperate the value of visible input fields, by accessing the parameter of the request object. Here is an example:

This code goes on the page where you want to hide the value.

<form action="anotherPage.jsp" method="GET">
    <input type="hidden" id="thisField" name="inputName" value="hiddenValue">
<input type="submit">   
</form>

Then on the 'anotherPage.jsp' page you recuperate the value by calling the getParameter(String name) method of the implicit request object, as so:

<% String hidden = request.getParameter("inputName"); %>
The Hidden Value is <%=hidden %>

The output of the above script will be:

The Hidden Value is hiddenValue 

How to fast-forward a branch to head?

To rebase the current local tracker branch moving local changes on top of the latest remote state:

$ git fetch && git rebase

More generally, to fast-forward and drop the local changes (hard reset)*:

$ git fetch && git checkout ${the_branch_name} && git reset --hard origin/${the_branch_name}

to fast-forward and keep the local changes (rebase):

$ git fetch && git checkout ${the_branch_name} && git rebase origin/${the_branch_name}

* - to undo the change caused by unintentional hard reset first do git reflog, that displays the state of the HEAD in reverse order, find the hash the HEAD was pointing to before the reset operation (usually obvious) and hard reset the branch to that hash.

Android: Cancel Async Task

I spent a while figuring this out, all I wanted was a simple example of how to do it, so I thought I'd post how I did it. This is some code that updates a library and has a progress dialog showing how many books have been updated and cancels when a user dismisses the dialog:

private class UpdateLibrary extends AsyncTask<Void, Integer, Boolean>{
    private ProgressDialog dialog = new ProgressDialog(Library.this);
    private int total = Library.instance.appState.getAvailableText().length;
    private int count = 0;

    //Used as handler to cancel task if back button is pressed
    private AsyncTask<Void, Integer, Boolean> updateTask = null;

    @Override
    protected void onPreExecute(){
        updateTask = this;
        dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        dialog.setOnDismissListener(new OnDismissListener() {               
            @Override
            public void onDismiss(DialogInterface dialog) {
                updateTask.cancel(true);
            }
        });
        dialog.setMessage("Updating Library...");
        dialog.setMax(total);
        dialog.show();
    }

    @Override
    protected Boolean doInBackground(Void... arg0) {
            for (int i = 0; i < appState.getAvailableText().length;i++){
                if(isCancelled()){
                    break;
                }
                //Do your updating stuff here
            }
        }

    @Override
    protected void onProgressUpdate(Integer... progress){
        count += progress[0];
        dialog.setProgress(count);
    }

    @Override
    protected void onPostExecute(Boolean finished){
        dialog.dismiss();
        if (finished)
            DialogHelper.showMessage(Str.TEXT_UPDATELIBRARY, Str.TEXT_UPDATECOMPLETED, Library.instance);
        else 
            DialogHelper.showMessage(Str.TEXT_UPDATELIBRARY,Str.TEXT_NOUPDATE , Library.instance);
    }
}

End-line characters from lines read from text file, using Python

Long time ago, there was Dear, clean, old, BASIC code that could run on 16 kb core machines: like that:

if (not open(1,"file.txt")) error "Could not open 'file.txt' for reading"
while(not eof(1)) 
  line input #1 a$
  print a$
wend
close

Now, to read a file line by line, with far better hardware and software (Python), we must reinvent the wheel:

def line_input (file):
    for line in file:
        if line[-1] == '\n':
            yield line[:-1]
        else:
            yield line

f = open("myFile.txt", "r")
for line_input(f):
    # do something with line

I am induced to think that something has gone the wrong way somewhere...

What is the worst programming language you ever worked with?

Dataflex 2.3 and VDF4.

VDF 4 is what drove me away from Dataflex.

One of the most stupid things they did was use the Windows message for the third mouse button to communicate between the IDE and the complier. It worked fine unless you had a 3 button mouse.

how to add new <li> to <ul> onclick with javascript

There is nothing much to add to your code except appending the li tag to the ul

ul.appendChild(li)

and there you go just add this to your function and then it should work.

Autocompletion in Vim

I'm a bit late to the party but autocomplpop might be helpful.

Get css top value as number not as string?

You can use the parseInt() function to convert the string to a number, e.g:

parseInt($('#elem').css('top'));

Update: (as suggested by Ben): You should give the radix too:

parseInt($('#elem').css('top'), 10);

Forces it to be parsed as a decimal number, otherwise strings beginning with '0' might be parsed as an octal number (might depend on the browser used).

A method to count occurrences in a list

public void printsOccurences(List<String> words)
{
    var selectQuery =
        from word in words
        group word by word into g
        select new {Word = g.Key, Count = g.Count()};
    foreach(var word in selectQuery)
        Console.WriteLine($"{word.Word}: {word.Count}");*emphasized text*
}

Steps to upload an iPhone application to the AppStore

Xcode 9

If this is your first time to submit an app, I recommend going ahead and reading through the full Apple iTunes Connect documentation or reading one of the following tutorials:

However, those materials are cumbersome when you just want a quick reminder of the steps. My answer to that is below:

Step 1: Create a new app in iTunes Connect

Sign in to iTunes Connect and go to My Apps. Then click the "+" button and choose New App.

enter image description here

Then fill out the basic information for a new app. The app bundle id needs to be the same as the one you are using in your Xcode project. There is probably a better was to name the SKU, but I've never needed it and I just use the bundle id.

enter image description here

Click Create and then go on to Step 2.

Step 2: Archive your app in Xcode

Choose the Generic iOS Device from the active scheme menu.

enter image description here

Then go to Product > Archive.

enter image description here

You may have to wait a little while for Xcode to finish archiving your project. After that you will be shown a dialog with your archived project. You can select Upload to the App Store... and follow the prompts.

I sometimes have to repeat this step a few times because I forgot to include something. Besides the upload wait, it isn't a big deal. Just keep doing it until you don't get any more errors.

Step 3: Finish filling out the iTunes Connect info

Back in iTunes Connect you will need to complete all the required information and resources.

enter image description here

Just go through all the menu options and make sure that you have everything entered that needs to be.

Step 4: Submit

In iTunes Connect, under your app's Prepare for Submission section, click Submit for Review. That's it. Give it about a week to be accepted (or rejected), but it might be faster.

Enable SQL Server Broker taking too long

Enabling SQL Server Service Broker requires a database lock. Stop the SQL Server Agent and then execute the following:

USE master ;
GO

ALTER DATABASE [MyDatabase] SET ENABLE_BROKER ;
GO

Change [MyDatabase] with the name of your database in question and then start SQL Server Agent.

If you want to see all the databases that have Service Broker enabled or disabled, then query sys.databases, for instance:

SELECT
    name, database_id, is_broker_enabled
FROM sys.databases

How to convert 'binary string' to normal string in Python3?

If the answer from falsetru didn't work you could also try:

>>> b'a string'.decode('utf-8')
'a string'

YAML equivalent of array of objects in JSON

Great answer above. Another way is to use the great yaml jq wrapper tool, yq at https://github.com/kislyuk/yq

Save your JSON example to a file, say ex.json and then

yq -y '.' ex.json

AAPL:
- shares: -75.088
  date: 11/27/2015
- shares: 75.088
  date: 11/26/2015

How to grab substring before a specified character jQuery or JavaScript

You could use regex as this will give you the string if it matches the requirements. The code would be something like:

const address = "1345 albany street, Bellevue WA 42344";
const regex = /[1-9][0-9]* [a-zA-Z]+ [a-zA-Z]+/;
const matchedResult = address.match(regex);

console.log(matchedResult[0]); // This will give you 1345 albany street.

So to break the code down. [1-9][0-9]* basically means the first number cannot be a zero and has to be a number between 1-9 and the next number can be any number from 0-9 and can occur zero or more times as sometimes the number is just one digit and then it matches a space. [a-zA-Z] basically matches all capital letters to small letters and has to occur one or more times and this is repeated.

Customize Bootstrap checkboxes

_x000D_
_x000D_
/* The customcheck */_x000D_
.customcheck {_x000D_
    display: block;_x000D_
    position: relative;_x000D_
    padding-left: 35px;_x000D_
    margin-bottom: 12px;_x000D_
    cursor: pointer;_x000D_
    font-size: 22px;_x000D_
    -webkit-user-select: none;_x000D_
    -moz-user-select: none;_x000D_
    -ms-user-select: none;_x000D_
    user-select: none;_x000D_
}_x000D_
_x000D_
/* Hide the browser's default checkbox */_x000D_
.customcheck input {_x000D_
    position: absolute;_x000D_
    opacity: 0;_x000D_
    cursor: pointer;_x000D_
}_x000D_
_x000D_
/* Create a custom checkbox */_x000D_
.checkmark {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    height: 25px;_x000D_
    width: 25px;_x000D_
    background-color: #eee;_x000D_
    border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* On mouse-over, add a grey background color */_x000D_
.customcheck:hover input ~ .checkmark {_x000D_
    background-color: #ccc;_x000D_
}_x000D_
_x000D_
/* When the checkbox is checked, add a blue background */_x000D_
.customcheck input:checked ~ .checkmark {_x000D_
    background-color: #02cf32;_x000D_
    border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* Create the checkmark/indicator (hidden when not checked) */_x000D_
.checkmark:after {_x000D_
    content: "";_x000D_
    position: absolute;_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
/* Show the checkmark when checked */_x000D_
.customcheck input:checked ~ .checkmark:after {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
/* Style the checkmark/indicator */_x000D_
.customcheck .checkmark:after {_x000D_
    left: 9px;_x000D_
    top: 5px;_x000D_
    width: 5px;_x000D_
    height: 10px;_x000D_
    border: solid white;_x000D_
    border-width: 0 3px 3px 0;_x000D_
    -webkit-transform: rotate(45deg);_x000D_
    -ms-transform: rotate(45deg);_x000D_
    transform: rotate(45deg);_x000D_
}
_x000D_
<div class="container">_x000D_
 <h1>Custom Checkboxes</h1></br>_x000D_
 _x000D_
        <label class="customcheck">One_x000D_
          <input type="checkbox" checked="checked">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Two_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Three_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Four_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Check if image exists on server using JavaScript?

If you are using React try this custom Image component:

import React, { useRef } from 'react';
import PropTypes from 'prop-types';

import defaultErrorImage from 'assets/images/default-placeholder-image.png';

const Image = ({ src, alt, className, onErrorImage }) => {
  const imageEl = useRef(null);
  return (
    <img
      src={src}
      alt={alt}
      className={className}
      onError={() => {
        imageEl.current.src = onErrorImage;
      }}
      ref={imageEl}
    />
  );
};

Image.defaultProps = {
  onErrorImage: defaultErrorImage,
};

Image.propTypes = {
  src: PropTypes.string.isRequired,
  alt: PropTypes.string.isRequired,
  className: PropTypes.string.isRequired,
  onErrorImage: PropTypes.string,
};

export default Image;

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

How should I cast in VB.NET?

According to the certification exam you should use Convert.ToXXX() whenever possible for simple conversions because it optimizes performance better than CXXX conversions.

Writing data to a local text file with javascript

Our HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>

JS (writing to the txt file):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}

checking a particular row:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}

Put these inside a .hta file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.

Null & empty string comparison in Bash

fedorqui has a working solution but there is another way to do the same thing.

Chock if a variable is set

#!/bin/bash
amIEmpty='Hello'
# This will be true if the variable has a value
if [ $amIEmpty ]; then
    echo 'No, I am not!';
fi

Or to verify that a variable is empty

#!/bin/bash      
amIEmpty=''
# This will be true if the variable is empty
if [ ! $amIEmpty ]; then
    echo 'Yes I am!';
fi

tldp.org has good documentation about if in bash:
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_07_01.html

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

How to tell PowerShell to wait for each command to end before starting the next?

Normally, for internal commands PowerShell does wait before starting the next command. One exception to this rule is external Windows subsystem based EXE. The first trick is to pipeline to Out-Null like so:

Notepad.exe | Out-Null

PowerShell will wait until the Notepad.exe process has been exited before continuing. That is nifty but kind of subtle to pick up from reading the code. You can also use Start-Process with the -Wait parameter:

Start-Process <path to exe> -NoNewWindow -Wait

If you are using the PowerShell Community Extensions version it is:

$proc = Start-Process <path to exe> -NoNewWindow -PassThru
$proc.WaitForExit()

Another option in PowerShell 2.0 is to use a background job:

$job = Start-Job { invoke command here }
Wait-Job $job
Receive-Job $job

http post - how to send Authorization header?

I had the same issue. This is my solution using angular documentation and firebase Token:

getService()  {

const accessToken=this.afAuth.auth.currentUser.getToken().then(res=>{
  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': res
    })
  };
  return this.http.get('Url',httpOptions)
    .subscribe(res => console.log(res));
}); }}

Array of PHP Objects

Yes.

$array[] = new stdClass;
$array[] = new stdClass;

print_r($array);

Results in:

Array
(
    [0] => stdClass Object
        (
        )

    [1] => stdClass Object
        (
        )

)

XAMPP installation on Win 8.1 with UAC Warning

As ivan.sim writes in his answer

  1. Ensure that your user account has administrator privilege.
  2. Disable UAC(User Account Control) as it restricts certain administrative function needed to run a web server.
  3. Install in C://xampp.

Problem with the correct answer is in the explanation of point 2., and magicandre1981 writes more about it

Moving the slider down doesn't completely disable UAC since Windows 8. This is changed compared to Windows 7, because the new Store apps require an active UAC. With UAC off, they no longer run.


How can we then disable UAC and install XAMPP?

Easy. Go to Registry Editor and navigate to

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

Registry Editor

Right click EnableLUA and modify the Value data to 0.

EnableLUA

Then restart your computer and you're ready to install XAMPP.

Installing XAMPP

XAMPP installed

XAMPP Control Panel

Multiple inheritance for an anonymous class

// The interface
interface Blah {
    void something();
}

...

// Something that expects an object implementing that interface
void chewOnIt(Blah b) {
    b.something();
}

...

// Let's provide an object of an anonymous class
chewOnIt(
    new Blah() {
        @Override
        void something() { System.out.println("Anonymous something!"); }
    }
);

Unresolved Import Issues with PyDev and Eclipse

Here is what worked for me (sugested by soulBit):

1) Restart using restart from the file menu
2) Once it started again, manually close and open it.

This is the simplest solution ever and it completely removes the annoying thing.

Put Excel-VBA code in module or sheet?

In my experience it's best to put as much code as you can into well-named modules, and only put as much code as you need to into the actual worksheet objects.

Example: Any code that uses worksheet events like Worksheet_SelectionChange or Worksheet_Calculate.

How can I fix the form size in a C# Windows Forms application and not to let user change its size?

Minimal settings to prevent resize events

form1.FormBorderStyle = FormBorderStyle.FixedDialog;
form1.MaximizeBox = false;

How to create a stopwatch using JavaScript?

This is my simple take on this question, I hope it helps someone out oneday, somewhere...

_x000D_
_x000D_
let output = document.getElementById('stopwatch');
let ms = 0;
let sec = 0;
let min = 0;

function timer() {
    ms++;
    if(ms >= 100){
        sec++
        ms = 0
    }
    if(sec === 60){
        min++
        sec = 0
    }
    if(min === 60){
        ms, sec, min = 0;
    }

    //Doing some string interpolation
    let milli = ms < 10 ? `0`+ ms : ms;
    let seconds = sec < 10 ? `0`+ sec : sec;
    let minute = min < 10 ? `0` + min : min;

    let timer= `${minute}:${seconds}:${milli}`;
    output.innerHTML =timer;
};
//Start timer
function start(){
 time = setInterval(timer,10);
}
//stop timer
function stop(){
    clearInterval(time)
}
//reset timer
function reset(){
    ms = 0;
    sec = 0;
    min = 0;

    output.innerHTML = `00:00:00`
}
const startBtn = document.getElementById('startBtn');
const stopBtn =  document.getElementById('stopBtn');
const resetBtn = document.getElementById('resetBtn');

startBtn.addEventListener('click',start,false);
stopBtn.addEventListener('click',stop,false);
resetBtn.addEventListener('click',reset,false);
_x000D_
    <p class="stopwatch" id="stopwatch">
        <!-- stopwatch goes here -->
    </p>
    <button class="btn-start" id="startBtn">Start</button>
    <button class="btn-stop" id="stopBtn">Stop</button>
    <button class="btn-reset" id="resetBtn">Reset</button>
_x000D_
_x000D_
_x000D_

"No rule to make target 'install'"... But Makefile exists

I also came across the same error. Here is the fix: If you are using Cmake-GUI:

  1. Clean the cache of the loaded libraries in Cmake-GUI File menu.
  2. Configure the libraries.
  3. Generate the Unix file.

If you missed the 3rd step:

*** No rule to make target `install'. Stop.

error will occur.

How to handle anchor hash linking in AngularJS

This is an old post, but I spent a long time researching various solutions so I wanted to share one more simple one. Just adding target="_self" to the <a> tag fixed it for me. The link works and takes me to the proper location on the page.

However, Angular still injects some weirdness with the # in the URL so you may run into trouble using the back button for navigation and such after using this method.

How to declare an ArrayList with values?

Try this!

List<String> x = new ArrayList<String>(Arrays.asList("xyz", "abc"));

It's a good practice to declare the ArrayList with interface List if you don't have to invoke the specific methods.

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

Doing it in one bulk read:

import re

textfile = open(filename, 'r')
filetext = textfile.read()
textfile.close()
matches = re.findall("(<(\d{4,5})>)?", filetext)

Line by line:

import re

textfile = open(filename, 'r')
matches = []
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += reg.findall(line)
textfile.close()

But again, the matches that returns will not be useful for anything except counting unless you added an offset counter:

import re

textfile = open(filename, 'r')
matches = []
offset = 0
reg = re.compile("(<(\d{4,5})>)?")
for line in textfile:
    matches += [(reg.findall(line),offset)]
    offset += len(line)
textfile.close()

But it still just makes more sense to read the whole file in at once.

Quickest way to find missing number in an array of numbers

(sum of 1 to n) - (sum of all values in the array) = missing number

int sum = 0;
int idx = -1;
for (int i = 0; i < arr.length; i++) {
  if (arr[i] == 0) idx = i; else sum += arr[i];
}
System.out.println("missing number is: " + (5050 - sum) + " at index " + idx);

Keyboard shortcuts in WPF

Documenting this answer for others, as there is a much simpler way to do this that is rarely referenced, and doesn't require touching the XAML at all.

To link a keyboard shortcut, in the Window constructor simply add a new KeyBinding to the InputBindings collection. As the command, pass in your arbitrary command class that implements ICommand. For the execute method, simply implement whatever logic you need. In my example below, my WindowCommand class takes a delegate that it will execute whenever invoked. When I construct the new WindowCommand to pass in with my binding, I simply indicate in my initializer, the method that I want the WindowCommand to execute.

You can use this pattern to come up with your own quick keyboard shortcuts.

public YourWindow() //inside any WPF Window constructor
{
   ...
   //add this one statement to bind a new keyboard command shortcut
   InputBindings.Add(new KeyBinding( //add a new key-binding, and pass in your command object instance which contains the Execute method which WPF will execute
      new WindowCommand(this)
      {
         ExecuteDelegate = TogglePause //REPLACE TogglePause with your method delegate
      }, new KeyGesture(Key.P, ModifierKeys.Control)));
   ...
}

Create a simple WindowCommand class which takes an execution delegate to fire off any method set on it.

public class WindowCommand : ICommand
{
    private MainWindow _window;

    //Set this delegate when you initialize a new object. This is the method the command will execute. You can also change this delegate type if you need to.
    public Action ExecuteDelegate { get; set; }

    //You don't have to add a parameter that takes a constructor. I've just added one in case I need access to the window directly.
    public WindowCommand(MainWindow window)
    {
        _window = window;
    }

    //always called before executing the command, mine just always returns true
    public bool CanExecute(object parameter)
    {
        return true; //mine always returns true, yours can use a new CanExecute delegate, or add custom logic to this method instead.
    }

    public event EventHandler CanExecuteChanged; //i'm not using this, but it's required by the interface

    //the important method that executes the actual command logic
    public void Execute(object parameter)
    {
        if (ExecuteDelegate != null)
        {
            ExecuteDelegate();
        }
        else
        {
            throw new InvalidOperationException();
        }
    }
}

$on and $broadcast in angular

First, a short description of $on(), $broadcast() and $emit():

  • .$on(name, listener) - Listens for a specific event by a given name
  • .$broadcast(name, args) - Broadcast an event down through the $scope of all children
  • .$emit(name, args) - Emit an event up the $scope hierarchy to all parents, including the $rootScope

Based on the following HTML (see full example here):

<div ng-controller="Controller1">
    <button ng-click="broadcast()">Broadcast 1</button>
    <button ng-click="emit()">Emit 1</button>
</div>

<div ng-controller="Controller2">
    <button ng-click="broadcast()">Broadcast 2</button>
    <button ng-click="emit()">Emit 2</button>
    <div ng-controller="Controller3">
        <button ng-click="broadcast()">Broadcast 3</button>
        <button ng-click="emit()">Emit 3</button>
        <br>
        <button ng-click="broadcastRoot()">Broadcast Root</button>
        <button ng-click="emitRoot()">Emit Root</button>
    </div>
</div>

The fired events will traverse the $scopes as follows:

  • Broadcast 1 - Will only be seen by Controller 1 $scope
  • Emit 1 - Will be seen by Controller 1 $scope then $rootScope
  • Broadcast 2 - Will be seen by Controller 2 $scope then Controller 3 $scope
  • Emit 2 - Will be seen by Controller 2 $scope then $rootScope
  • Broadcast 3 - Will only be seen by Controller 3 $scope
  • Emit 3 - Will be seen by Controller 3 $scope, Controller 2 $scope then $rootScope
  • Broadcast Root - Will be seen by $rootScope and $scope of all the Controllers (1, 2 then 3)
  • Emit Root - Will only be seen by $rootScope

JavaScript to trigger events (again, you can see a working example here):

app.controller('Controller1', ['$scope', '$rootScope', function($scope, $rootScope){
    $scope.broadcastAndEmit = function(){
        // This will be seen by Controller 1 $scope and all children $scopes 
        $scope.$broadcast('eventX', {data: '$scope.broadcast'});

        // Because this event is fired as an emit (goes up) on the $rootScope,
        // only the $rootScope will see it
        $rootScope.$emit('eventX', {data: '$rootScope.emit'});
    };
    $scope.emit = function(){
        // Controller 1 $scope, and all parent $scopes (including $rootScope) 
        // will see this event
        $scope.$emit('eventX', {data: '$scope.emit'});
    };

    $scope.$on('eventX', function(ev, args){
        console.log('eventX found on Controller1 $scope');
    });
    $rootScope.$on('eventX', function(ev, args){
        console.log('eventX found on $rootScope');
    });
}]);

Filtering Pandas Dataframe using OR statement

You can do like below to achieve your result:

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
....
....
#use filter with plot
#or
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') | (df1['Retailer country']=='France')], kind='count')

fg.set_xlabels('Retailer country')
plt.show()


#also
#and
fg=sns.factorplot('Retailer country', data=df1[(df1['Retailer country']=='United States') & (df1['Year']=='2013')], kind='count')

fg.set_xlabels('Retailer country')
plt.show()

Executing a shell script from a PHP script

Without really knowing the complexity of the setup, I like the sudo route. First, you must configure sudo to permit your webserver to sudo run the given command as root. Then, you need to have the script that the webserver shell_exec's(testscript) run the command with sudo.

For A Debian box with Apache and sudo:

  1. Configure sudo:

    • As root, run the following to edit a new/dedicated configuration file for sudo:

      visudo -f /etc/sudoers.d/Webserver
      

      (or whatever you want to call your file in /etc/sudoers.d/)

    • Add the following to the file:

      www-data ALL = (root) NOPASSWD: <executable_file_path>
      

      where <executable_file_path> is the command that you need to be able to run as root with the full path in its name(say /bin/chown for the chown executable). If the executable will be run with the same arguments every time, you can add its arguments right after the executable file's name to further restrict its use.

      For example, say we always want to copy the same file in the /root/ directory, we would write the following:

      www-data ALL = (root) NOPASSWD: /bin/cp /root/test1 /root/test2
      
  2. Modify the script(testscript):

    Edit your script such that sudo appears before the command that requires root privileges(say sudo /bin/chown ... or sudo /bin/cp /root/test1 /root/test2). Make sure that the arguments specified in the sudo configuration file exactly match the arguments used with the executable in this file. So, for our example above, we would have the following in the script:

    sudo /bin/cp /root/test1 /root/test2
    

If you are still getting permission denied, the script file and it's parent directories' permissions may not allow the webserver to execute the script itself. Thus, you need to move the script to a more appropriate directory and/or change the script and parent directory's permissions to allow execution by www-data(user or group), which is beyond the scope of this tutorial.

Keep in mind:

When configuring sudo, the objective is to permit the command in it's most restricted form. For example, instead of permitting the general use of the cp command, you only allow the cp command if the arguments are, say, /root/test1 /root/test2. This means that cp's arguments(and cp's functionality cannot be altered).

Base64 encoding and decoding in client-side Javascript

Here is a tightened up version of Sniper's post. It presumes well formed base64 string with no carriage returns. This version eliminates a couple of loops, adds the &0xff fix from Yaroslav, eliminates trailing nulls, plus a bit of code golf.

decodeBase64 = function(s) {
    var e={},i,b=0,c,x,l=0,a,r='',w=String.fromCharCode,L=s.length;
    var A="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    for(i=0;i<64;i++){e[A.charAt(i)]=i;}
    for(x=0;x<L;x++){
        c=e[s.charAt(x)];b=(b<<6)+c;l+=6;
        while(l>=8){((a=(b>>>(l-=8))&0xff)||(x<(L-2)))&&(r+=w(a));}
    }
    return r;
};

Spring JPA @Query with LIKE

Easy to use following (no need use CONCAT or ||):

@Query("from Service s where s.category.typeAsString like :parent%")
List<Service> findAll(@Param("parent") String parent);

Documented in: http://docs.spring.io/spring-data/jpa/docs/current/reference/html.

Android background music service

Do it without service

https://web.archive.org/web/20181116173307/http://www.rbgrn.net/content/307-light-racer-20-days-61-64-completion

If you are so serious about doing it with services using mediaplayer

Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);

public class BackgroundSoundService extends Service {
    private static final String TAG = null;
    MediaPlayer player;
    public IBinder onBind(Intent arg0) {

        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(this, R.raw.idil);
        player.setLooping(true); // Set looping
        player.setVolume(100,100);

    }
    public int onStartCommand(Intent intent, int flags, int startId) {
        player.start();
        return 1;
    }

    public void onStart(Intent intent, int startId) {
        // TO DO
    }
    public IBinder onUnBind(Intent arg0) {
        // TO DO Auto-generated method
        return null;
    }

    public void onStop() {

    }
    public void onPause() {

    }
    @Override
    public void onDestroy() {
        player.stop();
        player.release();
    }

    @Override
    public void onLowMemory() {

    }
}

Please call this service in Manifest Make sure there is no space at the end of the .BackgroundSoundService string

<service android:enabled="true" android:name=".BackgroundSoundService" />

How to use css style in php

I had this problem just now and I tried the require_once trick, but it would just echo the CSS above all my php code without actually applying the styles.

What I did to fix it, though, was wrap all my php in their own plain HTML templates. Just type out html in the first line of the document and pick the suggestion html:5 to get the HTML boilerplate, like you would when you're just starting a plain HTML doc. Then cut the closing body and html tags and paste them all the way down at the bottom, below the closing php tag to wrap your php code without actually changing anything. Finally, you can just put your plain old link to your stylesheet into the head of your HTML. Works just fine.

Android: Rotate image in imageview by an angle

Rotate an image in android with delay:

imgSplash.animate().rotationBy(360f).setDuration(3000).setInterpolator(new LinearInterpolator()).start();

CommandError: You must set settings.ALLOWED_HOSTS if DEBUG is False

Just simply comment out the line: ALLOWED_HOSTS = [...]

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

Create a BufferedImage from file and make it TYPE_INT_ARGB

Create a BufferedImage from file and make it TYPE_INT_RGB

import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
    public static void main(String args[]){
        try{
            BufferedImage img = new BufferedImage( 
                500, 500, BufferedImage.TYPE_INT_RGB );
            File f = new File("MyFile.png");
            int r = 5;
            int g = 25; 
            int b = 255;
            int col = (r << 16) | (g << 8) | b;
            for(int x = 0; x < 500; x++){
                for(int y = 20; y < 300; y++){
                    img.setRGB(x, y, col);
                }
            }
            ImageIO.write(img, "PNG", f); 
        }
        catch(Exception e){ 
            e.printStackTrace();
        }
    }
}

This paints a big blue streak across the top.

If you want it ARGB, do it like this:

    try{
        BufferedImage img = new BufferedImage( 
            500, 500, BufferedImage.TYPE_INT_ARGB );
        File f = new File("MyFile.png");
        int r = 255;
        int g = 10;
        int b = 57;
        int alpha = 255;
        int col = (alpha << 24) | (r << 16) | (g << 8) | b;
        for(int x = 0; x < 500; x++){
            for(int y = 20; y < 30; y++){
                img.setRGB(x, y, col);
            }
        }
        ImageIO.write(img, "PNG", f);
    }
    catch(Exception e){
        e.printStackTrace();
    }

Open up MyFile.png, it has a red streak across the top.

What does collation mean?

http://en.wikipedia.org/wiki/Collation

Collation is the assembly of written information into a standard order. (...) A collation algorithm such as the Unicode collation algorithm defines an order through the process of comparing two given character strings and deciding which should come before the other.

Convert a list of characters into a string

Use the join method of the empty string to join all of the strings together with the empty string in between, like so:

>>> a = ['a', 'b', 'c', 'd']
>>> ''.join(a)
'abcd'

No space left on device

You can execute the following commands

lsof / |grep deleted

kill the process id's, which free up the disk space.

Disable sorting for a particular column in jQuery DataTables

you can also use negative index like this:

$('.datatable').dataTable({
    "sDom": "<'row-fluid'<'span6'l><'span6'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
    "sPaginationType": "bootstrap",
    "aoColumnDefs": [
        { 'bSortable': false, 'aTargets': [ -1 ] }
    ]
});

Can Mockito capture arguments of a method called multiple times?

First of all: you should always import mockito static, this way the code will be much more readable (and intuitive) - the code samples below require it to work:

import static org.mockito.Mockito.*;

In the verify() method you can pass the ArgumentCaptor to assure execution in the test and the ArgumentCaptor to evaluate the arguments:

ArgumentCaptor<MyExampleClass> argument = ArgumentCaptor.forClass(MyExampleClass.class);
verify(yourmock, atleast(2)).myMethod(argument.capture());

List<MyExampleClass> passedArguments = argument.getAllValues();

for (MyExampleClass data : passedArguments){
    //assertSometing ...
    System.out.println(data.getFoo());
}

The list of all passed arguments during your test is accessible via the argument.getAllValues() method.

The single (last called) argument's value is accessible via the argument.getValue() for further manipulation / checking or whatever you wish to do.

CSS selector for disabled input type="submit"

I used @jensgram solution to hide a div that contains a disabled input. So I hide the entire parent of the input.

Here is the code :

div:has(>input[disabled=disabled]) {
    display: none;
}

Maybe it could help some of you.

Changing background color of selected cell?

Create a custom UITableViewCell. Inside you custom class override the "setSelected" function and change the contentView background color. You can also override you "setHighlighted" function.

In Swift:

class myTableViewCell: UITableViewCell {

    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Configure the view for the selected state
        // Add your color here
        self.contentView.backgroundColor = UIColor.whiteColor()
    }

    override func setHighlighted(highlighted: Bool, animated: Bool) {
        // Add your color here
        self.contentView.backgroundColor = UIColor.whiteColor()
    }
}

Angular 5, HTML, boolean on checkbox is checked

Work with checkboxes using observables

You could even choose to use a behaviourSubject to utilize the power of observables so you can start a certain chain of reaction starting at the isChecked$ observable.

In your component.ts:

public isChecked$ = new BehaviorSubject(false);
toggleChecked() {
  this.isChecked$.next(!this.isChecked$.value)
}

In your template

<input type="checkbox" [checked]="isChecked$ | async" (change)="toggleChecked()">

Datatype for storing ip address in SQL Server

I'm using varchar(15) so far everything is working for me. Insert, Update, Select. I have just started an app that has IP Addresses, though I have not done much dev work yet.

Here is the select statement:

select * From dbo.Server 
where  [IP] = ('132.46.151.181')
Go

Eclipse returns error message "Java was started but returned exit code = 1"

Directly changing eclipse file is not a good idea, no matter facet or ini, unless it could be changed in eclipse. Had the same problem, with jdk1.8 installed. Change it to jdk 1.7.enter image description here

Besides, according to https://wiki.eclipse.org/Eclipse/Installation, both LUNA and MARS need 1.7. So just ensure you have it installed.

CSS transition when class removed

Basically set up your css like:

element {
  border: 1px solid #fff;      
  transition: border .5s linear;
}

element.saved {
  border: 1px solid transparent;
}

How to debug stored procedures with print statements?

Here is an example of print statement use. They should appear under the messages tab as a previous person indicated.

    Declare @TestVar int = 5;

    print 'this is a test message';
    print @TestVar;
    print 'test-' + Convert(varchar(50), @TestVar);

Print Messages

no overload for matches delegate 'system.eventhandler'

Change the klik method as follows:

public void klik(object pea, EventArgs e)
{
    Bitmap c = this.DrawMandel();
    Button btn = pea as Button;
    Graphics gr = btn.CreateGraphics();
    gr.DrawImage(b, 150, 200);
}

GDB: break if variable equal value

in addition to a watchpoint nested inside a breakpoint you can also set a single breakpoint on the 'filename:line_number' and use a condition. I find it sometimes easier.

(gdb) break iter.c:6 if i == 5
Breakpoint 2 at 0x4004dc: file iter.c, line 6.
(gdb) c
Continuing.
0
1
2
3
4

Breakpoint 2, main () at iter.c:6
6           printf("%d\n", i);

If like me you get tired of line numbers changing, you can add a label then set the breakpoint on the label like so:

#include <stdio.h>
main()
{ 
     int i = 0;
     for(i=0;i<7;++i) {
       looping:
        printf("%d\n", i);
     }
     return 0;
}

(gdb) break main:looping if i == 5

What is the meaning of "__attribute__((packed, aligned(4))) "

Before answering, I would like to give you some data from Wiki


Data structure alignment is the way data is arranged and accessed in computer memory. It consists of two separate but related issues: data alignment and data structure padding.

When a modern computer reads from or writes to a memory address, it will do this in word sized chunks (e.g. 4 byte chunks on a 32-bit system). Data alignment means putting the data at a memory offset equal to some multiple of the word size, which increases the system's performance due to the way the CPU handles memory.

To align the data, it may be necessary to insert some meaningless bytes between the end of the last data structure and the start of the next, which is data structure padding.


gcc provides functionality to disable structure padding. i.e to avoid these meaningless bytes in some cases. Consider the following structure:

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}sSampleStruct;

sizeof(sSampleStruct) will be 12 rather than 8. Because of structure padding. By default, In X86, structures will be padded to 4-byte alignment:

typedef struct
{
     char Data1;
     //3-Bytes Added here.
     int Data2;
     unsigned short Data3;
     char Data4;
     //1-byte Added here.

}sSampleStruct;

We can use __attribute__((packed, aligned(X))) to insist particular(X) sized padding. X should be powers of two. Refer here

typedef struct
{
     char Data1;
     int Data2;
     unsigned short Data3;
     char Data4;

}__attribute__((packed, aligned(1))) sSampleStruct;  

so the above specified gcc attribute does not allow the structure padding. so the size will be 8 bytes.

If you wish to do the same for all the structures, simply we can push the alignment value to stack using #pragma

#pragma pack(push, 1)

//Structure 1
......

//Structure 2
......

#pragma pack(pop)

Browser Timeouts

It's browser dependent. "By default, Internet Explorer has a KeepAliveTimeout value of one minute and an additional limiting factor (ServerInfoTimeout) of two minutes. Either setting can cause Internet Explorer to reset the socket." - from IE support http://support.microsoft.com/kb/813827

Firefox is around the same value I think as well.

Usually though server timeout are set lower than browser timeouts, but at least you can control that and set it higher.

You'd rather handle the timeout though, so that way you can act upon such an event. See this thread: How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?

How to use a jQuery plugin inside Vue

I use it like this:

import jQuery from 'jQuery'

ready: function() {
    var self = this;
    jQuery(window).resize(function () {
      self.$refs.thisherechart.drawChart();
    })
  },

How can I use the python HTMLParser library to extract data from a specific div tag?

Little correction at Line 3

HTMLParser.HTMLParser.__init__(self)

it should be

HTMLParser.__init__(self)

The following worked for me though

import urllib2 

from HTMLParser import HTMLParser  

class MyHTMLParser(HTMLParser):

  def __init__(self):
    HTMLParser.__init__(self)
    self.recording = 0 
    self.data = []
  def handle_starttag(self, tag, attrs):
    if tag == 'required_tag':
      for name, value in attrs:
        if name == 'somename' and value == 'somevale':
          print name, value
          print "Encountered the beginning of a %s tag" % tag 
          self.recording = 1 


  def handle_endtag(self, tag):
    if tag == 'required_tag':
      self.recording -=1 
      print "Encountered the end of a %s tag" % tag 

  def handle_data(self, data):
    if self.recording:
      self.data.append(data)

 p = MyHTMLParser()
 f = urllib2.urlopen('http://www.someurl.com')
 html = f.read()
 p.feed(html)
 print p.data
 p.close()

`

JVM heap parameters

To summarize the information found after the link: The JVM allocates the amount specified by -Xms but the OS usually does not allocate real pages until they are needed. So the JVM allocates virtual memory as specified by Xms but only allocates physical memory as is needed.

You can see this by using Process Explorer by Sysinternals instead of task manager on windows.

So there is a real difference between using -Xms64M and -Xms512M. But I think the most important difference is the one you already pointed out: the garbage collector will run more often if you really need the 512MB but only started with 64MB.

Is it possible to use std::string in a constexpr?

Since the problem is the non-trivial destructor so if the destructor is removed from the std::string, it's possible to define a constexpr instance of that type. Like this

struct constexpr_str {
    char const* str;
    std::size_t size;

    // can only construct from a char[] literal
    template <std::size_t N>
    constexpr constexpr_str(char const (&s)[N])
        : str(s)
        , size(N - 1) // not count the trailing nul
    {}
};

int main()
{
    constexpr constexpr_str s("constString");

    // its .size is a constexpr
    std::array<int, s.size> a;
    return 0;
}

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

Make your Foreign key attributes nullable. That will work.

Private properties in JavaScript ES6 classes

Completing @d13 and the comments by @johnny-oshika and @DanyalAytekin:

I guess in the example provided by @johnny-oshika we could use normal functions instead of arrow functions and then .bind them with the current object plus a _privates object as a curried parameter:

something.js

function _greet(_privates) {
  return 'Hello ' + _privates.message;
}

function _updateMessage(_privates, newMessage) {
  _privates.message = newMessage;
}

export default class Something {
  constructor(message) {
    const _privates = {
      message
    };

    this.say = _greet.bind(this, _privates);
    this.updateMessage = _updateMessage.bind(this, _privates);
  }
}

main.js

import Something from './something.js';

const something = new Something('Sunny day!');

const message1 = something.say();
something.updateMessage('Cloudy day!');
const message2 = something.say();

console.log(message1 === 'Hello Sunny day!');  // true
console.log(message2 === 'Hello Cloudy day!');  // true

// the followings are not public
console.log(something._greet === undefined);  // true
console.log(something._privates === undefined);  // true
console.log(something._updateMessage === undefined);  // true

// another instance which doesn't share the _privates
const something2 = new Something('another Sunny day!');

const message3 = something2.say();

console.log(message3 === 'Hello another Sunny day!'); // true

Benefits I can think of:

  • we can have private methods (_greet and _updateMessage act like private methods as long as we don't export the references)
  • although they're not on the prototype, the above mentioned methods will save memory because the instances are created once, outside the class (as opposed to defining them in the constructor)
  • we don't leak any globals since we're inside a module
  • we can also have private properties using the binded _privates object

Some drawbacks I can think of:

A running snippet can be found here: http://www.webpackbin.com/NJgI5J8lZ

Disabling Chrome cache for website development

Since version 50 (if I remember correctly), the "Disable cache" option was removed from the Devtool Settings. Go to the "Network" tab and there's the "Disable cache" option.

Is it possible to apply CSS to half of a character?

How about something like this for shorter text?

It could even work for longer text if you did something with a loop, repeating the characters with JavaScript. Anyway, the result is something like this:

Is it possible to apply CSS to half of a character?

_x000D_
_x000D_
p.char {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  font-size: 60px;_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
p.char:before {_x000D_
  position: absolute;_x000D_
  content: attr(char);_x000D_
  width: 50%;_x000D_
  overflow: hidden;_x000D_
  color: black;_x000D_
}
_x000D_
<p class="char" char="S">S</p>_x000D_
<p class="char" char="t">t</p>_x000D_
<p class="char" char="a">a</p>_x000D_
<p class="char" char="c">c</p>_x000D_
<p class="char" char="k">k</p>_x000D_
<p class="char" char="o">o</p>_x000D_
<p class="char" char="v">v</p>_x000D_
<p class="char" char="e">e</p>_x000D_
<p class="char" char="r">r</p>_x000D_
<p class="char" char="f">f</p>_x000D_
<p class="char" char="l">l</p>_x000D_
<p class="char" char="o">o</p>_x000D_
<p class="char" char="w">w</p>
_x000D_
_x000D_
_x000D_

Execute raw SQL using Doctrine 2

Here's an example of a raw query in Doctrine 2 that I'm doing:

public function getAuthoritativeSportsRecords()
{   
    $sql = " 
        SELECT name,
               event_type,
               sport_type,
               level
          FROM vnn_sport
    ";

    $em = $this->getDoctrine()->getManager();
    $stmt = $em->getConnection()->prepare($sql);
    $stmt->execute();
    return $stmt->fetchAll();
}   

Are one-line 'if'/'for'-statements good Python style?

Older versions of Python would only allow a single simple statement after for ...: if ...: or similar block introductory statements.

I see that one can have multiple simple statements on the same line as any of these. However, there are various combinations that don't work. For example we can:

for i in range(3): print "Here's i:"; print i

... but, on the other hand, we can't:

for i in range(3): if i % 2: print "That's odd!"

We can:

x=10
while x > 0: print x; x-=1

... but we can't:

x=10; while x > 0: print x; x-=1

... and so on.

In any event all of these are considered to be extremely NON-pythonic. If you write code like this then experience Pythonistas will probably take a dim view of your skills.

It's marginally acceptable to combine multiple statements on a line in some cases. For example:

x=0; y=1

... or even:

if some_condition(): break

... for simple break continue and even return statements or assigments.

In particular if one needs to use a series of elif one might use something like:

if     keystroke == 'q':   break
elif   keystroke == 'c':   action='continue'
elif   keystroke == 'd':   action='delete'
# ...
else:                      action='ask again'

... then you might not irk your colleagues too much. (However, chains of elif like that scream to be refactored into a dispatch table ... a dictionary that might look more like:

dispatch = {
    'q': foo.break,
    'c': foo.continue,
    'd': foo.delete
    }


# ...
while True:
    key = SomeGetKey()
    dispatch.get(key, foo.try_again)()

How to specify more spaces for the delimiter using cut?

One way around this is to go:

$ps axu | grep jboss | sed 's/\s\+/ /g' | cut -d' ' -f3

to replace multiple consecutive spaces with a single one.

How to attach source or JavaDoc in eclipse for any jar file e.g. JavaFX?

You can configure the Javadocs with downloading jar, basically javadocs will be referred directly from internet.

Complete steps:

  1. Open the Build Path page of the project (right click, properties, Java build path).
  2. Open the Libraries tab.
  3. Expand the node of the library in question (JavaFX).
  4. Select JavaDoc location and click edit.
  5. Enter the location to the file which contains the Javadoc. Specifically for the javaFX javadoc enter http://docs.oracle.com/javafx/2.0/api/

for offline javadocs, you can download from : http://www.oracle.com/technetwork/java/javase/documentation/java-se-7-doc-download-435117.html

After clicking Accept License Agreement you can download javafx-2_2_0-apidocs.zip

"SyntaxError: Unexpected token < in JSON at position 0"

I experienced this error "SyntaxError: Unexpected token m in JSON at position", where the token 'm' can be any other characters.

It turned out that I missed one of the double quotes in the JSON object when I was using RESTconsole for DB test, as {"name: "math"}, the correct one should be {"name": "math"}

It took me a lot effort to figure out this clumsy mistake. I am afraid others would run into similar bummers.

Git add all subdirectories

I can't say for sure if this is the case, but what appeared to be a problem for me was having .gitignore files in some of the subdirectories. Again, I can't guarantee this, but everything worked after these were deleted.

ng-options with simple array init

If you setup your select like the following:

<select ng-model="myselect" ng-options="b for b in options track by b"></select>

you will get:

<option value="var1">var1</option>
<option value="var2">var2</option>
<option value="var3">var3</option>

working fiddle: http://jsfiddle.net/x8kCZ/15/

How to set HTTP header to UTF-8 using PHP which is valid in W3C validator?

For a correct implementation, you need to change a series of things.

Database (immediately after the connection):

mysql_query("SET NAMES utf8");

// Meta tag HTML (probably it's already set): 
meta charset="utf-8"
header php (before any output of the HTML):
header('Content-Type: text/html; charset=utf-8')
table-rows-charset (for each row):
utf8_unicode_ci

Convert DataTable to List<T>

Assuming your DataRows inherit from your own type, say MyDataRowType, this should work:

List<MyDataRowType> list = new List<MyDataRowType>();

foreach(DataRow row in dataTable.Rows)
{
    list.Add((MyDataRowType)row);
}

This is assuming, as you said in a comment, that you're using .NET 2.0 and don't have access to the LINQ extension methods.

Custom Card Shape Flutter SDK

You can also customize the card theme globally with ThemeData.cardTheme:

MaterialApp(
  title: 'savvy',
  theme: ThemeData(
    cardTheme: CardTheme(
      shape: RoundedRectangleBorder(
        borderRadius: const BorderRadius.all(
          Radius.circular(8.0),
        ),
      ),
    ),
    // ...

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

You have to change androidx.constraintlayout.widget.ConstraintLayout to RelativeLayout.

Disable Required validation attribute under certain circumstances

I was looking for a solution where I can use the same model for an insert and update in web api. In my situation is this always a body content. The [Requiered] attributes must be skipped if it is an update method. In my solution, you place an attribute [IgnoreRequiredValidations] above the method. This is as follows:

public class WebServiceController : ApiController
{
    [HttpPost]
    public IHttpActionResult Insert(SameModel model)
    {
        ...
    }

    [HttpPut]
    [IgnoreRequiredValidations]
    public IHttpActionResult Update(SameModel model)
    {
        ...
    }

    ...

What else needs to be done? An own BodyModelValidator must becreated and added at the startup. This is in the HttpConfiguration and looks like this: config.Services.Replace(typeof(IBodyModelValidator), new IgnoreRequiredOrDefaultBodyModelValidator());

using Owin;
using your_namespace.Web.Http.Validation;

[assembly: OwinStartup(typeof(your_namespace.Startup))]

namespace your_namespace
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            Configuration(app, new HttpConfiguration());
        }

        public void Configuration(IAppBuilder app, HttpConfiguration config)
        {
            config.Services.Replace(typeof(IBodyModelValidator), new IgnoreRequiredOrDefaultBodyModelValidator());
        }

        ...

My own BodyModelValidator is derived from the DefaultBodyModelValidator. And i figure out that i had to override the 'ShallowValidate' methode. In this override i filter the requierd model validators. And now the IgnoreRequiredOrDefaultBodyModelValidator class and the IgnoreRequiredValidations attributte class:

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web.Http.Controllers;
using System.Web.Http.Metadata;
using System.Web.Http.Validation;

namespace your_namespace.Web.Http.Validation
{
    public class IgnoreRequiredOrDefaultBodyModelValidator : DefaultBodyModelValidator
    {
        private static ConcurrentDictionary<HttpActionBinding, bool> _ignoreRequiredValidationByActionBindingCache;

        static IgnoreRequiredOrDefaultBodyModelValidator()
        {
            _ignoreRequiredValidationByActionBindingCache = new ConcurrentDictionary<HttpActionBinding, bool>();
        }

        protected override bool ShallowValidate(ModelMetadata metadata, BodyModelValidatorContext validationContext, object container, IEnumerable<ModelValidator> validators)
        {
            var actionContext = validationContext.ActionContext;

            if (RequiredValidationsIsIgnored(actionContext.ActionDescriptor.ActionBinding))
                validators = validators.Where(v => !v.IsRequired);          

            return base.ShallowValidate(metadata, validationContext, container, validators);
        }

        #region RequiredValidationsIsIgnored
        private bool RequiredValidationsIsIgnored(HttpActionBinding actionBinding)
        {
            bool ignore;

            if (!_ignoreRequiredValidationByActionBindingCache.TryGetValue(actionBinding, out ignore))
                _ignoreRequiredValidationByActionBindingCache.TryAdd(actionBinding, ignore = RequiredValidationsIsIgnored(actionBinding.ActionDescriptor as ReflectedHttpActionDescriptor));

            return ignore;
        }

        private bool RequiredValidationsIsIgnored(ReflectedHttpActionDescriptor actionDescriptor)
        {
            if (actionDescriptor == null)
                return false;

            return actionDescriptor.MethodInfo.GetCustomAttribute<IgnoreRequiredValidationsAttribute>(false) != null;
        } 
        #endregion
    }

    [AttributeUsage(AttributeTargets.Method, Inherited = true)]
    public class IgnoreRequiredValidationsAttribute : Attribute
    {

    }
}

Sources:

How to check for a JSON response using RSpec?

A lot of the above answers are a bit out of date, so this is a quick summary for a more recent version of RSpec (3.8+). This solution raises no warnings from rubocop-rspec and is inline with rspec best practices:

A successful JSON response is identified by two things:

  1. The content type of the response is application/json
  2. The body of the response can be parsed without errors

Assuming that the response object is the anonymous subject of the test, both of the above conditions can be validate using Rspec's built in matchers:

context 'when response is received' do
  subject { response }

  # check for a successful JSON response
  it { is_expected.to have_attributes(content_type: include('application/json')) }
  it { is_expected.to have_attributes(body: satisfy { |v| JSON.parse(v) }) }

  # validates OP's condition
  it { is_expected.to satisfy { |v| JSON.parse(v.body).key?('success') }
  it { is_expected.to satisfy { |v| JSON.parse(v.body)['success'] == true }
end

If you're prepared to name your subject then the above tests can be simplified further:

context 'when response is received' do
  subject(:response) { response }

  it 'responds with a valid content type' do
    expect(response.content_type).to include('application/json')
  end

  it 'responds with a valid json object' do
    expect { JSON.parse(response.body) }.not_to raise_error
  end

  it 'validates OPs condition' do
    expect(JSON.parse(response.body, symoblize_names: true))
      .to include(success: true)
  end
end

C - error: storage size of ‘a’ isn’t known

Say it like this: struct xyx a;

c# open file with default application and parameters

Please add Settings under Properties for the Project and make use of them this way you have clean and easy configurable settings that can be configured as default

How To: Create a New Setting at Design Time

Update: after comments below

  1. Right + Click on project
  2. Add New Item
  3. Under Visual C# Items -> General
  4. Select Settings File

The cast to value type 'Int32' failed because the materialized value is null

Had this error message when I was trying to select from a view.

The problem was the view recently had gained some new null rows (in SubscriberId column), and it had not been updated in EDMX (EF database first).

The column had to be Nullable type for it to work.

var dealer = Context.Dealers.Where(x => x.dealerCode == dealerCode).FirstOrDefault();

Before view refresh:

public int SubscriberId { get; set; }

After view refresh:

public Nullable<int> SubscriberId { get; set; }

Deleting and adding the view back in EDMX worked.

Hope it helps someone.

Base64 decode snippet in C++

I firstly made my own version and then found this topic.

Why does my version look simpler than others presented here? Am I doing something wrong? I didn't test it for speed.

inline char const* b64units = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

inline char* b64encode(void const* a, int64_t b) {
    ASSERT(a != nullptr);
    if (b > 0) {
        uint8_t const* aa = static_cast<uint8_t const*>(a);
        uint8_t v = 0;
        int64_t bp = 0;
        int64_t sb = 0;
        int8_t off = 0;
        int64_t nt = ((b + 2) / 3) * 4;
        int64_t nd = (b * 8) / 6;
        int64_t tl = ((b * 8) % 6) ? 1 : 0;
        int64_t nf = nt - nd - tl;
        int64_t ri = 0;
        char* r = new char[nt + 1]();
        for (int64_t i = 0; i < nd; i++) {
            v = (aa[sb] << off) | (aa[sb + 1] >> (8 - off));
            v >>= 2;
            r[ri] = b64units[v];
            ri += 1;
            bp += 6;
            sb = (bp / 8);
            off = (bp % 8);
        }
        if (tl > 0) {
            v = (aa[sb] << off);
            v >>= 2;
            r[ri] = b64units[v];
            ri += 1;
        }
        for (int64_t i = 0; i < nf; i++) {
            r[ri] = '=';
            ri += 1;
        }
        return r;
    } else return nullptr;
}

P.S.: My method works well. I tested it with Node.js:

let data = 'stackabuse.com';
let buff = new Buffer(data);
let base64data = buff.toString('base64');

How do I download a file using VBA (without Internet Explorer)

I was struggling for hours on this until I figured out it can be done in one line of powershell:

invoke-webrequest -Uri "http://myserver/Reports/Pages/ReportViewer.aspx?%2fClients%2ftest&rs:Format=PDF&rs:ClearSession=true&CaseCode=12345678" -OutFile "C:\Temp\test.pdf" -UseDefaultCredentials

I looked into doing it purely in VBA but it runs to several pages, so I just call my powershell script from VBA every time I want to download a file.

Simple.

Export a graph to .eps file with R

The easiest way I've found to create postscripts is the following, using the setEPS() command:

setEPS()
postscript("whatever.eps")
plot(rnorm(100), main="Hey Some Data")
dev.off()

sqlite copy data from one table to another

If you're copying data like that, that probably means your datamodel isn't fully normalized, right? Is it possible to make one list of countries and do a JOIN more?

Instead of a JOIN you could also use virtual tables so you don't have to change the queries in your system.

drop down list value in asp.net

<asp:DropDownList ID="DdlMonths" runat="server">
    <asp:ListItem Enabled="true" Text="Select Month" Value="-1"></asp:ListItem>
    <asp:ListItem Text="January" Value="1"></asp:ListItem>
    <asp:ListItem Text="February" Value="2"></asp:ListItem>
    ....
    <asp:ListItem Text="December" Value="12"></asp:ListItem>
</asp:DropDownList>

You can even use a RequiredFieldValidator which ignore this item, it considers it as unselected.

<asp:RequiredFieldValidator ID="ReqMonth" runat="server" ControlToValidate="DdlMonths"
    InitialValue="-1">
</asp:RequiredFieldValidator>

Include another HTML file in a HTML file

To insert contents of the named file:

<!--#include virtual="filename.htm"-->

What is the difference/usage of homebrew, macports or other package installation tools?

Currently, Macports has many more packages (~18.6 K) than there are Homebrew formulae (~3.1K), owing to its maturity. Homebrew is slowly catching up though.

Macport packages tend to be maintained by a single person.

Macports can keep multiple versions of packages around, and you can enable or disable them to test things out. Sometimes this list can get corrupted and you have to manually edit it to get things back in order, although this is not too hard.

Both package managers will ask to be regularly updated. This can take some time.

Note: you can have both package managers on your system! It is not one or the other. Brew might complain but Macports won't.

Also, if you are dealing with python or ruby packages, use a virtual environment wherever possible.

Getting the IP Address of a Remote Socket Endpoint

string ip = ((IPEndPoint)(testsocket.RemoteEndPoint)).Address.ToString();

How to fix the Eclipse executable launcher was unable to locate its companion shared library for windows 7?

Had similar issue, which was a result of update. Please make sure that names of libraries mentioned in eclipse.ini and the actual names of these files on your disk match exactly.

-startup
plugins\org.eclipse.equinox.launcher_1.0.100.v20080509-1800.jar

--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_1.1.1.R36x_v20100810

Here is the post that I used to fix this issue on my system http://codewithgeeks.blogspot.in/2013/11/fixing-eclipse-executable-launcher-was.html

What is the correct wget command syntax for HTTPS with username and password?

I have found that wget does not properly authenticate with some servers, perhaps because it is only HTTP 1.0 compliant. In such cases, curl (which is HTTP 1.1 compliant) usually does the trick:

curl -o <filename-to-save-as> -u <username>:<password> <url>

How to compare datetime with only date in SQL Server

Of-course this is an old thread but to make it complete.

From SQL 2008 you can use DATE datatype so you can simply do:

SELECT CONVERT(DATE,GETDATE())

OR

Select * from [User] U
where  CONVERT(DATE,U.DateCreated) = '2014-02-07' 

fork: retry: Resource temporarily unavailable

Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used

watch -n 5 -d "ps -eL <java_pid> | wc -l"

to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.

Get keys of a Typescript interface as array of strings

The following requires you to list the keys on your own, but at least TypeScript will enforce IUserProfile and IUserProfileKeys have the exact same keys (Required<T> was added in TypeScript 2.8):

export interface IUserProfile  {
  id: string;
  name: string;
};
type KeysEnum<T> = { [P in keyof Required<T>]: true };
const IUserProfileKeys: KeysEnum<IUserProfile> = {
  id: true,
  name: true,
};

Bring element to front using CSS

Note: z-index only works on positioned elements (position:absolute, position:relative, or position:fixed). Use one of those.

Postman: How to make multiple requests at the same time

I don't know if this question is still relevant, but there is such possibility in Postman now. They added it a few months ago.

All you need is create simple .js file and run it via node.js. It looks like this:

var path = require('path'),
  async = require('async'), //https://www.npmjs.com/package/async
  newman = require('newman'),

  parametersForTestRun = {
    collection: path.join(__dirname, 'postman_collection.json'), // your collection
    environment: path.join(__dirname, 'postman_environment.json'), //your env
  };

parallelCollectionRun = function(done) {
  newman.run(parametersForTestRun, done);
};

// Runs the Postman sample collection thrice, in parallel.
async.parallel([
    parallelCollectionRun,
    parallelCollectionRun,
    parallelCollectionRun
  ],
  function(err, results) {
    err && console.error(err);

    results.forEach(function(result) {
      var failures = result.run.failures;
      console.info(failures.length ? JSON.stringify(failures.failures, null, 2) :
        `${result.collection.name} ran successfully.`);
    });
  });

Then just run this .js file ('node fileName.js' in cmd).

More details here

Node.js connect only works on localhost

CHECK YOUR ANTI-VIRUS FIREWALL SETTINGS.

I have a NodeJS server working on Windows 10 PC, but when I put the IP address and port (example http://102.168.1.123:5000) into another computer's browser on my local network nothing happened, although it worked OK on the host computer.

(To find your windows IP address run CMD, then IPCONFIG)

Bar Horing Amir's answer points to the Windows firewall settings. On My PC the Windows Firewall was turned off - as McAfee anti-virus has added its own Firewall.

My system started to work on other computers after I added port 5000 to 'Ports and Systems Services' under the McAfee Firewall settings on the computer with NodeJS on it. Other anti-virus software will have similar settings.

I would seriously suggest trying this solution first with Windows.

What does cmd /C mean?

The part you should be interested in is the /? part, which should solve most other questions you have with the tool.

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\>cmd /?
Starts a new instance of the Windows XP command interpreter

CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
    [[/S] [/C | /K] string]

/C      Carries out the command specified by string and then terminates
/K      Carries out the command specified by string but remains
/S      Modifies the treatment of string after /C or /K (see below)
/Q      Turns echo off
/D      Disable execution of AutoRun commands from registry (see below)
/A      Causes the output of internal commands to a pipe or file to be ANSI
/U      Causes the output of internal commands to a pipe or file to be
        Unicode
/T:fg   Sets the foreground/background colors (see COLOR /? for more info)
/E:ON   Enable command extensions (see below)
/E:OFF  Disable command extensions (see below)
/F:ON   Enable file and directory name completion characters (see below)
/F:OFF  Disable file and directory name completion characters (see below)
/V:ON   Enable delayed environment variable expansion using ! as the
        delimiter. For example, /V:ON would allow !var! to expand the
        variable var at execution time.  The var syntax expands variables
        at input time, which is quite a different thing when inside of a FOR
        loop.
/V:OFF  Disable delayed environment expansion.

Oracle: what is the situation to use RAISE_APPLICATION_ERROR?

You use RAISE_APPLICATION_ERROR in order to create an Oracle style exception/error that is specific to your code/needs. Good use of these help to produce code that is clearer, more maintainable, and easier to debug.

For example, if I have an application calling a stored procedure that adds a user and that user already exists, you'll usually get back an error like:

ORA-00001: unique constraint (USERS.PK_USER_KEY) violated

Obviously this error and associated message are not unique to the task you were trying to do. Creating your own Oracle application errors allow you to be clearer on the intent of the action and the cause of the issue.

raise_application_error(-20101, 'User ' || in_user || ' already exists!');

Now your application code can write an exception handler in order to process this specific error condition. Think of it as a way to make Oracle communicate error conditions that your application expects in a "language" (for lack of a better term) that you have defined and is more meaningful to your application's problem domain.

Note that user defined errors must be in the range between -20000 and -20999.

The following link provides lots of good information on this topic and Oracle exceptions in general.

Programmatically stop execution of python script?

You could raise SystemExit(0) instead of going to all the trouble to import sys; sys.exit(0).

When is JavaScript synchronous?

"I have been under the impression for that JavaScript was always asynchronous"

You can use JavaScript in a synchronous way, or an asynchronous way. In fact JavaScript has really good asynchronous support. For example I might have code that requires a database request. I can then run other code, not dependent on that request, while I wait for that request to complete. This asynchronous coding is supported with promises, async/await, etc. But if you don't need a nice way to handle long waits then just use JS synchronously.

What do we mean by 'asynchronous'. Well it does not mean multi-threaded, but rather describes a non-dependent relationship. Check out this image from this popular answer:

         A-Start ------------------------------------------ A-End   
           | B-Start -----------------------------------------|--- B-End   
           |    |      C-Start ------------------- C-End      |      |   
           |    |       |                           |         |      |
           V    V       V                           V         V      V      
1 thread->|<-A-|<--B---|<-C-|-A-|-C-|--A--|-B-|--C-->|---A---->|--B-->| 

We see that a single threaded application can have async behavior. The work in function A is not dependent on function B completing, and so while function A began before function B, function A is able to complete at a later time and on the same thread.

So, just because JavaScript executes one command at a time, on a single thread, it does not then follow that JavaScript can only be used as a synchronous language.

"Is there a good reference anywhere about when it will be synchronous and when it will be asynchronous"

I'm wondering if this is the heart of your question. I take it that you mean how do you know if some code you are calling is async or sync. That is, will the rest of your code run off and do something while you wait for some result? Your first check should be the documentation for whichever library you are using. Node methods, for example, have clear names like readFileSync. If the documentation is no good there is a lot of help here on SO. EG:

How to know if a function is async?

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

Whenever I'm testing something with PHP/Curl, I try it from the command line first, figure out what works, and then port my options to PHP.

T-SQL: Deleting all duplicate rows but keeping one

You didn't say what version you were using, but in SQL 2005 and above, you can use a common table expression with the OVER Clause. It goes a little something like this:

WITH cte AS (
  SELECT[foo], [bar], 
     row_number() OVER(PARTITION BY foo, bar ORDER BY baz) AS [rn]
  FROM TABLE
)
DELETE cte WHERE [rn] > 1

Play around with it and see what you get.

(Edit: In an attempt to be helpful, someone edited the ORDER BY clause within the CTE. To be clear, you can order by anything you want here, it needn't be one of the columns returned by the cte. In fact, a common use-case here is that "foo, bar" are the group identifier and "baz" is some sort of time stamp. In order to keep the latest, you'd do ORDER BY baz desc)

Set JavaScript variable = null, or leave undefined?

Generally, I use null for values that I know can have a "null" state; for example

if(jane.isManager == false){
  jane.employees = null
}

Otherwise, if its a variable or function that's not defined yet (and thus, is not "usable" at the moment) but is supposed to be setup later, I usually leave it undefined.

How to export JSON from MongoDB using Robomongo

Don't run this command on shell, enter this script at a command prompt with your database name, collection name, and file name, all replacing the placeholders..

mongoexport --db (Database name) --collection (Collection Name) --out (File name).json

It works for me.

pandas: How do I split text in a column into multiple rows?

This splits the Seatblocks by space and gives each its own row.

In [43]: df
Out[43]: 
   CustNum     CustomerName  ItemQty Item                 Seatblocks  ItemExt
0    32363  McCartney, Paul        3  F04               2:218:10:4,6       60
1    31316     Lennon, John       25  F01  1:13:36:1,12 1:13:37:1,13      300

In [44]: s = df['Seatblocks'].str.split(' ').apply(Series, 1).stack()

In [45]: s.index = s.index.droplevel(-1) # to line up with df's index

In [46]: s.name = 'Seatblocks' # needs a name to join

In [47]: s
Out[47]: 
0    2:218:10:4,6
1    1:13:36:1,12
1    1:13:37:1,13
Name: Seatblocks, dtype: object

In [48]: del df['Seatblocks']

In [49]: df.join(s)
Out[49]: 
   CustNum     CustomerName  ItemQty Item  ItemExt    Seatblocks
0    32363  McCartney, Paul        3  F04       60  2:218:10:4,6
1    31316     Lennon, John       25  F01      300  1:13:36:1,12
1    31316     Lennon, John       25  F01      300  1:13:37:1,13

Or, to give each colon-separated string in its own column:

In [50]: df.join(s.apply(lambda x: Series(x.split(':'))))
Out[50]: 
   CustNum     CustomerName  ItemQty Item  ItemExt  0    1   2     3
0    32363  McCartney, Paul        3  F04       60  2  218  10   4,6
1    31316     Lennon, John       25  F01      300  1   13  36  1,12
1    31316     Lennon, John       25  F01      300  1   13  37  1,13

This is a little ugly, but maybe someone will chime in with a prettier solution.

How to put an image in div with CSS?

With Javascript/Jquery:

  • load image with hidden img
  • when image has been loaded, get width and height
  • dynamically create a div and set width, height and background
  • remove the original img

      $(document).ready(function() {
        var image = $("<img>");
        var div = $("<div>")
        image.load(function() {
          div.css({
            "width": this.width,
            "height": this.height,
            "background-image": "url(" + this.src + ")"
          });
          $("#container").append(div);
        });
        image.attr("src", "test0.png");
      });
    

How to get Android GPS location

The initial issue is solved by changing lat and lon to double.

I want to add comment to solution with Location location = locationManager.getLastKnownLocation(bestProvider); It works to find out last known location when other app was lisnerning for that. If, for example, no app did that since device start, the code will return zeros (spent some time myself recently to figure that out).

Also, it's a good practice to stop listening when there is no need for that by locationManager.removeUpdates(this);

Also, even with permissions in manifest, the code works when location service is enabled in Android settings on a device.

How to run Visual Studio post-build events for debug build only

Pre- and Post-Build Events run as a batch script. You can do a conditional statement on $(ConfigurationName).

For instance

if $(ConfigurationName) == Debug xcopy something somewhere

TINYTEXT, TEXT, MEDIUMTEXT, and LONGTEXT maximum storage sizes

Expansion of the same answer

  1. This SO post outlines in detail the overheads and storage mechanisms.
  2. As noted from point (1), A VARCHAR should always be used instead of TINYTEXT. However, when using VARCHAR, the max rowsize should not exceeed 65535 bytes.
  3. As outlined here http://dev.mysql.com/doc/refman/5.0/en/charset-unicode-utf8.html, max 3 bytes for utf-8.

THIS IS A ROUGH ESTIMATION TABLE FOR QUICK DECISIONS!

  1. So the worst case assumptions (3 bytes per utf-8 char) to best case (1 byte per utf-8 char)
  2. Assuming the english language has an average of 4.5 letters per word
  3. x is the number of bytes allocated

x-x

      Type | A= worst case (x/3) | B = best case (x) | words estimate (A/4.5) - (B/4.5)
-----------+---------------------------------------------------------------------------
  TINYTEXT |              85     | 255               | 18 - 56
      TEXT |          21,845     | 65,535            | 4,854.44 - 14,563.33  
MEDIUMTEXT |       5,592,415     | 16,777,215        | 1,242,758.8 - 3,728,270
  LONGTEXT |   1,431,655,765     | 4,294,967,295     | 318,145,725.5 - 954,437,176.6

Please refer to Chris V's answer as well : https://stackoverflow.com/a/35785869/1881812

SQL 'like' vs '=' performance

If value is unindexed, both result in a table-scan. The performance difference in this scenario will be negligible.

If value is indexed, as Daniel points out in his comment, the = will result in an index lookup which is O(log N) performance. The LIKE will (most likely - depending on how selective it is) result in a partial scan of the index >= 'abc' and < 'abd' which will require more effort than the =.

Note that I'm talking SQL Server here - not all DBMSs will be nice with LIKE.

How to show only next line after the matched one?

If you want to stick to grep:

grep -A1 'blah' logfile | grep -v "blah"

or alternatively with sed:

sed -n '/blah/{n;p;}' logfile