Programs & Examples On #Mbt

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

For the Collatz problem, you can get a significant boost in performance by caching the "tails". This is a time/memory trade-off. See: memoization (https://en.wikipedia.org/wiki/Memoization). You could also look into dynamic programming solutions for other time/memory trade-offs.

Example python implementation:

import sys

inner_loop = 0

def collatz_sequence(N, cache):
    global inner_loop

    l = [ ]
    stop = False
    n = N

    tails = [ ]

    while not stop:
        inner_loop += 1
        tmp = n
        l.append(n)
        if n <= 1:
            stop = True  
        elif n in cache:
            stop = True
        elif n % 2:
            n = 3*n + 1
        else:
            n = n // 2
        tails.append((tmp, len(l)))

    for key, offset in tails:
        if not key in cache:
            cache[key] = l[offset:]

    return l

def gen_sequence(l, cache):
    for elem in l:
        yield elem
        if elem in cache:
            yield from gen_sequence(cache[elem], cache)
            raise StopIteration

if __name__ == "__main__":
    le_cache = {}

    for n in range(1, 4711, 5):
        l = collatz_sequence(n, le_cache)
        print("{}: {}".format(n, len(list(gen_sequence(l, le_cache)))))

    print("inner_loop = {}".format(inner_loop))

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

You can increase the timeout in node like so.

app.post('/slow/request', function(req, res){ req.connection.setTimeout(100000); //100 seconds ... }

How can I use onItemSelected in Android?

If you don't want to implement the listener, you can set it up like this directly where you want it (call on your spinner after your adapter has been set):

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

                switch (position) {
                    case 0:
                        Toast.makeText(parent.getContext(), "Spinner item 1!", Toast.LENGTH_SHORT).show();
                        break;
                    case 1:
                        Toast.makeText(parent.getContext(), "Spinner item 2!", Toast.LENGTH_SHORT).show();
                        break;
                    case 2:
                        Toast.makeText(parent.getContext(), "Spinner item 3!", Toast.LENGTH_SHORT).show();
                        break;
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

               // sometimes you need nothing here
            }
        });

Android + Pair devices via bluetooth programmatically

if you have the BluetoothDevice object you can create bond(pair) from api 19 onwards with bluetoothDevice.createBond() method.

Edit

for callback, if the request was accepted or denied you will have to create a BroadcastReceiver with BluetoothDevice.ACTION_BOND_STATE_CHANGED action

Install sbt on ubuntu

My guess is that the directory ~/bin/sbt/bin is not in your PATH.

To execute programs or scripts that are in the current directory you need to prefix the command with ./, as in:

./sbt

This is a security feature in linux, so to prevent overriding of system commands (and other programs) by a malicious party dropping a file in your home directory (for example). Imagine a script called 'ls' that emails your /etc/passwd file to 3rd party before executing the ls command... Or one that executes 'rm -rf .'...

That said, unless you need something specific from the latest source code, you're best off doing what paradigmatic said in his post, and install it from the Typesafe repository.

How to use google maps without api key

Hey You can Use this insted

<iframe width="100%" height="100%" class="absolute inset-0" frameborder="0" title="map" marginheight="0" marginwidth="0" scrolling="no" src="https://maps.google.com/maps?width=100%&amp;height=600&amp;hl=en&amp;q=%C4%B0ikaneir+(Mumma's%20Bakery)&amp;ie=UTF8&amp;t=&amp;z=14&amp;iwloc=B&amp;output=embed" style="filter: scale(100) contrast(1.2) opacity(0.4);"></iframe>

Fill Combobox from database

You will have to completely re-write your code. DisplayMember and ValueMember point to columnNames! Furthermore you should really use a using block - so the connection gets disposed (and closed) after query execution.

Instead of using a dataReader to access the values I choosed a dataTable and bound it as dataSource onto the comboBox.

using (SqlConnection conn = new SqlConnection(@"Data Source=SHARKAWY;Initial Catalog=Booking;Persist Security Info=True;User ID=sa;Password=123456"))
{
    try
    {
        string query = "select FleetName, FleetID from fleets";
        SqlDataAdapter da = new SqlDataAdapter(query, conn);
        conn.Open();
        DataSet ds = new DataSet();
        da.Fill(ds, "Fleet");
        cmbTripName.DisplayMember =  "FleetName";
        cmbTripName.ValueMember = "FleetID";
        cmbTripName.DataSource = ds.Tables["Fleet"];
    }
    catch (Exception ex)
    {
        // write exception info to log or anything else
        MessageBox.Show("Error occured!");
    }               
}

Using a dataTable may be a little bit slower than a dataReader but I do not have to create my own class. If you really have to/want to make use of a DataReader you may choose @Nattrass approach. In any case you should write a using block!

EDIT

If you want to get the current Value of the combobox try this

private void cmbTripName_SelectedIndexChanged(object sender, EventArgs e)
{
    if (cmbTripName.SelectedItem != null)
    {
        DataRowView drv = cmbTripName.SelectedItem as DataRowView;

        Debug.WriteLine("Item: " + drv.Row["FleetName"].ToString());
        Debug.WriteLine("Value: " + drv.Row["FleetID"].ToString());
        Debug.WriteLine("Value: " + cmbTripName.SelectedValue.ToString());
    }
}

How to convert image into byte array and byte array to base64 String in android?

I wrote the following code to convert an image from sdcard to a Base64 encoded string to send as a JSON object.And it works great:

String filepath = "/sdcard/temp.png";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
    fis = new FileInputStream(imagefile);
    } catch (FileNotFoundException e) {
    e.printStackTrace();
}

Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos);    
byte[] b = baos.toByteArray(); 
encImage = Base64.encodeToString(b, Base64.DEFAULT);

Python base64 data decode

After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.

Neither BindingResult nor plain target object for bean name available as request attr

We faced the same issue and changed commandname="" to modelAttribute="" in jsp page to solve this issue.

What online brokers offer APIs?

Only related with currency trading (Forex), but many Forex brokers are offering MetaTrader which let you code in MQL. The main problem with it (aside that it's limited to Forex) is that you've to code in MQL which might not be your preferred language.

Receiving "Attempted import error:" in react app

import { combineReducers } from '../../store/reducers';

should be

import combineReducers from '../../store/reducers';

since it's a default export, and not a named export.

There's a good breakdown of the differences between the two here.

JQuery $.each() JSON array object iteration

Assign the second variable for the $.each function() as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

$.each(json, function(arrayID,group) {
            console.log('<a href="'+group.GROUP_ID+'">');
    $.each(group.EVENTS, function(eventID,eventData) {
            console.log('<p>'+eventData.SHORT_DESC+'</p>');
     });
});

Should print out everything you were trying in your question.

http://jsfiddle.net/niklasvh/hZsQS/

edit renamed the variables to make it bit easier to understand what is what.

Java: Get month Integer from Date

If you can't use Joda time and you still live in the dark world :) ( Java 5 or lower ) you can enjoy this :

Note: Make sure your date is allready made by the format : dd/MM/YYYY

/**
Make an int Month from a date
*/
public static int getMonthInt(Date date) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
    return Integer.parseInt(dateFormat.format(date));
}

/**
Make an int Year from a date
*/
public static int getYearInt(Date date) {

    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
    return Integer.parseInt(dateFormat.format(date));
}

Determine the data types of a data frame's columns

sapply(yourdataframe, class)

Where yourdataframe is the name of the data frame you're using

Use CSS to automatically add 'required field' asterisk to form inputs

Use jQuery and CSS

_x000D_
_x000D_
jQuery(document).ready(function() {_x000D_
 jQuery("[required]").after("<span class='required'>*</span>");_x000D_
});
_x000D_
.required {_x000D_
    position: absolute;_x000D_
    margin-left: -10px;_x000D_
    color: #FB0000;_x000D_
    font-size: 15px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" value="xxx" required>
_x000D_
_x000D_
_x000D_

Android: install .apk programmatically

For ICS I´ve implemented your code and made a class that extends AsyncTask. I hope you appreciate it! Thanks for your code and solution.

public class UpdateApp extends AsyncTask<String,Void,Void>{
    private Context context;
    public void setContext(Context contextf){
        context = contextf;
    }

    @Override
    protected Void doInBackground(String... arg0) {
        try {
            URL url = new URL(arg0[0]);
            HttpURLConnection c = (HttpURLConnection) url.openConnection();
            c.setRequestMethod("GET");
            c.setDoOutput(true);
            c.connect();

            String PATH = "/mnt/sdcard/Download/";
            File file = new File(PATH);
            file.mkdirs();
            File outputFile = new File(file, "update.apk");
            if(outputFile.exists()){
                outputFile.delete();
            }
            FileOutputStream fos = new FileOutputStream(outputFile);

            InputStream is = c.getInputStream();

            byte[] buffer = new byte[1024];
            int len1 = 0;
            while ((len1 = is.read(buffer)) != -1) {
                fos.write(buffer, 0, len1);
            }
            fos.close();
            is.close();

            Intent intent = new Intent(Intent.ACTION_VIEW);
            intent.setDataAndType(Uri.fromFile(new File("/mnt/sdcard/Download/update.apk")), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
            context.startActivity(intent);


        } catch (Exception e) {
            Log.e("UpdateAPP", "Update error! " + e.getMessage());
        }
        return null;
    }
}   

To use it, in your main activity call by this way:

atualizaApp = new UpdateApp();
atualizaApp.setContext(getApplicationContext());
atualizaApp.execute("http://serverurl/appfile.apk");

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

I don't know is there any method in Python API.But you can use this simple code to add Salt-and-Pepper noise to an image.

import numpy as np
import random
import cv2

def sp_noise(image,prob):
    '''
    Add salt and pepper noise to image
    prob: Probability of the noise
    '''
    output = np.zeros(image.shape,np.uint8)
    thres = 1 - prob 
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = random.random()
            if rdn < prob:
                output[i][j] = 0
            elif rdn > thres:
                output[i][j] = 255
            else:
                output[i][j] = image[i][j]
    return output

image = cv2.imread('image.jpg',0) # Only for grayscale image
noise_img = sp_noise(image,0.05)
cv2.imwrite('sp_noise.jpg', noise_img)

Find and replace with sed in directory and sub directories

grep -e apple your_site_root/**/*.* -s -l | xargs sed -i "" "s|apple|orage|"

Header set Access-Control-Allow-Origin in .htaccess doesn't work

This should work:

Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

Accessing inventory host variable in Ansible playbook

I struggled with this, too. My specific setup is: Your host.ini (with the modern names):

[test3]
test3-1 ansible_host=abc.def.ghi.pqr ansible_port=1212
test3-2 ansible_host=abc.def.ghi.stu ansible_port=1212

plus a play fill_file.yml

---
- remote_user: ec2-user
  hosts: test3
  tasks:
   - name: fill file
     template:
       src: file.j2
       dest: filled_file.txt

plus a template file.j2 , like

{% for host in groups['test3'] %}
   {{ hostvars[host].ansible_host }}
{% endfor %}

This worked for me, the result is

abc.def.ghi.pqr
abc.def.ghi.stu

I have to admit it's ansible 2.7, not 2.1. The template is a variation of an example in https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html.

The accepted answer didn't work in my setup. With a template

{{ hostvars['test3'].ansible_host }}

my play fails with "AnsibleUndefinedVariable: \"hostvars['test3']\" is undefined" .

Remark: I tried some variations, but failed, occasionally with "ansible.vars.hostvars.HostVars object has no element "; Some of this might be explained by what they say. in https://github.com/ansible/ansible/issues/13343#issuecomment-160992631

hostvars emulates a dictionary [...]. hostvars is also lazily loaded

Converting camel case to underscore case in ruby

In case someone looking for case when he need to apply underscore to string with spaces and want to convert them to underscores as well you can use something like this

'your String will be converted To underscore'.parameterize.underscore
#your_string_will_be_converted_to_underscore

Or just use .parameterize('_') but keep in mind that this one is deprecated

'your String will be converted To underscore'.parameterize('_')
#your_string_will_be_converted_to_underscore

Quick Way to Implement Dictionary in C

Hashing is the key. I think use lookup table and hashing key for this. You can find many hashing function online.

Can I call an overloaded constructor from another constructor of the same class in C#?

If you mean if you can do ctor chaining in C#, the answer is yes. The question has already been asked.

However it seems from the comments, it seems what you really intend to ask is 'Can I call an overloaded constructor from within another constructor with pre/post processing?'
Although C# doesn't have the syntax to do this, you could do this with a common initialization function (like you would do in C++ which doesn't support ctor chaining)

class A
{
  //ctor chaining
  public A() : this(0)
  {  
      Console.WriteLine("default ctor"); 
  }

  public A(int i)
  {  
      Init(i); 
  }

  // what you want
  public A(string s)
  {  
      Console.WriteLine("string ctor overload" );
      Console.WriteLine("pre-processing" );
      Init(Int32.Parse(s));
      Console.WriteLine("post-processing" );
  }

   private void Init(int i)
   {
      Console.WriteLine("int ctor {0}", i);
   }
}

How to clear browsing history using JavaScript?

to disable back function of the back button:

window.addEventListener('popstate', function (event) {
  history.pushState(null, document.title, location.href);
});

What datatype should be used for storing phone numbers in SQL Server 2005?

nvarchar with preprocessing to standardize them as much as possible. You'll probably want to extract extensions and store them in another field.

How to install ADB driver for any android device?

You don't really need to install or use any third party tools.

The drivers located in ...\Android\Sdk\extras\google\usb_driver work just fine.

Step 1: In Device Manager, Right click on the malfunctioning Android ADB Interface driver

Step 2: Select Update Driver Software

Step 3: Select Browse my computer for driver software

Step 4: Select Let me pick from a list of device drivers on my computer

Step 5: Select Have Disk

This window pops up:

enter image description here

Step 6: Copy the location of the Google USB Driver (...\Android\Sdk\extras\google\usb_driver) or browse to it.

Step 7: Click Ok

This window pops up:

enter image description here

Step 8: Select Android ADB Interface and click Next

The window below pops up with a warning:

enter image description here

That's it. You driver installation will start and in a few seconds, you should be able to see your device

Specify the date format in XMLGregorianCalendar

Much simpler using only SimpleDateFormat, without passing all the parameters individual:

    String FORMATER = "yyyy-MM-dd'T'HH:mm:ss'Z'";

    DateFormat format = new SimpleDateFormat(FORMATER);

    Date date = new Date();
    XMLGregorianCalendar gDateFormatted =
        DatatypeFactory.newInstance().newXMLGregorianCalendar(format.format(date));

Full example here.

Note: This is working only to remove the last 2 fields: milliseconds and timezone or to remove the entire time component using formatter yyyy-MM-dd.

Pylint "unresolved import" error in Visual Studio Code

In my case I already had a Conda environment activated, but I still wanted local Python modules to be available for autocomplete, peeking definition, etc.

I tried many solutions such as adding a list of Python paths etc., but what finally solved it for me was to create a symbolic link from Conda's lib/python{your version}/site-packages to my local module.

How to fire a button click event from JavaScript in ASP.NET

You can just place this line in a JavaScript function:

__doPostBack('btnSubmit','OnClick');

Or do something like this:

$('#btnSubmit').trigger('click');

The located assembly's manifest definition does not match the assembly reference

I had the same issue today which prevented me from performing Add-Migration after I made changes in Entity Framework.

I had two projects in my solution, let's call them "Client" and "Data" - a class library project which held my EF models and context. The Client referenced the Data project.

I had signed both projects, and then later made changes to an EF model. After I removed the signature I were able to add the migrations, and could then signed the project anew.

I hope this can be useful for someone, sparing them of prolonged frustration..

Creating Accordion Table with Bootstrap

This seems to be already asked before:

This might help:

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

UPDATE:

Your fiddle wasn't loading jQuery, so anything worked.

<table class="table table-hover">
<thead>
  <tr>
    <th></th>
    <th></th>
    <th></th>
  </tr>
</thead>

<tbody>
    <tr data-toggle="collapse" data-target="#accordion" class="clickable">
        <td>Some Stuff</td>
        <td>Some more stuff</td>
        <td>And some more</td>
    </tr>
    <tr>
        <td colspan="3">
            <div id="accordion" class="collapse">Hidden by default</div>
        </td>
    </tr>
</tbody>
</table>

Try this one: http://jsfiddle.net/Nb7wy/2/

I also added colspan='2' to the details row. But it's essentially your fiddle with jQuery loaded (in frameworks in the left column)

How to include duplicate keys in HashMap?

hashMaps can't have duplicate keys. That said, you can create a map with list values:

Map<Integer, List<String>>

However, using this approach will have performance implications.

View stored procedure/function definition in MySQL

SHOW CREATE PROCEDURE <name>

Returns the text of a previously defined stored procedure that was created using the CREATE PROCEDURE statement. Swap PROCEDURE for FUNCTION for a stored function.

Setting a PHP $_SESSION['var'] using jQuery

Whats you are looking for is jQuery Ajax. And then just setup a php page to process the request.

Use underscore inside Angular controllers

If you don't mind using lodash try out https://github.com/rockabox/ng-lodash it wraps lodash completely so it is the only dependency and you don't need to load any other script files such as lodash.

Lodash is completely off of the window scope and no "hoping" that it's been loaded prior to your module.

Forking / Multi-Threaded Processes | Bash

Based on what you all shared I was able to put this together:

#!/usr/bin/env bash

VAR1="192.168.1.20 192.168.1.126 192.168.1.36"

for a in $VAR1; do { ssh -t -t $a -l Administrator "sudo softwareupdate -l"; } & done;
WAITPIDS="$WAITPIDS "$!;...; wait $WAITPIDS
echo "Script has finished"

Exit 1

This lists all the updates on the mac on three machines at once. Later on I used it to perform a software update for all machines when i CAT my ipaddress.txt

Debugging with Android Studio stuck at "Waiting For Debugger" forever

This solution works for me:

turning off the USB debugging from my device settings , and then turning it on again.

its Much quicker and easier than restart the device.

CSS display:table-row does not expand when width is set to 100%

Tested answer:

In the .view-row css, change:

display:table-row;

to:

display:table

and get rid of "float". Everything will work as expected.

As it has been suggested in the comments, there is no need for a wrapping table. CSS allows for omitting levels of the tree structure (in this case rows) that are implicit. The reason your code doesn't work is that "width" can only be interpreted at the table level, not at the table-row level. When you have a "table" and then "table-cell"s directly underneath, they're implicitly interpreted as sitting in a row.

Working example:

<div class="view">
    <div>Type</div>
    <div>Name</div>                
</div>

with css:

.view {
  width:100%;
  display:table;
}

.view > div {
  width:50%;
  display: table-cell;
}

Difference between frontend, backend, and middleware in web development

Here is one breakdown:

Front-end tier -> User Interface layer usually consisting of a mix of HTML, Javascript, CSS, Flash, and various server-side code like ASP.Net, classic ASP, PHP, etc. Think of this as being closest to the user in terms of code.

Middleware, middle-tier -> One tier back, generally referred to as the "plumbing" part of a system. Java and C# are common languages for writing this part that could be viewed as the glue between the UI and the data and can be webservices or WCF components or other SOA components possibly.

Back-end tier -> Databases and other data stores are generally at this level. Oracle, MS-SQL, MySQL, SAP, and various off-the-shelf pieces of software come to mind for this piece of software that is the final processing of the data.

Overlap can exist between any of these as you could have everything poured into one layer like an ASP.Net website that uses the built-in AJAX functionality that generates Javascript while the code behind may contain database commands making the code behind contain both middle and back-end tiers. Alternatively, one could use VBScript to act as all the layers using ADO objects and merging all three tiers into one.

Similarly, taking middleware and either front or back-end can be combined in some cases.

Bottlenecks generally have a few different levels to them:

1) Database or back-end processing -> This can vary from payroll or sales or other tasks where the throughput to the database is bogging things down.

2) Middleware bottlenecks -> This would be where some web service may be hitting capacity but the front and back ends have bandwidth to handle more traffic. Alternatively, there may be some server that is part of a system that isn't quite the UI part or the raw data that can be a bottleneck using something like Biztalk or MSMQ.

3) Front-end bottlenecks -> This could client or server-side issues. For example, if you took a low-end PC and had it load a web page that consisted of a lot of data being downloaded, the client could be where the bottleneck is. Similarly, the server could be queuing up requests if it is getting hammered with requests like what Amazon.com or other high-traffic websites may get at times.

Some of this is subject to interpretation, so it isn't perfect by any means and YMMV.


EDIT: Something to consider is that some systems can have multiple front-ends or back-ends. For example, a content management system will likely have a way for site visitors to view the content that is a front-end but what about how content editors are able to change the data on the site? The ability to pull up this data could be seen as front-end since it is a UI component or it could be seen as a back-end since it is used by internal users rather than the general public viewing the site. Thus, there is something to be said for context here.

How can I send mail from an iPhone application

A few things I'd like to add here:

  1. Using the mailto URL won't work in the simulator as mail.app isn't installed on the simulator. It does work on device though.

  2. There is a limit to the length of the mailto URL. If the URL is larger than 4096 characters, mail.app won't launch.

  3. There is a new class in OS 3.0 that lets you send an e-mail without leaving your app. See the class MFMailComposeViewController.

moving committed (but not pushed) changes to a new branch after pull

One more way assume branch1 - is branch with committed changes branch2 - is desirable branch

git fetch && git checkout branch1
git log

select commit ids that you need to move

git fetch && git checkout branch2
git cherry-pick commit_id_first..commit_id_last
git push

Now revert unpushed commits from initial branch

git fetch && git checkout branch1
git reset --soft HEAD~1

How to change HTML Object element data attribute value in javascript

This works:

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

<object type="text/html" id="htmlFrame" style="border: none;" standby="loading" width="100%"></object> 

<script type="text/javascript">
  var element = document.getElementById("htmlFrame"); 
  element.setAttribute("data", "attributeValue"); 
</script>

</body>
</html>

If you put this in a file, open in it a web browser, the javascript will execute and and the "data" attribute + value will be added to the object element.

Note: If you simply look at the HTML source, you wil NOT see the attribute. This is because the browser is showing you the static source sent by the webserver, NOT the dynamically rendered DOM. To inspect the DOM, use a tool like Firebug. This will show you what DOM the browser has rendered, and you will be able to see the added attribute.

Using Firefox + Firebug or Google Chrome, you can right click on a part of a page and do "Inspect Element". This will bring up a view of the rendered DOM.

How can I convert integer into float in Java?

// The integer I want to convert

int myInt = 100;

// Casting of integer to float

float newFloat = (float) myInt

How do I change the default schema in sql developer?

Just create a new connection (hit the green plus sign) and enter the schema name and password of the new default schema your DBA suggested. You can switch between your old schema and the new schema with the pull down menu at the top right end of your window.

Disable sorting on last column when using jQuery DataTables

I would like to develop the current answer.

The good way is to use aoColumnDefs as mentioned.
The default value for the bSortable parameter is true (for each column).

You've got 2 options...

By index :

var table = $('#example').DataTable({
   'aoColumnDefs': [{
        'bSortable': false,
        'aTargets': [-1] /* 1st one, start by the right */
    }]
});

By class :

var table = $('#example').DataTable({
   'aoColumnDefs': [{
        'bSortable': false,
        'aTargets': ['nosort']
    }]
});

Adding the class on the <th> :

<table>
    <thead>
        <tr>
            <th>Foo</th>
            <th>Bar</th>
            <th class="nosort">Baz</th>
        </tr>
    </thead>
    <tbody>...</tbody>
</table>

Documentation about columns

JSBin

Get first day of week in SQL Server

For the basic (the current week's Sunday)

select cast(dateadd(day,-(datepart(dw,getdate())-1),getdate()) as date)

If previous week:

select cast(dateadd(day,-(datepart(dw,getdate())-1),getdate()) -7 as date)

Internally, we built a function that does it but if you need quick and dirty, this will do it.

How to put a jpg or png image into a button in HTML

<a href="#">
        <img src="p.png"></img>
    </a>

SQL Case Expression Syntax?

Case statement syntax in SQL SERVER:

CASE column
   WHEN value1 THEN 1
   WHEN value3 THEN 2
   WHEN value3 THEN 3
   WHEN value1 THEN 4
   ELSE ''
END

And we can use like below also:

CASE 
   WHEN column=value1 THEN 1
   WHEN column=value3 THEN 2
   WHEN column=value3 THEN 3
   WHEN column=value1 THEN 4
   ELSE ''
END

Float a div above page content

Yes, the higher the z-index, the better. It will position your content element on top of every other element on the page. Say you have z-index to some elements on your page. Look for the highest and then give a higher z-index to your popup element. This way it will flow even over the other elements with z-index. If you don't have a z-index in any element on your page, you should give like z-index:2; or something higher.

Changing cursor to waiting in javascript/jquery

The following is my preferred way, and will change the cursor everytime a page is about to change i.e. beforeunload

$(window).on('beforeunload', function(){
   $('*').css("cursor", "progress");
});

how get yesterday and tomorrow datetime in c#

Beware of adding an unwanted timezone to your results, especially if the date is going to be sent out via a Web API. Use UtcNow instead, to make it timezone-less.

Rendering JSON in controller

You'll normally be returning JSON either because:

A) You are building part / all of your application as a Single Page Application (SPA) and you need your client-side JavaScript to be able to pull in additional data without fully reloading the page.

or

B) You are building an API that third parties will be consuming and you have decided to use JSON to serialize your data.

Or, possibly, you are eating your own dogfood and doing both

In both cases render :json => some_data will JSON-ify the provided data. The :callback key in the second example needs a bit more explaining (see below), but it is another variation on the same idea (returning data in a way that JavaScript can easily handle.)

Why :callback?

JSONP (the second example) is a way of getting around the Same Origin Policy that is part of every browser's built-in security. If you have your API at api.yoursite.com and you will be serving your application off of services.yoursite.com your JavaScript will not (by default) be able to make XMLHttpRequest (XHR - aka ajax) requests from services to api. The way people have been sneaking around that limitation (before the Cross-Origin Resource Sharing spec was finalized) is by sending the JSON data over from the server as if it was JavaScript instead of JSON). Thus, rather than sending back:

{"name": "John", "age": 45}

the server instead would send back:

valueOfCallbackHere({"name": "John", "age": 45})

Thus, a client-side JS application could create a script tag pointing at api.yoursite.com/your/endpoint?name=John and have the valueOfCallbackHere function (which would have to be defined in the client-side JS) called with the data from this other origin.)

How can I get the concatenation of two lists in Python without modifying either one?

You can also use sum, if you give it a start argument:

>>> list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
>>> all_lists = sum([list1, list2, list3], [])
>>> all_lists
[1, 2, 3, 'a', 'b', 'c', 7, 8, 9]

This works in general for anything that has the + operator:

>>> sum([(1,2), (1,), ()], ())
(1, 2, 1)

>>> sum([Counter('123'), Counter('234'), Counter('345')], Counter())
Counter({'1':1, '2':2, '3':3, '4':2, '5':1})

>>> sum([True, True, False], False)
2

With the notable exception of strings:

>>> sum(['123', '345', '567'], '')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sum() can't sum strings [use ''.join(seq) instead]

How to bind 'touchstart' and 'click' events but not respond to both?

Just for documentation purposes, here's what I've done for the fastest/most responsive click on desktop/tap on mobile solution that I could think of:

I replaced jQuery's on function with a modified one that, whenever the browser supports touch events, replaced all my click events with touchstart.

$.fn.extend({ _on: (function(){ return $.fn.on; })() });
$.fn.extend({
    on: (function(){
        var isTouchSupported = 'ontouchstart' in window || window.DocumentTouch && document instanceof DocumentTouch;
        return function( types, selector, data, fn, one ) {
            if (typeof types == 'string' && isTouchSupported && !(types.match(/touch/gi))) types = types.replace(/click/gi, 'touchstart');
            return this._on( types, selector, data, fn);
        };
    }()),
});

Usage than would be the exact same as before, like:

$('#my-button').on('click', function(){ /* ... */ });

But it would use touchstart when available, click when not. No delays of any kind needed :D

What does 'git remote add upstream' help achieve?

Let's take an example: You want to contribute to django, so you fork its repository. In the while you work on your feature, there is much work done on the original repo by other people. So the code you forked is not the most up to date. setting a remote upstream and fetching it time to time makes sure your forked repo is in sync with the original repo.

Calling a java method from c++ in Android

Solution posted by Denys S. in the question post:

I quite messed it up with c to c++ conversion (basically env variable stuff), but I got it working with the following code for C++:

#include <string.h>
#include <stdio.h>
#include <jni.h>

jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
    jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

And next code for java methods:

    public class MainActivity extends Activity {
    private static String LIB_NAME = "thelib";

    static {
        System.loadLibrary(LIB_NAME);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(this.getJniString());
    }

    // please, let me live even though I used this dark programming technique
    public String messageMe(String text) {
        System.out.println(text);
        return text;
    }

    public native String getJniString();
}

How to connect to mysql with laravel?

Laravel makes it very easy to manage your database connections through app/config/database.php.

As you noted, it is looking for a database called 'database'. The reason being that this is the default name in the database configuration file.

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'database', <------ Default name for database
    'username'  => 'root',
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

Change this to the name of the database that you would like to connect to like this:

'mysql' => array(
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'my_awesome_data', <------ change name for database
    'username'  => 'root',            <------ remember credentials
    'password'  => '',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
),

Once you have this configured correctly you will easily be able to access your database!

Happy Coding!

How to use Select2 with JSON via Ajax request?

for select2 v4.0.0 slightly different

$(".itemSearch").select2({
    tags: true,
    multiple: true,
    tokenSeparators: [',', ' '],
    minimumInputLength: 2,
    minimumResultsForSearch: 10,
    ajax: {
        url: URL,
        dataType: "json",
        type: "GET",
        data: function (params) {

            var queryParameters = {
                term: params.term
            }
            return queryParameters;
        },
        processResults: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.tag_value,
                        id: item.tag_id
                    }
                })
            };
        }
    }
});

ReactJS - .JS vs .JSX

There is none when it comes to file extensions. Your bundler/transpiler/whatever takes care of resolving what type of file contents there is.

There are however some other considerations when deciding what to put into a .js or a .jsx file type. Since JSX isn't standard JavaScript one could argue that anything that is not "plain" JavaScript should go into its own extensions ie., .jsx for JSX and .ts for TypeScript for example.

There's a good discussion here available for read

What browsers support HTML5 WebSocket API?

Client side

  • Hixie-75:
    • Chrome 4.0 + 5.0
    • Safari 5.0.0
  • HyBi-00/Hixie-76:
  • HyBi-07+:
  • HyBi-10:
    • Chrome 14.0 + 15.0
    • Firefox 7.0 + 8.0 + 9.0 + 10.0 - prefixed: MozWebSocket
    • IE 10 (from Windows 8 developer preview)
  • HyBi-17/RFC 6455
    • Chrome 16
    • Firefox 11
    • Opera 12.10 / Opera Mobile 12.1

Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.

See caniuse for the current status of WebSockets support in desktop and mobile browsers.

See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.


Server side

It depends on which language you use.

In Java/Java EE:

Some other Java implementations:

In C#:

In PHP:

In Python:

In C:

In Node.js:

  • Socket.io : Socket.io also has serverside ports for Python, Java, Google GO, Rack
  • sockjs : sockjs also has serverside ports for Python, Java, Erlang and Lua
  • WebSocket-Node - Pure JavaScript Client & Server implementation of HyBi-10.

Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :

  • Support for Ruby(JRuby), Java, Groovy, Javascript(Rhino/Nashorn), Scala, ...
  • True threading. (unlike Node.js)
  • Understands multiple network protocols out of the box including: TCP, SSL, UDP, HTTP, HTTPS, Websockets, SockJS as fallback for WebSockets

Pusher.com is a Websocket cloud service accessible through a REST API.

DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.

Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.

For other language implementations, see the Wikipedia article for more information.

The RFC for Websockets : RFC6455

How do I specify unique constraint for multiple columns in MySQL?

You can add multiple-column unique indexes via phpMyAdmin. (I tested in version 4.0.4)

Navigate to the structure page for your target table. Add a unique index to one of the columns. Expand the Indexes list on the bottom of the structure page to see the unique index you just added. Click the edit icon, and in the following dialog you can add additional columns to that unique index.

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

The problem arose because you added the following code as request header in your front-end :

headers.append('Access-Control-Allow-Origin', 'http://localhost:3000');
headers.append('Access-Control-Allow-Credentials', 'true');

Those headers belong to response, not request. So remove them, including the line :

headers.append('GET', 'POST', 'OPTIONS');

Your request had 'Content-Type: application/json', hence triggered what is called CORS preflight. This caused the browser sent the request with OPTIONS method. See CORS preflight for detailed information.

Therefore in your back-end, you have to handle this preflighted request by returning the response headers which include :

Access-Control-Allow-Origin : http://localhost:3000
Access-Control-Allow-Credentials : true
Access-Control-Allow-Methods : GET, POST, OPTIONS
Access-Control-Allow-Headers : Origin, Content-Type, Accept

Of course, the actual syntax depends on the programming language you use for your back-end.

In your front-end, it should be like so :

function performSignIn() {
    let headers = new Headers();

    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');
    headers.append('Authorization', 'Basic ' + base64.encode(username + ":" +  password));
    headers.append('Origin','http://localhost:3000');

    fetch(sign_in, {
        mode: 'cors',
        credentials: 'include',
        method: 'POST',
        headers: headers
    })
    .then(response => response.json())
    .then(json => console.log(json))
    .catch(error => console.log('Authorization failed : ' + error.message));
}

How to get current PHP page name

You can use basename() and $_SERVER['PHP_SELF'] to get current page file name

echo basename($_SERVER['PHP_SELF']); /* Returns The Current PHP File Name */

What does a (+) sign mean in an Oracle SQL WHERE clause?

This is an Oracle-specific notation for an outer join. It means that it will include all rows from t1, and use NULLS in the t0 columns if there is no corresponding row in t0.

In standard SQL one would write:

SELECT t0.foo, t1.bar
  FROM FIRST_TABLE t0
 RIGHT OUTER JOIN SECOND_TABLE t1;

Oracle recommends not to use those joins anymore if your version supports ANSI joins (LEFT/RIGHT JOIN) :

Oracle recommends that you use the FROM clause OUTER JOIN syntax rather than the Oracle join operator. Outer join queries that use the Oracle join operator (+) are subject to the following rules and restrictions […]

string in namespace std does not name a type

You need to add:

#include <string>

In your header file.

Show MySQL host via SQL Command

I think you try to get the remote host of the conneting user...

You can get a String like 'myuser@localhost' from the command:

SELECT USER()

You can split this result on the '@' sign, to get the parts:

-- delivers the "remote_host" e.g. "localhost" 
SELECT SUBSTRING_INDEX(USER(), '@', -1) 

-- delivers the user-name e.g. "myuser"
SELECT SUBSTRING_INDEX(USER(), '@', 1)

if you are conneting via ip address you will get the ipadress instead of the hostname.

How to force Chrome's script debugger to reload javascript?

On Windows, Ctrl+Shift+r would force reload the script in chrome.

Convert a Map<String, String> to a POJO

Well, you can achieve that with Jackson, too. (and it seems to be more comfortable since you were considering using jackson).

Use ObjectMapper's convertValue method:

final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
final MyPojo pojo = mapper.convertValue(map, MyPojo.class);

No need to convert into JSON string or something else; direct conversion does much faster.

remote rejected master -> master (pre-receive hook declined)

You might also want to check for Heroku telling you there's a typo in your CSS file.

Read through the long boring messages in the terminal closely after you push. There may be something like this: Invalid CSS after. It means Heroku has found a typo and you need to fix it in the CSS file.

You can do a find for rake aborted! and directly after that it should say why the push failed.

How to store array or multiple values in one column

You have a couple of questions here, so I'll address them separately:

I need to store a number of selected items in one field in a database

My general rule is: don't. This is something which all but requires a second table (or third) with a foreign key. Sure, it may seem easier now, but what if the use case comes along where you need to actually query for those items individually? It also means that you have more options for lazy instantiation and you have a more consistent experience across multiple frameworks/languages. Further, you are less likely to have connection timeout issues (30,000 characters is a lot).

You mentioned that you were thinking about using ENUM. Are these values fixed? Do you know them ahead of time? If so this would be my structure:

Base table (what you have now):

| id primary_key sequence
| -- other columns here.

Items table:

| id primary_key sequence
| descript VARCHAR(30) UNIQUE

Map table:

| base_id  bigint
| items_id bigint

Map table would have foreign keys so base_id maps to Base table, and items_id would map to the items table.

And if you'd like an easy way to retrieve this from a DB, then create a view which does the joins. You can even create insert and update rules so that you're practically only dealing with one table.

What format should I use store the data?

If you have to do something like this, why not just use a character delineated string? It will take less processing power than a CSV, XML, or JSON, and it will be shorter.

What column type should I use store the data?

Personally, I would use TEXT. It does not sound like you'd gain much by making this a BLOB, and TEXT, in my experience, is easier to read if you're using some form of IDE.

Tuple unpacking in for loops

The enumerate function returns a generator object which, at each iteration, yields a tuple containing the index of the element (i), numbered starting from 0 by default, coupled with the element itself (a), and the for loop conveniently allows you to access both fields of those generated tuples and assign variable names to them.

How to disable an input type=text?

You can get the DOM element and set disabled attribute to true/false.

If you use vue framework,here is a very easy demo.

_x000D_
_x000D_
  let vm = new Vue({
        el: "#app",
        data() {
            return { flag: true }
        },
        computed: {
            btnText() {
                return this.flag ? "Enable" : "Disable";
            }
        }
    })
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
    <input type="text" value="something" :disabled="flag" />
    <input type="button" :value="btnText" @click="flag=!flag">
</div>
_x000D_
_x000D_
_x000D_

Close Form Button Event

Try this:

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
    // You may decide to prompt to user else just kill.
    Process.GetCurrentProcess().Goose();
} 

How can I run NUnit tests in Visual Studio 2017?

This one helped me:

Getting started with .NET unit testing using NUnit

Basically:

  • Add the NUnit 3 library in NuGet.
  • Create the class you want to test.
  • Create a separate testing class. This should have [TestFixture] above it.
  • Create a function in the testing class. This should have [Test] above it.
  • Then go into TEST/WINDOW/TEST EXPLORER (across the top).
  • Click run to the left-hand side. It will tell you what has passed and what has failed.

My example code is here:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NUnit.Framework;

namespace NUnitTesting
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }

    public class Maths
    {
        public int Add(int a, int b)
        {
            int x = a + b;
            return x;
        }
    }

    [TestFixture]
    public class TestLogging
    {
        [Test]
        public void Add()
        {
            Maths add = new Maths();
            int expectedResult = add.Add(1, 2);
            Assert.That(expectedResult, Is.EqualTo(3));
        }
    }
}

This will return true, and if you change the parameter in Is.EqualTo it will fail, etc.

Search and get a line in Python

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

if "token" in mystring:
    print(mystring)

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

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

Recover sa password

The best way is to simply reset the password by connecting with a domain/local admin (so you may need help from your system administrators), but this only works if SQL Server was set up to allow local admins (these are now left off the default admin group during setup).

If you can't use this or other existing methods to recover / reset the SA password, some of which are explained here:

Then you could always backup your important databases, uninstall SQL Server, and install a fresh instance.

You can also search for less scrupulous ways to do it (e.g. there are password crackers that I am not enthusiastic about sharing).

As an aside, the login properties for sa would never say Windows Authentication. This is by design as this is a SQL Authentication account. This does not mean that Windows Authentication is disabled at the instance level (in fact it is not possible to do so), it just doesn't apply for a SQL auth account.

I wrote a tip on using PSExec to connect to an instance using the NT AUTHORITY\SYSTEM account (which works < SQL Server 2012), and a follow-up that shows how to hack the SqlWriter service (which can work on more modern versions):

And some other resources:

percentage of two int?

Well to make the decimal into a percent you can do this,

float percentage = (correct * 100.0f) / questionNum;

How to get length of a list of lists in python

if the name of your list is listlen then just type len(listlen). This will return the size of your list in the python.

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

This issue is not happening in Firefox and Safari. Make sure you are using the latest version of xml2json.js. Because i faced the XML parser error in IE. In Chrome best way you should open it in server like Apache or XAMPP.

HTML 5 Video "autoplay" not automatically starting in CHROME

Extremeandy has mentioned as of Chrome 66 autoplay video has been disabled.

After looking into this I found that muted videos are still able to be autoplayed. In my case the video didn't have any audio, but adding muted to the video tag has fixed it:

Hopefully this will help others also.

docker unauthorized: authentication required - upon push with successful login

If you are pushing a new private image for the first time, make sure your subscription supports this extra image.

Docker allows you to have 6 private images named, even if you only pay for 5, but not to push that 6th image. The lack of an informative message is confusing and irritating.

What does \d+ mean in regular expression terms?

\d is called a character class and will match digits. It is equal to [0-9].

+ matches 1 or more occurrences of the character before.

So \d+ means match 1 or more digits.

Splitting a C++ std::string using tokens, e.g. ";"

You could use a string stream and read the elements into the vector.

Here are many different examples...

A copy of one of the examples:

std::vector<std::string> split(const std::string& s, char seperator)
{
   std::vector<std::string> output;

    std::string::size_type prev_pos = 0, pos = 0;

    while((pos = s.find(seperator, pos)) != std::string::npos)
    {
        std::string substring( s.substr(prev_pos, pos-prev_pos) );

        output.push_back(substring);

        prev_pos = ++pos;
    }

    output.push_back(s.substr(prev_pos, pos-prev_pos)); // Last word

    return output;
}

How to build & install GLFW 3 and use it in a Linux project

Since the accepted answer does not allow more edits, I'm going to summarize it with a single copy-paste command (Replace 3.2.1 with the latest version available in the first line):

version="3.2.1" && \
wget "https://github.com/glfw/glfw/releases/download/${version}/glfw-${version}.zip" && \
unzip glfw-${version}.zip && \
cd glfw-${version} && \
sudo apt-get install cmake xorg-dev libglu1-mesa-dev && \
sudo cmake -G "Unix Makefiles" && \
sudo make && \
sudo make install

If you want to compile a program use the following commands:

g++ -std=c++11 -c main.cpp && \
g++ main.o -o main.exec -lGL -lGLU -lglfw3 -lX11 -lXxf86vm -lXrandr -lpthread -lXi -ldl -lXinerama -lXcursor

If you are following the learnopengl.com tutorial you may have to set up GLAD as well. In such case click on this link

http://glad.dav1d.de/#profile=core&specification=gl&api=gl%3D3.3&api=gles1%3Dnone&api=gles2%3Dnone&api=glsc2%3Dnone&language=c&loader=on

and then click on the "Generate" button at the bottom right corner of the website and download the zip file. Extract it and compile the sources with the following command:

g++ glad/src/glad.c -c -Iglad/include

Now, the commands to compile your program become like this:

g++ -std=c++11 -c main.cpp -Iglad/include && \
g++ main.o glad.o -o main.exec -lGL -lGLU -lglfw3 -lX11 -lXxf86vm -lXrandr -lpthread -lXi -ldl -lXinerama -lXcursor

How to setup Main class in manifest file in jar produced by NetBeans project

Brother you don't need to set class path just follow these simple steps (I use Apache NetBeans)

Steps:

  1. extract the jar file which you want to add in your project.

  2. only copy those packages (folder) which you need in the project. (do not copy manifest file)

  3. open the main project jar file(dist/file.jar) with WinRAR.

  4. paste that folder or package in the main project jar file.

  5. Those packages work 100% in your project.

warning: Do not make any changes in the manifest file.

Another method:

  • In my case lib folder present outside the dist(main jar file) folder.
  • we need to move lib folder in dist folder.then we set class path from manifest.mf file of main jar file.

    Edit the manifest.mf And ADD this type of line

  • Class-Path: lib\foldername\jarfilename.jar lib\foldername\jarfilename.jar

Warning: lib folder must be inside the dist folder otherwise jar file do not access your lib folder jar files

Serialize form data to JSON

I know this doesn't meet the helper function requirement, but the way I've done this is using jQuery's $.each() method

var loginForm = $('.login').serializeArray();
var loginFormObject = {};
$.each(loginForm,
    function(i, v) {
        loginFormObject[v.name] = v.value;
    });

Then I can pass loginFormObject to my backend, or you could create a userobject and save() it in backbone as well.

How to schedule a function to run every hour on Flask?

I'm a little bit new with the concept of application schedulers, but what I found here for APScheduler v3.3.1 , it's something a little bit different. I believe that for the newest versions, the package structure, class names, etc., have changed, so I'm putting here a fresh solution which I made recently, integrated with a basic Flask application:

#!/usr/bin/python3
""" Demonstrating Flask, using APScheduler. """

from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask

def sensor():
    """ Function for test purposes. """
    print("Scheduler is alive!")

sched = BackgroundScheduler(daemon=True)
sched.add_job(sensor,'interval',minutes=60)
sched.start()

app = Flask(__name__)

@app.route("/home")
def home():
    """ Function for test purposes. """
    return "Welcome Home :) !"

if __name__ == "__main__":
    app.run()

I'm also leaving this Gist here, if anyone have interest on updates for this example.

Here are some references, for future readings:

List files ONLY in the current directory

instead of os.walk, just use os.listdir

Find a string within a cell using VBA

I simplified your code to isolate the test for "%" being in the cell. Once you get that to work, you can add in the rest of your code.

Try this:

Option Explicit


Sub DoIHavePercentSymbol()
   Dim rng As Range

   Set rng = ActiveCell

   Do While rng.Value <> Empty
        If InStr(rng.Value, "%") = 0 Then
            MsgBox "I know nothing about percentages!"
            Set rng = rng.Offset(1)
            rng.Select
        Else
            MsgBox "I contain a % symbol!"
            Set rng = rng.Offset(1)
            rng.Select
        End If
   Loop

End Sub

InStr will return the number of times your search text appears in the string. I changed your if test to check for no matches first.

The message boxes and the .Selects are there simply for you to see what is happening while you are stepping through the code. Take them out once you get it working.

Get key by value in dictionary

Here is a solution which works both in Python 2 and Python 3:

dict((v, k) for k, v in list.items())[search_age]

The part until [search_age] constructs the reverse dictionary (where values are keys and vice-versa). You could create a helper method which will cache this reversed dictionary like so:

def find_name(age, _rev_lookup=dict((v, k) for k, v in ages_by_name.items())):
    return _rev_lookup[age]

or even more generally a factory which would create a by-age name lookup method for one or more of you lists

def create_name_finder(ages_by_name):
    names_by_age = dict((v, k) for k, v in ages_by_name.items())
    def find_name(age):
      return names_by_age[age]

so you would be able to do:

find_teen_by_age = create_name_finder({'george':16,'amber':19})
...
find_teen_by_age(search_age)

Note that I renamed list to ages_by_name since the former is a predefined type.

How do I make a simple crawler in PHP?

Thank you @hobodave.

However I found two weaknesses in your code. Your parsing of the original url to get the "host" segment stops at the first single slash. This presumes that all relative links start in the root directory. This only true sometimes.

original url   :  http://example.com/game/index.html
href in <a> tag:  highscore.html
author's intent:  http://example.com/game/highscore.html  <-200->
crawler result :  http://example.com/highscore.html       <-404->

fix this by breaking at the last single slash not the first

a second unrelated bug, is that $depth does not really track recursion depth, it tracks breadth of the first level of recursion.

If I believed this page were in active use I might debug this second issue, but I suspect the text I am writing now will never be read by anyone, human or robot, since this issue is six years old and I do not even have enough reputation to notify +hobodave directly about these defects by commmenting on his code. Thanks anyway hobodave.

How to send a stacktrace to log4j?

You pass the exception directly to the logger, e.g.

try {
   ...
} catch (Exception e) {
    log.error( "failed!", e );
}

It's up to log4j to render the stack trace.

Auto select file in Solution Explorer from its open tab

It's in VS2012 - Specifically the 2-Arrow icon at the top of the solution explorer (Left/Right arrows, one above the other). This automatically jumps to the current file.

This icon is only visible if you've got Track Active Item in Solution Explorer disabled.

How to increase the vertical split window size in Vim

I am using numbers to resize by mapping the following in .vimrc

nmap 7 :res +2<CR> " increase pane by 2 
nmap 8 :res -2<CR> " decrease pane by 2
nmap 9 :vertical res +2<CR> " vertical increase pane by 2
nmap 0 :vertical res -2<CR> " vertical decrease pane by 2

HTTP Error 503. The service is unavailable. App pool stops on accessing website

For my situation is that my login password changed, while the application pool still uses the old one. So just click the "Advanced Settings" of your application pool and reset your "Identity".

Make Frequency Histogram for Factor Variables

Country is a categorical variable and I want to see how many occurences of country exist in the data set. In other words, how many records/attendees are from each Country

barplot(summary(df$Country))

How do I get the current username in .NET using C#?

I went over most of the answers here and none of them gave me the right user name.

In my case I wanted to get the logged in user name, while running my app from a different user, like when shift+right click on a file and "Run as a different user".

The answers I tried gave me the 'other' username.

This blog post supplies a way to get the logged in user name, which works even in my scenario:
https://smbadiwe.github.io/post/track-activities-windows-service/

It uses Wtsapi

Should I set max pool size in database connection string? What happens if I don't?

Currently your application support 100 connections in pool. Here is what conn string will look like if you want to increase it to 200:

public static string srConnectionString = 
                "server=localhost;database=mydb;uid=sa;pwd=mypw;Max Pool Size=200;";

You can investigate how many connections with database your application use, by executing sp_who procedure in your database. In most cases default connection pool size will be enough.

Could not open input file: composer.phar

The composer.phar install is not working but without .phar this is working.

We need to enable the openssl module in php before installing the zendframe work.

We have to uncomment the line ;extension=php_openssl.dll from php.ini file.

composer use different php.ini file which is located at the wamp\bin\php\php-<version number>\php.ini

After enabling the openssl we need to restart the server.

The execute the following comments.

I can install successfully using these commands -

composer self-update
composer install --prefer-dist

enter image description here

Extension gd is missing from your system - laravel composer Update

Before installing the missing dependency, you need to check which version of PHP is installed on your system.

php -v
PHP 7.2.10-0ubuntu0.18.04.1 (cli) (built: Sep 13 2018 13:45:02) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.2.10-0ubuntu0.18.04.1, Copyright (c) 1999-2018, by Zend Technologies

In this case it's php7.2. apt search php7.2 returns all the available PHP extensions.

apt search php7.2
Sorting... Done
Full Text Search... Done
libapache2-mod-php7.2/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  server-side, HTML-embedded scripting language (Apache 2 module)

libphp7.2-embed/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  HTML-embedded scripting language (Embedded SAPI library)

php-all-dev/bionic,bionic 1:60ubuntu1 all
  package depending on all supported PHP development packages

php7.2/bionic-updates,bionic-updates,bionic-security,bionic-security 7.2.10-0ubuntu0.18.04.1 all
  server-side, HTML-embedded scripting language (metapackage)

php7.2-bcmath/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Bcmath module for PHP

php7.2-bz2/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  bzip2 module for PHP

php7.2-cgi/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  server-side, HTML-embedded scripting language (CGI binary)

php7.2-cli/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  command-line interpreter for the PHP scripting language

php7.2-common/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  documentation, examples and common module for PHP

php7.2-curl/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed]
  CURL module for PHP

php7.2-dba/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  DBA module for PHP

php7.2-dev/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Files for PHP7.2 module development

php7.2-enchant/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Enchant module for PHP

php7.2-fpm/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed]
  server-side, HTML-embedded scripting language (FPM-CGI binary)

php7.2-gd/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed]
  GD module for PHP

php7.2-gmp/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  GMP module for PHP

php7.2-imap/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  IMAP module for PHP

php7.2-interbase/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Interbase module for PHP

php7.2-intl/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Internationalisation module for PHP

php7.2-json/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  JSON module for PHP

php7.2-ldap/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  LDAP module for PHP

php7.2-mbstring/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  MBSTRING module for PHP

php7.2-mysql/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  MySQL module for PHP

php7.2-odbc/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  ODBC module for PHP

php7.2-opcache/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  Zend OpCache module for PHP

php7.2-pgsql/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  PostgreSQL module for PHP

php7.2-phpdbg/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  server-side, HTML-embedded scripting language (PHPDBG binary)

php7.2-pspell/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  pspell module for PHP

php7.2-readline/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed,automatic]
  readline module for PHP

php7.2-recode/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  recode module for PHP

php7.2-snmp/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  SNMP module for PHP

php7.2-soap/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  SOAP module for PHP

php7.2-sqlite3/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed]
  SQLite3 module for PHP

php7.2-sybase/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Sybase module for PHP

php7.2-tidy/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  tidy module for PHP

php7.2-xml/bionic-updates,bionic-security,now 7.2.10-0ubuntu0.18.04.1 amd64 [installed]
  DOM, SimpleXML, WDDX, XML, and XSL module for PHP

php7.2-xmlrpc/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  XMLRPC-EPI module for PHP

php7.2-xsl/bionic-updates,bionic-updates,bionic-security,bionic-security 7.2.10-0ubuntu0.18.04.1 all
  XSL module for PHP (dummy)

php7.2-zip/bionic-updates,bionic-security 7.2.10-0ubuntu0.18.04.1 amd64
  Zip module for PHP

You can now proceed to installing the missing dependency by running:

sudo apt install php7.2-gd

psql: FATAL: database "<user>" does not exist

Had this problem when installing postgresql via homebrew.

Had to create the default "postgres" super user with:

createuser --interactive postgres answer y to for super user

createuser --interactive user answer y to for super user

Git vs Team Foundation Server

On top of everything that's been said (

https://stackoverflow.com/a/4416666/172109

https://stackoverflow.com/a/4894099/172109

https://stackoverflow.com/a/4415234/172109

), which is correct, TFS isn't just a VCS. One major feature that TFS provides is natively integrated bug tracking functionality. Changesets are linked to issues and could be tracked. Various policies for check-ins are supported, as well as integration with Windows domain, which is what people who run TFS have. Tightly integrated GUI with Visual Studio is another selling point, which appeals to less than average mouse and click developer and his manager.

Hence comparing Git to TFS isn't a proper question to ask. Correct, though impractical, question is to compare Git with just VCS functionality of TFS. At that, Git blows TFS out of the water. However, any serious team needs other tools and this is where TFS provides one stop destination.

What is the equivalent to getLastInsertId() in Cakephp?

$Machinedispatch = 
   $this->Machinedispatch->find('first',array('order'=>array('Machinedispatch.id DESC')));

Simplest way of finding last inserted row. For me getLastInsertId() this not works.

How can I get the SQL of a PreparedStatement?

Code Snippet to convert SQL PreparedStaments with the list of arguments. It works for me

  /**
         * 
         * formatQuery Utility function which will convert SQL
         * 
         * @param sql
         * @param arguments
         * @return
         */
        public static String formatQuery(final String sql, Object... arguments) {
            if (arguments != null && arguments.length <= 0) {
                return sql;
            }
            String query = sql;
            int count = 0;
            while (query.matches("(.*)\\?(.*)")) {
                query = query.replaceFirst("\\?", "{" + count + "}");
                count++;
            }
            String formatedString = java.text.MessageFormat.format(query, arguments);
            return formatedString;
        }

Override hosts variable of Ansible playbook from the command line

If you want to run a task that's associated with a host, but on different host, you should try delegate_to.

In your case, you should delegate to your localhost (ansible master) and calling ansible-playbook command

How to URL encode in Python 3?

You misread the documentation. You need to do two things:

  1. Quote each key and value from your dictionary, and
  2. Encode those into a URL

Luckily urllib.parse.urlencode does both those things in a single step, and that's the function you should be using.

from urllib.parse import urlencode, quote_plus

payload = {'username':'administrator', 'password':'xyz'}
result = urlencode(payload, quote_via=quote_plus)
# 'password=xyz&username=administrator'

Why am I getting error CS0246: The type or namespace name could not be found?

I have resolved this problem by adding the reference to System.Web.

Easiest way to rotate by 90 degrees an image using OpenCV?

Here's my EmguCV (a C# port of OpenCV) solution:

public static Image<TColor, TDepth> Rotate90<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    var rot = new Image<TColor, TDepth>(img.Height, img.Width);
    CvInvoke.cvTranspose(img.Ptr, rot.Ptr);
    rot._Flip(FLIP.HORIZONTAL);
    return rot;
}

public static Image<TColor, TDepth> Rotate180<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    var rot = img.CopyBlank();
    rot = img.Flip(FLIP.VERTICAL);
    rot._Flip(FLIP.HORIZONTAL);
    return rot;
}

public static void _Rotate180<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    img._Flip(FLIP.VERTICAL);
    img._Flip(FLIP.HORIZONTAL);
}

public static Image<TColor, TDepth> Rotate270<TColor, TDepth>(this Image<TColor, TDepth> img)
    where TColor : struct, IColor
    where TDepth : new()
{
    var rot = new Image<TColor, TDepth>(img.Height, img.Width);
    CvInvoke.cvTranspose(img.Ptr, rot.Ptr);
    rot._Flip(FLIP.VERTICAL);
    return rot;
}

Shouldn't be too hard to translate it back into C++.

Phone Number Validation MVC

Try for simple regular expression for Mobile No

[Required (ErrorMessage="Required")]
[RegularExpression(@"^(\d{10})$", ErrorMessage = "Wrong mobile")]
public string Mobile { get; set; }

AJAX jQuery refresh div every 5 seconds

<script type="text/javascript">
$(document).ready(function(){
  refreshTable();
});

function refreshTable(){
    $('#tableHolder').load('getTable.php', function(){
       setTimeout(refreshTable, 5000);
    });
}
</script>

How do I concatenate strings with variables in PowerShell?

You could use the PowerShell equivalent of String.Format - it's usually the easiest way to build up a string. Place {0}, {1}, etc. where you want the variables in the string, put a -f immediately after the string and then the list of variables separated by commas.

Get-ChildItem c:\code|%{'{0}\{1}\{2}.dll' -f $_.fullname,$buildconfig,$_.name}

(I've also taken the dash out of the $buildconfig variable name as I have seen that causes issues before too.)

C++ convert hex string to signed integer

use std::stringstream

unsigned int x;   
std::stringstream ss;
ss << std::hex << "fffefffe";
ss >> x;

the following example produces -65538 as its result:

#include <sstream>
#include <iostream>

int main() {
    unsigned int x;   
    std::stringstream ss;
    ss << std::hex << "fffefffe";
    ss >> x;
    // output it as a signed type
    std::cout << static_cast<int>(x) << std::endl;
}

In the new C++11 standard, there are a few new utility functions which you can make use of! specifically, there is a family of "string to number" functions (http://en.cppreference.com/w/cpp/string/basic_string/stol and http://en.cppreference.com/w/cpp/string/basic_string/stoul). These are essentially thin wrappers around C's string to number conversion functions, but know how to deal with a std::string

So, the simplest answer for newer code would probably look like this:

std::string s = "0xfffefffe";
unsigned int x = std::stoul(s, nullptr, 16);

NOTE: Below is my original answer, which as the edit says is not a complete answer. For a functional solution, stick the code above the line :-).

It appears that since lexical_cast<> is defined to have stream conversion semantics. Sadly, streams don't understand the "0x" notation. So both the boost::lexical_cast and my hand rolled one don't deal well with hex strings. The above solution which manually sets the input stream to hex will handle it just fine.

Boost has some stuff to do this as well, which has some nice error checking capabilities as well. You can use it like this:

try {
    unsigned int x = lexical_cast<int>("0x0badc0de");
} catch(bad_lexical_cast &) {
    // whatever you want to do...
}

If you don't feel like using boost, here's a light version of lexical cast which does no error checking:

template<typename T2, typename T1>
inline T2 lexical_cast(const T1 &in) {
    T2 out;
    std::stringstream ss;
    ss << in;
    ss >> out;
    return out;
}

which you can use like this:

// though this needs the 0x prefix so it knows it is hex
unsigned int x = lexical_cast<unsigned int>("0xdeadbeef"); 

HTML image bottom alignment inside DIV container

Flexboxes can accomplish this by using align-items: flex-end; with display: flex; or display: inline-flex;

div#imageContainer {
    height: 160px;  
    align-items: flex-end;
    display: flex;

    /* This is the default value, so you only need to explicitly set it if it's already being set to something else elsewhere. */
    /*flex-direction: row;*/
}

JSFiddle example

CSS-Tricks has a good guide for flexboxes

document.getElementById().value doesn't set the value

According to my tests with Chrome:

If you set a number input to a Number, then it works fine.

If you set a number input to a String that contains nothing but a number, then it works fine.

If you set a number input to a String that contains a number and some whitespace, then it blanks the input.

You probably have a space or a new line after the data in the server response that you actually care about.

Use document.getElementById("points").value = parseInt(request.responseText, 10); instead.

How to loop backwards in python?

for x in reversed(whatever):
    do_something()

This works on basically everything that has a defined order, including xrange objects and lists.

How to convert integer to string in C?

That's because itoa isn't a standard function. Try snprintf instead.

char str[LEN];
snprintf(str, LEN, "%d", 42);

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

Python "expected an indented block"

in python .....intendation matters, e.g.:

if a==1:
    print("hey")

if a==2:
   print("bye")

print("all the best")

In this case "all the best" will be printed if either of the two conditions executes, but if it would have been like this

if a==2:
   print("bye")
   print("all the best")

then "all the best" will be printed only if a==2

Color picker utility (color pipette) in Ubuntu

I recommend GPick:

sudo apt-get install gpick

Applications -> Graphics -> GPick

It has many more features than gcolor2 but is still extremely simple to use: click on one of the hex swatches, move your mouse around the screen over the colours you want to pick, then press the Space bar to add to your swatch list.

If that doesn't work, another way is to click-and-drag from the centre of the hexagon and release your mouse over the pixel that you want to sample. Then immediately hit Space to copy that color into the next swatch in rotation.

It also has a traditional colour picker (like gcolor2) in the bottom right-hand corner of the window to allow you to pick individual colours with magnification.

How to debug Google Apps Script (aka where does Logger.log log to?)

I've gone through these posts and somehow ended up finding a simple answer, which I'm posting here for those how want short and sweet solutions:

  1. Use console.log("Hello World") in your script.
  2. Go to https://script.google.com/home/my and select your add-on.
  3. Click on the ellipsis menu on Project Details, select Executions.

enter image description here

  1. Click on the header of the latest execution and read the log.

enter image description here

How can I get a list of repositories 'apt-get' is checking?

All I needed was:

cd /etc/apt
nano source.list
deb http://http.kali.org/kali kali-rolling main non-free contrib
deb-src http://http.kali.org/kali kali-rolling main non-free contrib
apt upgrade && update

Source: Kali Network Repositories (/etc/apt/sources.list)

Better way to set distance between flexbox items

tl;dr

$gutter: 8px;

.container {
  display: flex;
  justify-content: space-between;

  .children {
    flex: 0 0 calc(33.3333% - $gutter);
  }
}

android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

Other possible solution:

tv.setText(Integer.toString(a1));  // where a1 - int value

What's the advantage of a Java enum versus a class with public static final fields?

Main reason: Enums help you to write well-structured code where the semantic meaning of parameters is clear and strongly-typed at compile time - for all the reasons other answers have given.

Quid pro quo: in Java out of the box, an Enum's array of members is final. That's normally good as it helps value safety and testing, but in some situations it could be a drawback, for example if you are extending existing base code perhaps from a library. In contrast, if the same data is in a class with static fields you can easily add new instances of that class at runtime (you might also need to write code to add these to any Iterable you have for that class). But this behaviour of Enums can be changed: using reflection you can add new members at runtime or replace existing members, though this should probably only be done in specialised situations where there is no alternative: i.e. it's a hacky solution and may produce unexpected issues, see my answer on Can I add and remove elements of enumeration at runtime in Java.

selecting rows with id from another table

You can use a subquery:

SELECT *
FROM terms
WHERE id IN (SELECT term_id FROM terms_relation WHERE taxonomy='categ');

and if you need to show all columns from both tables:

SELECT t.*, tr.*
FROM terms t, terms_relation tr
WHERE t.id = tr.term_id
AND tr.taxonomy='categ'

How do I serialize a Python dictionary into a string, and then back to a dictionary?

Pickle is great but I think it's worth mentioning literal_eval from the ast module for an even lighter weight solution if you're only serializing basic python types. It's basically a "safe" version of the notorious eval function that only allows evaluation of basic python types as opposed to any valid python code.

Example:

>>> d = {}
>>> d[0] = range(10)
>>> d['1'] = {}
>>> d['1'][0] = range(10)
>>> d['1'][1] = 'hello'
>>> data_string = str(d)
>>> print data_string
{0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], '1': {0: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 1: 'hello'}}

>>> from ast import literal_eval
>>> d == literal_eval(data_string)
True

One benefit is that the serialized data is just python code, so it's very human friendly. Compare it to what you would get with pickle.dumps:

>>> import pickle
>>> print pickle.dumps(d)
(dp0
I0
(lp1
I0
aI1
aI2
aI3
aI4
aI5
aI6
aI7
aI8
aI9
asS'1'
p2
(dp3
I0
(lp4
I0
aI1
aI2
aI3
aI4
aI5
aI6
aI7
aI8
aI9
asI1
S'hello'
p5
ss.

The downside is that as soon as the the data includes a type that is not supported by literal_ast you'll have to transition to something else like pickling.

setting system property

System.setProperty("gate.home", "/some/directory"); 

After that you can retrieve its value later by calling

String value =  System.getProperty("gate.home");

Abort a git cherry-pick?

Try also with '--quit' option, which allows you to abort the current operation and further clear the sequencer state.

--quit Forget about the current operation in progress. Can be used to clear the sequencer state after a failed cherry-pick or revert.

--abort Cancel the operation and return to the pre-sequence state.

use help to see the original doc with more details, $ git help cherry-pick

I would avoid 'git reset --hard HEAD' that is too harsh and you might ended up doing some manual work.

How to check a boolean condition in EL?

You can check this way too

<c:if test="${theBooleanVariable ne true}">It's false!</c:if>

jQuery add blank option to top of list and make selected to existing dropdown

This worked:

$("#theSelectId").prepend("<option value='' selected='selected'></option>");

Firebug Output:

<select id="theSelectId">
  <option selected="selected" value=""/>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

You could also use .prependTo if you wanted to reverse the order:

?$("<option>", { value: '', selected: true }).prependTo("#theSelectId");???????????

How to vertically center a "div" element for all browsers using CSS?

The following is working in my case and was tested in Firefox.

#element {
    display: block;
    transform: translateY(50%);
    -moz-transform: translateY(50%);
    -webkit-transform: translateY(50%);
    -ms-transform: translateY(50%);
}

The div's height and parent's height are dynamic. I use it when there are other elements on the same parent which is higher than the target element, where both are positioned horizontally inline.

How to get request URL in Spring Boot RestController

Add a parameter of type UriComponentsBuilder to your controller method. Spring will give you an instance that's preconfigured with the URI for the current request, and you can then customize it (such as by using MvcUriComponentsBuilder.relativeTo to point at a different controller using the same prefix).

Run PowerShell command from command prompt (no ps1 script)

Run it on a single command line like so:

powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile 
  -WindowStyle Hidden -Command "Get-AppLockerFileInformation -Directory <folderpath> 
  -Recurse -FileType <type>"

Circular (or cyclic) imports in Python

I solved the problem the following way, and it works well without any error. Consider two files a.py and b.py.

I added this to a.py and it worked.

if __name__ == "__main__":
        main ()

a.py:

import b
y = 2
def main():
    print ("a out")
    print (b.x)

if __name__ == "__main__":
    main ()

b.py:

import a
print ("b out")
x = 3 + a.y

The output I get is

>>> b out 
>>> a out 
>>> 5

PHP, How to get current date in certain format

date("Y-m-d H:i:s"); // This should do it.

Best practices for adding .gitignore file for Python projects?

One question is if you also want to use git for the deploment of your projects. If so you probably would like to exclude your local sqlite file from the repository, same probably applies to file uploads (mostly in your media folder). (I'm talking about django now, since your question is also tagged with django)

json.dumps vs flask.jsonify

consider

data={'fld':'hello'}

now

jsonify(data)

will yield {'fld':'hello'} and

json.dumps(data)

gives

"<html><body><p>{'fld':'hello'}</p></body></html>"

addEventListener in Internet Explorer

Here's something for those who like beautiful code.

function addEventListener(obj,evt,func){
    if ('addEventListener' in window){
        obj.addEventListener(evt,func, false);
    } else if ('attachEvent' in window){//IE
        obj.attachEvent('on'+evt,func);
    }
}

Shamelessly stolen from Iframe-Resizer.

Flask example with POST

Before actually answering your question:

Parameters in a URL (e.g. key=listOfUsers/user1) are GET parameters and you shouldn't be using them for POST requests. A quick explanation of the difference between GET and POST can be found here.

In your case, to make use of REST principles, you should probably have:

http://ip:5000/users
http://ip:5000/users/<user_id>

Then, on each URL, you can define the behaviour of different HTTP methods (GET, POST, PUT, DELETE). For example, on /users/<user_id>, you want the following:

GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id> 

So, in your example, you want do a POST to /users/user_1 with the POST data being "John". Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.

Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:

from flask import Flask
from flask import request

app = Flask(__name__)

@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
    if request.method == 'GET':
        """return the information for <user_id>"""
        .
        .
        .
    if request.method == 'POST':
        """modify/update the information for <user_id>"""
        # you can use <user_id>, which is a str but could
        # changed to be int or whatever you want, along
        # with your lxml knowledge to make the required
        # changes
        data = request.form # a multidict containing POST data
        .
        .
        .
    if request.method == 'DELETE':
        """delete user with ID <user_id>"""
        .
        .
        .
    else:
        # POST Error 405 Method Not Allowed
        .
        .
        .

There are a lot of other things to consider like the POST request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.

Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.

Failed to execute 'atob' on 'Window'

In my case, I was going nuts since there wasn't any issues with the string to be decoded, since I could successfully decode it on online tools. Until I found out that you first have to decodeURIComponent what you are decoding, like so:

atob(decodeURIComponent(dataToBeDecoded));

How do you specify a byte literal in Java?

If you're passing literals in code, what's stopping you from simply declaring it ahead of time?

byte b = 0; //Set to desired value.
f(b);

"R cannot be resolved to a variable"?

Sometimes you can accidentially add an import to "R", so if at the top of your code you see some weird import about that that you did not add yourself, delete the reference, and everything should go back to normal

Signed versus Unsigned Integers

Just a few points for completeness:

  • this answer is discussing only integer representations. There may be other answers for floating point;

  • the representation of a negative number can vary. The most common (by far - it's nearly universal today) in use today is two's complement. Other representations include one's complement (quite rare) and signed magnitude (vanishingly rare - probably only used on museum pieces) which is simply using the high bit as a sign indicator with the remain bits representing the absolute value of the number.

  • When using two's complement, the variable can represent a larger range (by one) of negative numbers than positive numbers. This is because zero is included in the 'positive' numbers (since the sign bit is not set for zero), but not the negative numbers. This means that the absolute value of the smallest negative number cannot be represented.

  • when using one's complement or signed magnitude you can have zero represented as either a positive or negative number (which is one of a couple of reasons these representations aren't typically used).

Why an inline "background-image" style doesn't work in Chrome 10 and Internet Explorer 8?

Chrome 11 spits out the following in its debugger:

[Error] GET http://www.mypicx.com/images/logo.jpg undefined (undefined)

It looks like that hosting service is using some funky dynamic system that is preventing these browsers from fetching it correctly. (Instead it tries to fetch the default base image, which is problematically a jpeg.) Could you just upload another copy of the image elsewhere? I would expect it to be the easiest solution by a long mile.

Edit: See what happens in Chrome when you place the image using normal <img> tags ;)

Array length in angularjs returns undefined

Make it like this:

$scope.users.data.length;

how to remove empty strings from list, then remove duplicate values from a list

Amiram Korach solution is indeed tidy. Here's an alternative for the sake of versatility.

var count = dtList.Count;
// Perform a reverse tracking.
for (var i = count - 1; i > -1; i--)
{
    if (dtList[i]==string.Empty) dtList.RemoveAt(i);
}
// Keep only the unique list items.
dtList = dtList.Distinct().ToList();

Volatile Vs Atomic

There are two important concepts in multithreading environment:

  1. atomicity
  2. visibility

The volatile keyword eradicates visibility problems, but it does not deal with atomicity. volatile will prevent the compiler from reordering instructions which involve a write and a subsequent read of a volatile variable; e.g. k++. Here, k++ is not a single machine instruction, but three:

  1. copy the value to a register;
  2. increment the value;
  3. place it back.

So, even if you declare a variable as volatile, this will not make this operation atomic; this means another thread can see a intermediate result which is a stale or unwanted value for the other thread.

On the other hand, AtomicInteger, AtomicReference are based on the Compare and swap instruction. CAS has three operands: a memory location V on which to operate, the expected old value A, and the new value B. CAS atomically updates V to the new value B, but only if the value in V matches the expected old value A; otherwise, it does nothing. In either case, it returns the value currently in V. The compareAndSet() methods of AtomicInteger and AtomicReference take advantage of this functionality, if it is supported by the underlying processor; if it is not, then the JVM implements it via spin lock.

How can I access a hover state in reactjs?

ReactJs defines the following synthetic events for mouse events:

onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit
onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave
onMouseMove onMouseOut onMouseOver onMouseUp

As you can see there is no hover event, because browsers do not define a hover event natively.

You will want to add handlers for onMouseEnter and onMouseLeave for hover behavior.

ReactJS Docs - Events

Attach the Java Source Code

Hold ctrl key and then click on class of which you want to see the inner working (for ex: String) then you will find there button "Attach Source". Click on it. Then click on External Folder. Then browse to your jdk location, per instance C:\Program Files\Java\jdk1.6.0. That's it.

enter image description here

"implements Runnable" vs "extends Thread" in Java

Actually, It is not wise to compare Runnable and Thread with each other.

This two have a dependency and relationship in multi-threading just like Wheel and Engine relationship of motor vehicle.

I would say, there is only one way for multi-threading with two steps. Let me make my point.

Runnable:
When implementing interface Runnable it means you are creating something which is run able in a different thread. Now creating something which can run inside a thread (runnable inside a thread), doesn't mean to creating a Thread.
So the class MyRunnable is nothing but a ordinary class with a void run method. And it's objects will be some ordinary objects with only a method run which will execute normally when called. (unless we pass the object in a thread).

Thread:
class Thread, I would say A very special class with the capability of starting a new Thread which actually enables multi-threading through its start() method.

Why not wise to compare?
Because we need both of them for multi-threading.

For Multi-threading we need two things:

  • Something that can run inside a Thread (Runnable).
  • Something That can start a new Thread (Thread).

So technically and theoretically both of them is necessary to start a thread, one will run and one will make it run (Like Wheel and Engine of motor vehicle).

That's why you can not start a thread with MyRunnable you need to pass it to a instance of Thread.

But it is possible to create and run a thread only using class Thread because Class Thread implements Runnable so we all know Thread also is a Runnable inside.

Finally Thread and Runnable are complement to each other for multithreading not competitor or replacement.

Android: remove left margin from actionbar's custom layout

<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
android:paddingLeft="0dp">

This should be good enough.

Automatically size JPanel inside JFrame

If the BorderLayout option provided by our friends doesnot work, try adding ComponentListerner to the JFrame and implement the componentResized(event) method. When the JFrame object will be resized, this method will be called. So if you write the the code to set the size of the JPanel in this method, you will achieve the intended result.

Ya, I know this 'solution' is not good but use it as a safety net. ;)

How would I access variables from one class to another?

Just create the variables in a class. And then inherit from that class to access its variables. But before accessing them, the parent class has to be called to initiate the variables.

class a:
    def func1(self):
        a.var1 = "Stack "

class b:
    def func2(self):
        b.var2 = "Overflow"

class c(a,b):
    def func3(self):
        c.var3 = a.var1 + b.var2
        print(c.var3)

a().func1()
b().func2()
c().func3()

How to compare two date values with jQuery

var startDt=document.getElementById("startDateId").value;
var endDt=document.getElementById("endDateId").value;

if( (new Date(startDt).getTime() > new Date(endDt).getTime()))
{
    ----------------------------------
}

What is the difference between const and readonly in C#?

The key difference is that Const is the C equivalent of #DEFINE. The number literally gets substituted a-la precompiler. Readonly is actually treated as a variable.

This distinction is especially relevant when you have Project A depending on a Public constant from Project B. Suppose the public constant changes. Now your choice of const/readonly will impact the behavior on project A:

Const: project A does not catch the new value (unless it is recompiled with the new const, of course) because it was compiled with the constants subtituted in.

ReadOnly: Project A will always ask project B for it's variable value, so it will pick up the new value of the public constant in B.

Honestly, I would recommend you use readonly for nearly everything except truly universal constants ( e.g. Pi, Inches_To_Centimeters). For anything that could possibly change, I say use readonly.

Hope this helps, Alan.

Exit a Script On Error

If you put set -e in a script, the script will terminate as soon as any command inside it fails (i.e. as soon as any command returns a nonzero status). This doesn't let you write your own message, but often the failing command's own messages are enough.

The advantage of this approach is that it's automatic: you don't run the risk of forgetting to deal with an error case.

Commands whose status is tested by a conditional (such as if, && or ||) do not terminate the script (otherwise the conditional would be pointless). An idiom for the occasional command whose failure doesn't matter is command-that-may-fail || true. You can also turn set -e off for a part of the script with set +e.

How to print bytes in hexadecimal using System.out.println?

for (int j=0; j<test.length; j++) {
   System.out.format("%02X ", test[j]);
}
System.out.println();

How do I position one image on top of another in HTML?

Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.

How would one write object-oriented code in C?

Object oriented C, can be done, I've seen that type of code in production in Korea, and it was the most horrible monster I'd seen in years (this was like last year(2007) that I saw the code). So yes it can be done, and yes people have done it before, and still do it even in this day and age. But I'd recommend C++ or Objective-C, both are languages born from C, with the purpose of providing object orientation with different paradigms.

How can I make the computer beep in C#?

You can also use the relatively unused:

    System.Media.SystemSounds.Beep.Play();
    System.Media.SystemSounds.Asterisk.Play();
    System.Media.SystemSounds.Exclamation.Play();
    System.Media.SystemSounds.Question.Play();
    System.Media.SystemSounds.Hand.Play();

Documentation for this sounds is available in http://msdn.microsoft.com/en-us/library/system.media.systemsounds(v=vs.110).aspx

java.lang.IllegalStateException: Error processing condition on org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration

In my case I had created a SB app from the SB Initializer and had included a fair number of deps in it to other things. I went in and commented out the refs to them in the build.gradle file and so was left with:

implementation 'org.springframework.boot:spring-boot-starter-hateoas'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.hsqldb:hsqldb'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'

as deps. Then my bare-bones SB app was able to build and get running successfully. As I go to try to do things that may need those commented-out libs I will add them back and see what breaks.

How do you subtract Dates in Java?

You can use the following approach:

SimpleDateFormat formater=new SimpleDateFormat("yyyy-MM-dd");

long d1=formater.parse("2001-1-1").getTime();
long d2=formater.parse("2001-1-2").getTime();

System.out.println(Math.abs((d1-d2)/(1000*60*60*24)));

Problems when trying to load a package in R due to rJava

I had a similar problem what worked for me was to set JAVA_HOME. I tired it first in R:

Sys.setenv(JAVA_HOME = "C:/Program Files/Java/jdk1.8.0_101/")

And when it actually worked I set it in

System Properties -> Advanced -> Environment Variables

by adding a new System variable. I then restarted R/RStudio and everything worked.

CSS @font-face not working in ie

Change as per below

@font-face {
    font-family: "Futura";
    src: url("../fonts/Futura_Medium_BT.eot"); /* IE */
    src: local("Futura"), url( "../fonts/Futura_Medium_BT.ttf" ) format("truetype"); /* non-IE */  
}

body nav {
     font-family: "Futura";
    font-size:1.2em;
    height: 40px;
}

How to make a JFrame button open another JFrame class in Netbeans?

This link works with me: video

The answer posted before didn't work for me until the second click

So what I did is Directly call:

        new NewForm().setVisible(true);

        this.dispose();//to close the current jframe

How to set background color of an Activity to white programmatically?

Button btn;
View root;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button)findViewById(R.id.button);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            root =findViewById(R.id.activity_main).getRootView();
            root.setBackgroundColor(Color.parseColor("#FFFFFF"));
        }
    });
}

Visual Studio Copy Project

If you want a copy, the fastest way of doing this would be to save the project. Then make a copy of the entire thing on the File System. Go back into Visual Studio and open the copy. From there, I would most likely recommend re-naming the project/solution so that you don't have two of the same name, but that is the fastest way to make a copy.

how to rotate text left 90 degree and cell size is adjusted according to text in html

Daniel Imms answer is excellent in regards to applying your CSS rotation to an inner element. However, it is possible to accomplish the end goal in a way that does not require JavaScript and works with longer strings of text.

Typically the whole reason to have vertical text in the first table column is to fit a long line of text in a short horizontal space and to go alongside tall rows of content (as in your example) or multiple rows of content (which I'll use in this example).

enter image description here

By using the ".rotate" class on the parent TD tag, we can not only rotate the inner DIV, but we can also set a few CSS properties on the parent TD tag that will force all of the text to stay on one line and keep the width to 1.5em. Then we can use some negative margins on the inner DIV to make sure that it centers nicely.

_x000D_
_x000D_
td {_x000D_
    border: 1px black solid;_x000D_
    padding: 5px;_x000D_
}_x000D_
.rotate {_x000D_
  text-align: center;_x000D_
  white-space: nowrap;_x000D_
  vertical-align: middle;_x000D_
  width: 1.5em;_x000D_
}_x000D_
.rotate div {_x000D_
     -moz-transform: rotate(-90.0deg);  /* FF3.5+ */_x000D_
       -o-transform: rotate(-90.0deg);  /* Opera 10.5 */_x000D_
  -webkit-transform: rotate(-90.0deg);  /* Saf3.1+, Chrome */_x000D_
             filter:  progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083);  /* IE6,IE7 */_x000D_
         -ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0.083)"; /* IE8 */_x000D_
         margin-left: -10em;_x000D_
         margin-right: -10em;_x000D_
}
_x000D_
<table cellpadding="0" cellspacing="0" align="center">_x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>10 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>20 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
    <tr>_x000D_
        <td class='rotate' rowspan="4"><div>30 kilograms</div></td>_x000D_
        <td>B</td>_x000D_
        <td>C</td>_x000D_
        <td>D</td>_x000D_
        <td>E</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>G</td>_x000D_
        <td>H</td>_x000D_
        <td>I</td>_x000D_
        <td>J</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>L</td>_x000D_
        <td>M</td>_x000D_
        <td>N</td>_x000D_
        <td>O</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td>Q</td>_x000D_
        <td>R</td>_x000D_
        <td>S</td>_x000D_
        <td>T</td>_x000D_
    </tr>_x000D_
    _x000D_
</table>
_x000D_
_x000D_
_x000D_

One thing to keep in mind with this solution is that it does not work well if the height of the row (or spanned rows) is shorter than the vertical text in the first column. It works best if you're spanning multiple rows or you have a lot of content creating tall rows.

Have fun playing around with this on jsFiddle.

TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader

I think it has to do with your second element in storbinary. You are trying to open file, but it is already a pointer to the file you opened in line file = open(local_path,'rb'). So, try to use ftp.storbinary("STOR " + i, file).

EF 5 Enable-Migrations : No context type was found in the assembly

Adding a class which inherits DbContext resolved my problem:

public class MyDbContext : DbContext { public MyDbContext() { } }

Fastest Way to Find Distance Between Two Lat/Long Points

   select
   (((acos(sin(('$latitude'*pi()/180)) * sin((`lat`*pi()/180))+cos(('$latitude'*pi()/180)) 
    * cos((`lat`*pi()/180)) * cos((('$longitude'- `lng`)*pi()/180))))*180/pi())*60*1.1515) 
    AS distance
    from table having distance<22;

How can I implement custom Action Bar with custom buttons in Android?

Please write following code in menu.xml file:

<menu xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:my_menu_tutorial_app="http://schemas.android.com/apk/res-auto"
      xmlns:tools="http://schemas.android.com/tools"
      tools:context="com.example.mymenus.menu_app.MainActivity">
<item android:id="@+id/item_one"
      android:icon="@drawable/menu_icon"
      android:orderInCategory="l01"
      android:title="Item One"
      my_menu_tutorial_app:showAsAction="always">
      <!--sub-menu-->
      <menu>
          <item android:id="@+id/sub_one"
                android:title="Sub-menu item one" />
          <item android:id="@+id/sub_two"
                android:title="Sub-menu item two" />
      </menu>

Also write this java code in activity class file:

public boolean onOptionsItemSelected(MenuItem item)
{
    super.onOptionsItemSelected(item);
    Toast.makeText(this, "Menus item selected: " +
        item.getTitle(), Toast.LENGTH_SHORT).show();
    switch (item.getItemId())
    {
        case R.id.sub_one:
            isItemOneSelected = true;
            supportInvalidateOptionsMenu();
            return true;
        case MENU_ITEM + 1:
            isRemoveItem = true;
            supportInvalidateOptionsMenu();
            return true;
        default:
            return false;
    }
}

This is the easiest way to display menus in action bar.

Using a PHP variable in a text input value = statement

If you want to read any created function, this how we do it:

<input type="button" value="sports" onClick="window.open('<?php sports();?>', '_self');">

Delete directory with files in it?

You could copy the YII helpers

$directory (string) - to be deleted recursively.

$options (array) - for the directory removal. Valid options are: traverseSymlinks: boolean, whether symlinks to the directories should be traversed too. Defaults to false, meaning that the content of the symlinked directory would not be deleted. Only symlink would be removed in that default case.

public static function removeDirectory($directory,$options=array())
{
    if(!isset($options['traverseSymlinks']))
        $options['traverseSymlinks']=false;
    $items=glob($directory.DIRECTORY_SEPARATOR.'{,.}*',GLOB_MARK | GLOB_BRACE);
    foreach($items as $item)
    {
        if(basename($item)=='.' || basename($item)=='..')
            continue;
        if(substr($item,-1)==DIRECTORY_SEPARATOR)
        {
            if(!$options['traverseSymlinks'] && is_link(rtrim($item,DIRECTORY_SEPARATOR)))
                unlink(rtrim($item,DIRECTORY_SEPARATOR));
            else
                self::removeDirectory($item,$options);
        }
        else
            unlink($item);
    }
    if(is_dir($directory=rtrim($directory,'\\/')))
    {
        if(is_link($directory))
            unlink($directory);
        else
            rmdir($directory);
    }
}

Leap year calculation

There's an algorithm on wikipedia to determine leap years:

function isLeapYear (year):
    if ((year modulo 4 is 0) and (year modulo 100 is not 0))
    or (year modulo 400 is 0)
        then true
    else false

There's a lot of information about this topic on the wikipedia page about leap years, inclusive information about different calendars.

Get values from a listbox on a sheet

Unfortunately for MSForms list box looping through the list items and checking their Selected property is the only way. However, here is an alternative. I am storing/removing the selected item in a variable, you can do this in some remote cell and keep track of it :)

Dim StrSelection As String

Private Sub ListBox1_Change()
    If ListBox1.Selected(ListBox1.ListIndex) Then
        If StrSelection = "" Then
            StrSelection = ListBox1.List(ListBox1.ListIndex)
        Else
            StrSelection = StrSelection & "," & ListBox1.List(ListBox1.ListIndex)
        End If
    Else
        StrSelection = Replace(StrSelection, "," & ListBox1.List(ListBox1.ListIndex), "")
    End If
End Sub

Do AJAX requests retain PHP Session info?

Well, not always. Using cookies, you are good. But the "can I safely rely on the id being present" urged me to extend the discussion with an important point (mostly for reference, as the visitor count of this page seems quite high).

PHP can be configured to maintain sessions by URL-rewriting, instead of cookies. (How it's good or bad (<-- see e.g. the topmost comment there) is a separate question, let's now stick to the current one, with just one side-note: the most prominent issue with URL-based sessions -- the blatant visibility of the naked session ID -- is not an issue with internal Ajax calls; but then, if it's turned on for Ajax, it's turned on for the rest of the site, too, so there...)

In case of URL-rewriting (cookieless) sessions, Ajax calls must take care of it themselves that their request URLs are properly crafted. (Or you can roll your own custom solution. You can even resort to maintaining sessions on the client side, in less demanding cases.) The point is the explicit care needed for session continuity, if not using cookies:

  1. If the Ajax calls just extract URLs verbatim from the HTML (as received from PHP), that should be OK, as they are already cooked (umm, cookified).

  2. If they need to assemble request URIs themselves, the session ID needs to be added to the URL manually. (Check here, or the page sources generated by PHP (with URL-rewriting on) to see how to do it.)


From OWASP.org:

Effectively, the web application can use both mechanisms, cookies or URL parameters, or even switch from one to the other (automatic URL rewriting) if certain conditions are met (for example, the existence of web clients without cookies support or when cookies are not accepted due to user privacy concerns).

From a Ruby-forum post:

When using php with cookies, the session ID will automatically be sent in the request headers even for Ajax XMLHttpRequests. If you use or allow URL-based php sessions, you'll have to add the session id to every Ajax request url.

How can I check if a directory exists?

You might use stat() and pass it the address of a struct stat, then check its member st_mode for having S_IFDIR set.

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>

...

char d[] = "mydir";

struct stat s = {0};

if (!stat(d, &s))
  printf("'%s' is %sa directory.\n", d, (s.st_mode & S_IFDIR)  : "" ? "not ");
  // (s.st_mode & S_IFDIR) can be replaced with S_ISDIR(s.st_mode)
else
  perror("stat()");

How to convert enum names to string in c

One way, making the preprocessor do the work. It also ensures your enums and strings are in sync.

#define FOREACH_FRUIT(FRUIT) \
        FRUIT(apple)   \
        FRUIT(orange)  \
        FRUIT(grape)   \
        FRUIT(banana)  \

#define GENERATE_ENUM(ENUM) ENUM,
#define GENERATE_STRING(STRING) #STRING,

enum FRUIT_ENUM {
    FOREACH_FRUIT(GENERATE_ENUM)
};

static const char *FRUIT_STRING[] = {
    FOREACH_FRUIT(GENERATE_STRING)
};

After the preprocessor gets done, you'll have:

enum FRUIT_ENUM {
    apple, orange, grape, banana,
};

static const char *FRUIT_STRING[] = {
    "apple", "orange", "grape", "banana",
};

Then you could do something like:

printf("enum apple as a string: %s\n",FRUIT_STRING[apple]);

If the use case is literally just printing the enum name, add the following macros:

#define str(x) #x
#define xstr(x) str(x)

Then do:

printf("enum apple as a string: %s\n", xstr(apple));

In this case, it may seem like the two-level macro is superfluous, however, due to how stringification works in C, it is necessary in some cases. For example, let's say we want to use a #define with an enum:

#define foo apple

int main() {
    printf("%s\n", str(foo));
    printf("%s\n", xstr(foo));
}

The output would be:

foo
apple

This is because str will stringify the input foo rather than expand it to be apple. By using xstr the macro expansion is done first, then that result is stringified.

See Stringification for more information.

How do I style a <select> dropdown with only CSS?

You definitely should do it like in Styling select, optgroup and options with CSS. In many ways, background-color and color are just what you would typically need to style options, not the entire select.

Multiline string literal in C#

Add multiple lines : use @

string query = @"SELECT foo, bar
FROM table
WHERE id = 42";

Add String Values to the middle : use $

string text ="beer";
string query = $"SELECT foo {text} bar ";

Multiple line string Add Values to the middle: use $@

string text ="Customer";
string query = $@"SELECT foo, bar
FROM {text}Table
WHERE id = 42";

Sorting dictionary keys in python

my_list = sorted(dict.items(), key=lambda x: x[1])

How to define custom exception class in Java, the easiest way?

No, you don't "inherit" non-default constructors, you need to define the one taking a String in your class. Typically you use super(message) in your constructor to invoke your parent constructor. For example, like this:

public class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

What's the best strategy for unit-testing database-driven applications?

I use the first (running the code against a test database). The only substantive issue I see you raising with this approach is the possibilty of schemas getting out of sync, which I deal with by keeping a version number in my database and making all schema changes via a script which applies the changes for each version increment.

I also make all changes (including to the database schema) against my test environment first, so it ends up being the other way around: After all tests pass, apply the schema updates to the production host. I also keep a separate pair of testing vs. application databases on my development system so that I can verify there that the db upgrade works properly before touching the real production box(es).

Base64 String throwing invalid character error

Whether null char is allowed or not really depends on base64 codec in question. Given vagueness of Base64 standard (there is no authoritative exact specification), many implementations would just ignore it as white space. And then others can flag it as a problem. And buggiest ones wouldn't notice and would happily try decoding it... :-/

But it sounds c# implementation does not like it (which is one valid approach) so if removing it helps, that should be done.

One minor additional comment: UTF-8 is not a requirement, ISO-8859-x aka Latin-x, and 7-bit Ascii would work as well. This because Base64 was specifically designed to only use 7-bit subset which works with all 7-bit ascii compatible encodings.

MySQL JOIN the most recent row only?

You can also do this

SELECT    CONCAT(title, ' ', forename, ' ', surname) AS name
FROM      customer c
LEFT JOIN  (
              SELECT * FROM  customer_data ORDER BY id DESC
          ) customer_data ON (customer_data.customer_id = c.customer_id)
GROUP BY  c.customer_id          
WHERE     CONCAT(title, ' ', forename, ' ', surname) LIKE '%Smith%' 
LIMIT     10, 20;

How do I implement a callback in PHP?

Implementation of a callback is done like so

// This function uses a callback function. 
function doIt($callback) 
{ 
    $data = "this is my data";
    $callback($data); 
} 


// This is a sample callback function for doIt(). 
function myCallback($data) 
{ 
    print 'Data is: ' .  $data .  "\n"; 
} 


// Call doIt() and pass our sample callback function's name. 
doIt('myCallback');

Displays: Data is: this is my data

When to use 'npm start' and when to use 'ng serve'?

For a project that's using the CLI, you will usually use ng serve. In other cases you may want to use npm start. Here the detailed explanation:

ng serve

Will serve a project that is 'Angular CLI aware', i.e. a project that has been created using the Angular CLI, particularly using:

ng new app-name

So, if you've scaffolded a project using the CLI, you'll probably want to use ng serve

npm start

This can be used in the case of a project that is not Angular CLI aware (or it can simply be used to run 'ng serve' for a project that's Angular CLI aware)

As the other answers state, this is an npm command that will run the npm command(s) from the package.json that have the identifier 'start', and it doesn't just have to run 'ng serve'. It's possible to have something like the following in the package.json:

   "scripts": {
     "build:watch": "tsc -p src/ -w",
     "serve": "lite-server -c=bs-config.json",
     "start": "concurrently \"npm run build:watch\" \"npm run serve\""
     ...
   },
   "devDependencies": {
     "concurrently": "^3.2.0",
     "lite-server": "^2.2.2",

In this case, 'npm start' will result in the following commands to be run:

concurrently "npm run build:watch" "npm run serve"

This will concurrently run the TypeScript compiler (watching for code changes), and run the Node lite-server (which users BrowserSync)

Splitting comma separated string in a PL/SQL stored proc

I use apex_util.string_to_table to parse strings, but you can use a different parser if you wish. Then you can insert the data as in this example:

declare
  myString varchar2(2000) :='0.75, 0.64, 0.56, 0.45';
  myAmount varchar2(2000) :='0.25, 0.5, 0.65, 0.8';
  v_array1 apex_application_global.vc_arr2;
  v_array2 apex_application_global.vc_arr2;
begin

  v_array1 := apex_util.string_to_table(myString, ', ');
  v_array2 := apex_util.string_to_table(myAmount, ', ');

  forall i in 1..v_array1.count
     insert into mytable (a, b) values (v_array1(i), v_array2(i));
end;

Apex_util is available from Oracle 10G onwards. Prior to this it was called htmldb_util and was not installed by default. If you can't use that you could use the string parser I wrote many years ago and posted here.

Read contents of a local file into a variable in Rails

Answering my own question here... turns out it's a Windows only quirk that happens when reading binary files (in my case a JPEG) that requires an additional flag in the open or File.open function call. I revised it to open("/path/to/file", 'rb') {|io| a = a + io.read} and all was fine.

On a CSS hover event, can I change another div's styling?

This can not be done purely with css. This is a behaviour, which affects the styling of the page.

With jquery you can quickly implement the behavior from your question:

$(function() {
  $('#a').hover(function() {
    $('#b').css('background-color', 'yellow');
  }, function() {
    // on mouseout, reset the background colour
    $('#b').css('background-color', '');
  });
});

php stdClass to array

Here is a version of Carlo's answer that can be used in a class:

class Formatter
{
    public function objectToArray($data)
    {
        if (is_object($data)) {
            $data = get_object_vars($data);
        }

        if (is_array($data)) {
            return array_map(array($this, 'objectToArray'), $data);
        }

        return $data;
    }
}

Length of a JavaScript object

Below is a version of James Coglan's answer in CoffeeScript for those who have abandoned straight JavaScript :)

Object.size = (obj) ->
  size = 0
  size++ for own key of obj
  size

Echo tab characters in bash script

If you want to use echo "a\tb" in a script, you run the script as:

# sh -e myscript.sh

Alternatively, you can give to myscript.sh the execution permission, and then run the script.

# chmod +x myscript.sh
# ./myscript.sh

SQL query to get the deadlocks in SQL SERVER 2008

You can use a deadlock graph and gather the information you require from the log file.

The only other way I could suggest is digging through the information by using EXEC SP_LOCK (Soon to be deprecated), EXEC SP_WHO2 or the sys.dm_tran_locks table.

SELECT  L.request_session_id AS SPID, 
    DB_NAME(L.resource_database_id) AS DatabaseName,
    O.Name AS LockedObjectName, 
    P.object_id AS LockedObjectId, 
    L.resource_type AS LockedResource, 
    L.request_mode AS LockType,
    ST.text AS SqlStatementText,        
    ES.login_name AS LoginName,
    ES.host_name AS HostName,
    TST.is_user_transaction as IsUserTransaction,
    AT.name as TransactionName,
    CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
    JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
    JOIN sys.objects O ON O.object_id = P.object_id
    JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
    JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
    JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
    JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
    CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

http://www.sqlmag.com/article/sql-server-profiler/gathering-deadlock-information-with-deadlock-graph

http://weblogs.sqlteam.com/mladenp/archive/2008/04/29/SQL-Server-2005-Get-full-information-about-transaction-locks.aspx

CSS hover vs. JavaScript mouseover

The problem with :hover is that IE6 only supports it on links. I use jQuery for this kind of thing these days:

$("div input").hover(function() {
  $(this).addClass("blue");
}, function() {
  $(this).removeClass("blue");
});

Makes things a lot easier. That'll work in IE6, FF, Chrome and Safari.

How to get response using cURL in PHP

If anyone else comes across this, I'm adding another answer to provide the response code or other information that might be needed in the "response".

http://php.net/manual/en/function.curl-getinfo.php

// init curl object        
$ch = curl_init();

// define options
$optArray = array(
    CURLOPT_URL => 'http://www.google.com',
    CURLOPT_RETURNTRANSFER => true
);

// apply those options
curl_setopt_array($ch, $optArray);

// execute request and get response
$result = curl_exec($ch);

// also get the error and response code
$errors = curl_error($ch);
$response = curl_getinfo($ch, CURLINFO_HTTP_CODE);

curl_close($ch);

var_dump($errors);
var_dump($response);

Output:

string(0) ""
int(200)

// change www.google.com to www.googlebofus.co
string(42) "Could not resolve host: www.googlebofus.co"
int(0)

how to count the spaces in a java string?

I just had to do something similar to this and this is what I used:

String string = stringValue;
String[] stringArray = string.split("\\s+");
int length = stringArray.length;
System.out.println("The number of parts is: " + length);

Html table with button on each row

Put a single listener on the table. When it gets a click from an input with a button that has a name of "edit" and value "edit", change its value to "modify". Get rid of the input's id (they aren't used for anything here), or make them all unique.

<script type="text/javascript">

function handleClick(evt) {
  var node = evt.target || evt.srcElement;
  if (node.name == 'edit') {
    node.value = "Modify";
  }
}

</script>

<table id="table1" border="1" onclick="handleClick(event);">
    <thead>
      <tr>
          <th>Select
    </thead>
    <tbody>
       <tr> 
           <td>
               <form name="f1" action="#" >
                <input id="edit1" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f2" action="#" >
                <input id="edit2" type="submit" name="edit" value="Edit">
               </form>
       <tr> 
           <td>
               <form name="f3" action="#" >
                <input id="edit3" type="submit" name="edit" value="Edit">
               </form>

   </tbody>
</table>

Getting DOM node from React child element

This may be possible by using the refs attribute.

In the example of wanting to to reach a <div> what you would want to do is use is <div ref="myExample">. Then you would be able to get that DOM node by using React.findDOMNode(this.refs.myExample).

From there getting the correct DOM node of each child may be as simple as mapping over this.refs.myExample.children(I haven't tested that yet) but you'll at least be able to grab any specific mounted child node by using the ref attribute.

Here's the official react documentation on refs for more info.

Add another class to a div

If the element has no class, give it one. Otherwise, append a space followed by the new className:

  var el = document.getElementById('hello');
  if(el) {
    el.className += el.className ? ' someClass' : 'someClass';
  }

How to connect SQLite with Java?

connection = DriverManager.getConnection("jdbc:sqlite:D:\\testdb.db");

Instead of this put

connection = DriverManager.getConnection("jdbc:sqlite:D:\\testdb");

Alter SQL table - allow NULL column value

The following MySQL statement should modify your column to accept NULLs.

ALTER TABLE `MyTable`
ALTER COLUMN `Col3` varchar(20) DEFAULT NULL

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

Your DemoApplication class is in the com.ag.digital.demo.boot package and your LoginBean class is in the com.ag.digital.demo.bean package. By default components (classes annotated with @Component) are found if they are in the same package or a sub-package of your main application class DemoApplication. This means that LoginBean isn't being found so dependency injection fails.

There are a couple of ways to solve your problem:

  1. Move LoginBean into com.ag.digital.demo.boot or a sub-package.
  2. Configure the packages that are scanned for components using the scanBasePackages attribute of @SpringBootApplication that should be on DemoApplication.

A few of other things that aren't causing a problem, but are not quite right with the code you've posted:

  • @Service is a specialisation of @Component so you don't need both on LoginBean
  • Similarly, @RestController is a specialisation of @Component so you don't need both on DemoRestController
  • DemoRestController is an unusual place for @EnableAutoConfiguration. That annotation is typically found on your main application class (DemoApplication) either directly or via @SpringBootApplication which is a combination of @ComponentScan, @Configuration, and @EnableAutoConfiguration.

JQuery Number Formatting

Using the jQuery Number Format plugin, you can get a formatted number in one of three ways:

// Return as a string
$.number( 1234.5678, 2 ); // Returns '1,234.57'

// Place formatted number directly in an element:
$('#mynum').number( 1234.5678 ); // #mynum would then contain '1,235'

// Replace existing number values in any element
$('span.num').number( true, 2 ); // Formats and replaces existing numbers in those elements.

If you don't like the format, or you need to localise, there are other parameters that let you choose how the number gets formatted:

.number( theNumber, decimalPlaces, decimalSeparator, thousandsSeparator )

You can also get jQuery Number Format from GitHub.

How to add image that is on my computer to a site in css or html?

The image needs to be in the same folder that your html page is in, then create a href to that folder with the picture name at the end. Example:

<img src="C:\users\home\pictures\picture.png"/>

HttpServletRequest - how to obtain the referring URL?

As all have mentioned it is

request.getHeader("referer");

I would like to add some more details about security aspect of referer header in contrast with accepted answer. In Open Web Application Security Project(OWASP) cheat sheets, under Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet it mentions about importance of referer header.

More importantly for this recommended Same Origin check, a number of HTTP request headers can't be set by JavaScript because they are on the 'forbidden' headers list. Only the browsers themselves can set values for these headers, making them more trustworthy because not even an XSS vulnerability can be used to modify them.

The Source Origin check recommended here relies on three of these protected headers: Origin, Referer, and Host, making it a pretty strong CSRF defense all on its own.

You can refer Forbidden header list here. User agent(ie:browser) has the full control over these headers not the user.

writing to existing workbook using xlwt

The code example is exactly this:

from xlutils.copy import copy
from xlrd import *
w = copy(open_workbook('book1.xls'))
w.get_sheet(0).write(0,0,"foo")
w.save('book2.xls')

You'll need to create book1.xls to test, but you get the idea.