Programs & Examples On #Jgroups

JGroups is a Java networking library that supports reliable group communication over UDP (IP Multicast) or TCP.

What is the use of "using namespace std"?

  • using: You are going to use it.
  • namespace: To use what? A namespace.
  • std: The std namespace (where features of the C++ Standard Library, such as string or vector, are declared).

After you write this instruction, if the compiler sees string it will know that you may be referring to std::string, and if it sees vector, it will know that you may be referring to std::vector. (Provided that you have included in your compilation unit the header files where they are defined, of course.)

If you don't write it, when the compiler sees string or vector it will not know what you are refering to. You will need to explicitly tell it std::string or std::vector, and if you don't, you will get a compile error.

Reverse HashMap keys and values in Java

If the values are not unique, the safe way to inverse the map is by using java 8's groupingBy function

Map<String, Integer> map = new HashMap<>();
map.put("a",1);
map.put("b",2);

Map<Integer, List<String>> mapInversed = 
map.entrySet()
   .stream()
   .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())))

Delete dynamically-generated table row using jQuery

I know this is old but I've used a function similar to this...

deleteRow: function (ctrl) {

    //remove the row from the table
    $(ctrl).closest('tr').remove();

}

... with markup like this ...

<tr>
<td><span id="spDeleteRow" onclick="deleteRow(this)">X</td>
<td> blah blah </td>
</tr>

...and it works fine

How to print exact sql query in zend framework ?

from >= 2.1.4

echo $select->getSqlString()

Video streaming over websockets using JavaScript

It's definitely conceivable but I am not sure we're there yet. In the meantime, I'd recommend using something like Silverlight with IIS Smooth Streaming. Silverlight is plugin-based, but it works on Windows/OSX/Linux. Some day the HTML5 <video> element will be the way to go, but that will lack support for a little while.

Reload .profile in bash shell script (in unix)?

The bash script runs in a separate subshell. In order to make this work you will need to source this other script as well.

Using import fs from 'fs'

Building on RobertoNovelo's answer:

import * as fs from 'fs';

is currently the simplest way to do it.

It was tested with a Node.js project (Node.js v10.15.3), with esm, allowing to use import.

YAML: Do I need quotes for strings in YAML?

After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:

  • In general, you don't need quotes.
  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).
  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
  • Double quotes parse escape codes. "\n" would be returned as a line feed character.
  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.

Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.

Update

"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:

en:
  yesno:
    'yes': 'Yes'
    'no': 'No'

Git undo local branch delete

If you haven't push the deletion yet, you can simply do :

$ git checkout deletedBranchName

PHP cURL, extract an XML response

simple load xml file ..

$xml = @simplexml_load_string($retValuet);

$status = (string)$xml->Status; 
$operator_trans_id = (string)$xml->OPID;
$trns_id = (string)$xml->TID;

?>

Best way to detect when a user leaves a web page?

For What its worth, this is what I did and maybe it can help others even though the article is old.

PHP:

session_start();

$_SESSION['ipaddress'] = $_SERVER['REMOTE_ADDR'];

if(isset($_SESSION['userID'])){
    if(!strpos($_SESSION['activeID'], '-')){
        $_SESSION['activeID'] = $_SESSION['userID'].'-'.$_SESSION['activeID'];
    }
}elseif(!isset($_SESSION['activeID'])){
    $_SESSION['activeID'] = time();
}

JS

window.setInterval(function(){
            var userid = '<?php echo $_SESSION['activeID']; ?>';
            var ipaddress = '<?php echo $_SESSION['ipaddress']; ?>';
            var action = 'data';

            $.ajax({
                url:'activeUser.php',
                method:'POST',
                data:{action:action,userid:userid,ipaddress:ipaddress},
                success:function(response){
                     //alert(response);                 
                }
            });
          }, 5000);

Ajax call to activeUser.php

if(isset($_POST['action'])){
    if(isset($_POST['userid'])){
        $stamp = time();
        $activeid = $_POST['userid'];
        $ip = $_POST['ipaddress'];

        $query = "SELECT stamp FROM activeusers WHERE activeid = '".$activeid."' LIMIT 1";
        $results = RUNSIMPLEDB($query);

        if($results->num_rows > 0){
            $query = "UPDATE activeusers SET stamp = '$stamp' WHERE activeid = '".$activeid."' AND ip = '$ip' LIMIT 1";
            RUNSIMPLEDB($query);
        }else{
            $query = "INSERT INTO activeusers (activeid,stamp,ip)
                    VALUES ('".$activeid."','$stamp','$ip')";
            RUNSIMPLEDB($query);
        }
    }
}

Database:

CREATE TABLE `activeusers` (
  `id` int(11) NOT NULL,
  `activeid` varchar(20) NOT NULL,
  `stamp` int(11) NOT NULL,
  `ip` text
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Basically every 5 seconds the js will post to a php file that will track the user and the users ip address. Active users are simply a database record that have an update to the database time stamp within 5 seconds. Old users stop updating to the database. The ip address is used just to ensure that a user is unique so 2 people on the site at the same time don't register as 1 user.

Probably not the most efficient solution but it does the job.

auto refresh for every 5 mins

Auto reload with target of your choice. In this case target is _self set to every 5 minutes.

300000 milliseconds = 300 seconds = 5 minutes

as 60000 milliseconds = 60 seconds = 1 minute.

This is how you do it:

<script type="text/javascript">
function load()
{
setTimeout("window.open('http://YourPage.com', '_self');", 300000);
}
</script>
<body onload="load()">

Or this if it is the same page to reload itself:

<script type="text/javascript">
function load()
{
setTimeout("window.open(self.location, '_self');", 300000);
}
</script>
<body onload="load()">

Git on Bitbucket: Always asked for password, even after uploading my public SSH key

The following assumes command-line access via iTerm / Terminal to bitbucket.

For MacOS Sierra 10.12.5, my system manifested an equivalent problem - asking for my SSH passphrase on each connection to bitbucket.

The issue has to do with OpenSSH updates in macOS 10.12.2, which are described here in Technical Note TN2449.

You very well might want to tailor your solution, but the following will work when added to your ~/.ssh/config file:

Host *
    UseKeychain yes

For more information on ssh configs, take a look at the man pages for ssh_config:

% man ssh_config

One other thing: there is a good write-up on superuser here that discusses this problem and various solutions depending on your needs and setup.

C++ Array Of Pointers

For example, if you want an array of int pointers it will be int* a[10]. It means that variable a is a collection of 10 int* s.

EDIT

I guess this is what you want to do:

class Bar
{
};

class Foo
{
public:

    //Takes number of bar elements in the pointer array
    Foo(int size_in);

    ~Foo();
    void add(Bar& bar);
private:

    //Pointer to bar array
    Bar** m_pBarArr;

    //Current fee bar index
    int m_index;
};

Foo::Foo(int size_in) : m_index(0)
{
    //Allocate memory for the array of bar pointers
    m_pBarArr = new Bar*[size_in];
}

Foo::~Foo()
{
    //Notice delete[] and not delete
    delete[] m_pBarArr;
    m_pBarArr = NULL;
}

void Foo::add(Bar &bar)
{
    //Store the pointer into the array. 
    //This is dangerous, you are assuming that bar object
    //is valid even when you try to use it
    m_pBarArr[m_index++] = &bar;
}

test if event handler is bound to an element in jQuery

This solution is no more supported since jQuery 1.8 as we can read on the blog here:

$(element).data(“events”): This is now removed in 1.8, but you can still get to the events data for debugging purposes via $._data(element, "events"). Note that this is not a supported public interface; the actual data structures may change incompatibly from version to version.

So, you should unbind/rebind it or simply, use a boolean to determine if your event as been attached or not (which is in my opinion the best solution).

How do I tell Maven to use the latest version of a dependency?

If you want Maven should use the latest version of a dependency, then you can use Versions Maven Plugin and how to use this plugin, Tim has already given a good answer, follow his answer.

But as a developer, I will not recommend this type of practices. WHY?

answer to why is already given by Pascal Thivent in the comment of the question

I really don't recommend this practice (nor using version ranges) for the sake of build reproducibility. A build that starts to suddenly fail for an unknown reason is way more annoying than updating manually a version number.

I will recommend this type of practice:

<properties>
    <spring.version>3.1.2.RELEASE</spring.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>

</dependencies>

it is easy to maintain and easy to debug. You can update your POM in no time.

What is the list of valid @SuppressWarnings warning names in Java?

If you're using SonarLint, try above the method or class the whole squid string: @SuppressWarnings("squid:S1172")

How to download fetch response in react as file

Browser technology currently doesn't support downloading a file directly from an Ajax request. The work around is to add a hidden form and submit it behind the scenes to get the browser to trigger the Save dialog.

I'm running a standard Flux implementation so I'm not sure what the exact Redux (Reducer) code should be, but the workflow I just created for a file download goes like this...

  1. I have a React component called FileDownload. All this component does is render a hidden form and then, inside componentDidMount, immediately submit the form and call it's onDownloadComplete prop.
  2. I have another React component, we'll call it Widget, with a download button/icon (many actually... one for each item in a table). Widget has corresponding action and store files. Widget imports FileDownload.
  3. Widget has two methods related to the download: handleDownload and handleDownloadComplete.
  4. Widget store has a property called downloadPath. It's set to null by default. When it's value is set to null, there is no file download in progress and the Widget component does not render the FileDownload component.
  5. Clicking the button/icon in Widget calls the handleDownload method which triggers a downloadFile action. The downloadFile action does NOT make an Ajax request. It dispatches a DOWNLOAD_FILE event to the store sending along with it the downloadPath for the file to download. The store saves the downloadPath and emits a change event.
  6. Since there is now a downloadPath, Widget will render FileDownload passing in the necessary props including downloadPath as well as the handleDownloadComplete method as the value for onDownloadComplete.
  7. When FileDownload is rendered and the form is submitted with method="GET" (POST should work too) and action={downloadPath}, the server response will now trigger the browser's Save dialog for the target download file (tested in IE 9/10, latest Firefox and Chrome).
  8. Immediately following the form submit, onDownloadComplete/handleDownloadComplete is called. This triggers another action that dispatches a DOWNLOAD_FILE event. However, this time downloadPath is set to null. The store saves the downloadPath as null and emits a change event.
  9. Since there is no longer a downloadPath the FileDownload component is not rendered in Widget and the world is a happy place.

Widget.js - partial code only

import FileDownload from './FileDownload';

export default class Widget extends Component {
    constructor(props) {
        super(props);
        this.state = widgetStore.getState().toJS();
    }

    handleDownload(data) {
        widgetActions.downloadFile(data);
    }

    handleDownloadComplete() {
        widgetActions.downloadFile();
    }

    render() {
        const downloadPath = this.state.downloadPath;

        return (

            // button/icon with click bound to this.handleDownload goes here

            {downloadPath &&
                <FileDownload
                    actionPath={downloadPath}
                    onDownloadComplete={this.handleDownloadComplete}
                />
            }
        );
    }

widgetActions.js - partial code only

export function downloadFile(data) {
    let downloadPath = null;

    if (data) {
        downloadPath = `${apiResource}/${data.fileName}`;
    }

    appDispatcher.dispatch({
        actionType: actionTypes.DOWNLOAD_FILE,
        downloadPath
    });
}

widgetStore.js - partial code only

let store = Map({
    downloadPath: null,
    isLoading: false,
    // other store properties
});

class WidgetStore extends Store {
    constructor() {
        super();
        this.dispatchToken = appDispatcher.register(action => {
            switch (action.actionType) {
                case actionTypes.DOWNLOAD_FILE:
                    store = store.merge({
                        downloadPath: action.downloadPath,
                        isLoading: !!action.downloadPath
                    });
                    this.emitChange();
                    break;

FileDownload.js
- complete, fully functional code ready for copy and paste
- React 0.14.7 with Babel 6.x ["es2015", "react", "stage-0"]
- form needs to be display: none which is what the "hidden" className is for

import React, {Component, PropTypes} from 'react';
import ReactDOM from 'react-dom';

function getFormInputs() {
    const {queryParams} = this.props;

    if (queryParams === undefined) {
        return null;
    }

    return Object.keys(queryParams).map((name, index) => {
        return (
            <input
                key={index}
                name={name}
                type="hidden"
                value={queryParams[name]}
            />
        );
    });
}

export default class FileDownload extends Component {

    static propTypes = {
        actionPath: PropTypes.string.isRequired,
        method: PropTypes.string,
        onDownloadComplete: PropTypes.func.isRequired,
        queryParams: PropTypes.object
    };

    static defaultProps = {
        method: 'GET'
    };

    componentDidMount() {
        ReactDOM.findDOMNode(this).submit();
        this.props.onDownloadComplete();
    }

    render() {
        const {actionPath, method} = this.props;

        return (
            <form
                action={actionPath}
                className="hidden"
                method={method}
            >
                {getFormInputs.call(this)}
            </form>
        );
    }
}

How to change column datatype from character to numeric in PostgreSQL 8.4

If your VARCHAR column contains empty strings (which are not the same as NULL for PostgreSQL as you might recall) you will have to use something in the line of the following to set a default:

ALTER TABLE presales ALTER COLUMN code TYPE NUMERIC(10,0)
            USING COALESCE(NULLIF(code, '')::NUMERIC, 0);

(found with the help of this answer)

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

@mikejonesguy answer is perfect, just in case you plan to test room migrations (recommended), add the schema location to the source sets.

In your build.gradle file you specify a folder to place these generated schema JSON files. As you update your schema, you’ll end up with several JSON files, one for every version. Make sure you commit every generated file to source control. The next time you increase your version number again, Room will be able to use the JSON file for testing.

build.gradle

android {

    // [...]

    defaultConfig {

        // [...]

        javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }

    // add the schema location to the source sets
    // used by Room, to test migrations
    sourceSets {
        androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
    }

    // [...]
}

Convert js Array() to JSon object for use with JQuery .ajax

There is actuly a difference between array object and JSON object. Instead of creating array object and converting it into a json object(with JSON.stringify(arr)) you can do this:

var sels = //Here is your array of SELECTs
var json = { };

for(var i = 0, l = sels.length; i < l; i++) {
  json[sels[i].id] = sels[i].value;
}

There is no need of converting it into JSON because its already a json object. To view the same use json.toSource();

Lightweight Javascript DB for use in Node.js

Maybe you should try LocallyDB it's easy-to-use and lightweight in addition to the with advanced selecting system similar to javascript conditional expression...

https://github.com/btwael/locallydb

jQuery's .on() method combined with the submit event

I had a problem with the same symtoms. In my case, it turned out that my submit function was missing the "return" statement.

For example:

 $("#id_form").on("submit", function(){
   //Code: Action (like ajax...)
   return false;
 })

How to remove leading and trailing zeros in a string? Python

You can simply do this with a bool:

if int(number) == float(number):

   number = int(number)

else:

   number = float(number)

Redis command to get all available keys?

Try to look at KEYS command. KEYS * will list all keys stored in redis.

EDIT: please note the warning at the top of KEYS documentation page:

Time complexity: O(N) with N being the number of keys in the database, under the assumption that the key names in the database and the given pattern have limited length.

UPDATE (V2.8 or greater): SCAN is a superior alternative to KEYS, in the sense that it does not block the server nor does it consume significant resources. Prefer using it.

Merge/flatten an array of arrays

ES-Next solutions

  1. Array.from / Set / Array.flat / Array.sort
// 1. remove duplicate item
// 2. flat array
let arr= [["$6", ["$18"]], ["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];

let result = Array.from(new Set(arr.flat(Infinity)));

console.log(`flat array with unique filter`, result);
// 

_x000D_
_x000D_
// 1. remove duplicate item_x000D_
// 2. sort by Asc order (munber only)_x000D_
// 3. flat array_x000D_
_x000D_
// let arr= [["$6", ["$18"]], ["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];_x000D_
_x000D_
let arr= [["6", ["18"]], ["6"], ["12"], ["25"], ["25"], ["18"], ["22"], ["10"]];_x000D_
_x000D_
let result = Array.from(new Set(arr.flat(Infinity))).map(Number).sort((a,b)=> a > b ? 1: -1);_x000D_
_x000D_
console.log(`flat array with unique filter & Asc sort`, result);_x000D_
//
_x000D_
_x000D_
_x000D_

  1. ...spread / Set / Array.flat / Array.sort
// 1. remove duplicate item
// 2. flat array
let arr= [["$6", ["$18"]], ["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];

let result = [...new Set(arr.flat(Infinity))];

console.log(`flat array with unique filter`, result);
// 

_x000D_
_x000D_
// 1. remove duplicate item_x000D_
// 2. sort by Asc order(number only)_x000D_
// 3. flat array_x000D_
_x000D_
//let arr= [["$6", ["$18"]], ["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]];_x000D_
_x000D_
let arr= [["6", ["18"]], ["6"], ["12"], ["25"], ["25"], ["18"], ["22"], ["10"]];_x000D_
_x000D_
let result = [...new Set(arr.flat(Infinity))].map(Number).sort((a,b)=> a > b ? 1: -1);_x000D_
_x000D_
console.log(`flat array with unique filter & Asc sort`, result);_x000D_
// 
_x000D_
_x000D_
_x000D_

refs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

How can I count the numbers of rows that a MySQL query returned?

In the event you have to solve the problem with simple SQL you might use an inline view.

select count(*) from (select * from foo) as x;

Scale Image to fill ImageView width and keep aspect ratio

You can try to do what you're doing by manually loading the images, but I would very very strongly recommend taking a look at Universal Image Loader.

I recently integrated it into my project and I have to say its fantastic. Does all the worrying about making things asynchronous, resizing, caching images for you. It's really easy to integrate and set up. Within 5 minutes you can probably get it doing what you want.

Example code:

//ImageLoader config
DisplayImageOptions displayimageOptions = new DisplayImageOptions.Builder().showStubImage(R.drawable.downloadplaceholder).cacheInMemory().cacheOnDisc().showImageOnFail(R.drawable.loading).build();

    ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getApplicationContext()).
            defaultDisplayImageOptions(displayimageOptions).memoryCache(new WeakMemoryCache()).discCache(new UnlimitedDiscCache(cacheDir)).build();

    if (ImageLoader.getInstance().isInited()) {
        ImageLoader.getInstance().destroy();
    }
    ImageLoader.getInstance().init(config);

    imageLoadingListener = new ImageLoadingListener() {
        @Override
        public void onLoadingStarted(String s, View view) {

        }

        @Override
        public void onLoadingFailed(String s, View view, FailReason failReason) {
            ImageView imageView = (ImageView) view;
            imageView.setImageResource(R.drawable.android);
            Log.i("Failed to Load " + s, failReason.toString());
        }

        @Override
        public void onLoadingComplete(String s, View view, Bitmap bitmap) {

        }

        @Override
        public void onLoadingCancelled(String s, View view) {

        }
    };

//Imageloader usage
ImageView imageView = new ImageView(getApplicationContext());
    if (orientation == 1) {
        imageView.setLayoutParams(new LinearLayout.LayoutParams(width / 6, width / 6));
    } else {
        imageView.setLayoutParams(new LinearLayout.LayoutParams(height / 6, height / 6));
    }
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageLoader.displayImage(SERVER_HOSTNAME + "demos" + demo.getPathRoot() + demo.getRootName() + ".png", imageView, imageLoadingListener);

This can lazy load the images, fit them correctly to the size of the imageView showing a placeholder image while it loads, and showing a default icon if loading fails and caching the resources.

-- I should also add that this current config keeps the image aspect ratio, hence applicable to your original question

SQL SERVER: Get total days between two dates

Another date format

select datediff(day,'20110101','20110301')

Why is the jquery script not working?

This works fine. just insert your jquery code in document.ready function.

 $(document).ready(function(e) {   
    // your code here
 });

example:

jquery

    $(document).ready(function(e) {   

      $('[id^=\"btnRight\"]').click(function (e) {    
        $(this).prev('select').find('option:selected').remove().appendTo('#isselect_code');    
      });

      $('[id^=\"btnLeft\"]').click(function (e) {
        $(this).next('select').find('option:selected').remove().appendTo('#canselect_code');
      });

    });

html

    <div>
        <select id='canselect_code' name='canselect_code' multiple class='fl'>
            <option value='1'>toto</option>
            <option value='2'>titi</option>
        </select>
        <input type='button' id='btnRight_code' value='  >  ' />
        <br>
        <input type='button' id='btnLeft_code' value='  <  ' />
        <select id='isselect_code' name='isselect_code' multiple class='fr'>
            <option value='3'>tata</option>
            <option value='4'>tutu</option>
        </select>
    </div>

Open Jquery modal dialog on click event

Try this

    $(function() {

$('#clickMe').click(function(event) {
    var mytext = $('#myText').val();


    $('<div id="dialog">'+mytext+'</div>').appendTo('body');        
    event.preventDefault();

        $("#dialog").dialog({                   
            width: 600,
            modal: true,
            close: function(event, ui) {
                $("#dialog").remove();
                }
            });
    }); //close click
});

And in HTML

<h3 id="clickMe">Open dialog</h3>
<textarea cols="0" rows="0" id="myText" style="display:none">Some hidden text display none</textarea>

How to use a variable from a cursor in the select statement of another cursor in pl/sql

You can certainly do something like

SQL> ed
Wrote file afiedt.buf

  1  begin
  2    for d in (select * from dept)
  3    loop
  4      for e in (select * from emp where deptno=d.deptno)
  5      loop
  6        dbms_output.put_line( 'Employee ' || e.ename ||
  7                              ' in department ' || d.dname );
  8      end loop;
  9    end loop;
 10* end;
SQL> /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES

PL/SQL procedure successfully completed.

Or something equivalent using explicit cursors.

SQL> ed
Wrote file afiedt.buf

  1  declare
  2    cursor dept_cur
  3        is select *
  4             from dept;
  5    d dept_cur%rowtype;
  6    cursor emp_cur( p_deptno IN dept.deptno%type )
  7        is select *
  8             from emp
  9            where deptno = p_deptno;
 10    e emp_cur%rowtype;
 11  begin
 12    open dept_cur;
 13    loop
 14      fetch dept_cur into d;
 15      exit when dept_cur%notfound;
 16      open emp_cur( d.deptno );
 17      loop
 18        fetch emp_cur into e;
 19        exit when emp_cur%notfound;
 20        dbms_output.put_line( 'Employee ' || e.ename ||
 21                              ' in department ' || d.dname );
 22      end loop;
 23      close emp_cur;
 24    end loop;
 25    close dept_cur;
 26* end;
 27  /
Employee CLARK in department ACCOUNTING
Employee KING in department ACCOUNTING
Employee MILLER in department ACCOUNTING
Employee smith in department RESEARCH
Employee JONES in department RESEARCH
Employee SCOTT in department RESEARCH
Employee ADAMS in department RESEARCH
Employee FORD in department RESEARCH
Employee ALLEN in department SALES
Employee WARD in department SALES
Employee MARTIN in department SALES
Employee BLAKE in department SALES
Employee TURNER in department SALES
Employee JAMES in department SALES

PL/SQL procedure successfully completed.

However, if you find yourself using nested cursor FOR loops, it is almost always more efficient to let the database join the two results for you. After all, relational databases are really, really good at joining. I'm guessing here at what your tables look like and how they relate based on the code you posted but something along the lines of

FOR x IN (SELECT *
            FROM all_users,
                 org
           WHERE length(all_users.username) = 3
             AND all_users.username = org.username )
LOOP
  <<do something>>
END LOOP;

Java, return if trimmed String in List contains String

You may be able to use an approximate string matching library to do this, e.g. SecondString, but that is almost certainly overkill - just use one of the for-loop answers provided instead.

How do I use 3DES encryption/decryption in Java?

Here's a very simply static encrypt/decrypt class biased on the Bouncy Castle no padding example by Jose Luis Montes de Oca. This one is using "DESede/ECB/PKCS7Padding" so I don't have to bother manually padding.


    package com.zenimax.encryption;

    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.security.NoSuchProviderException;
    import java.security.Security;
    import javax.crypto.BadPaddingException;
    import javax.crypto.Cipher;
    import javax.crypto.IllegalBlockSizeException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;

    /**
     * 
     * @author Matthew H. Wagner
     */
    public class TripleDesBouncyCastle {
        private static String TRIPLE_DES_TRANSFORMATION = "DESede/ECB/PKCS7Padding";
        private static String ALGORITHM = "DESede";
        private static String BOUNCY_CASTLE_PROVIDER = "BC";

        private static void init()
        {
            Security.addProvider(new BouncyCastleProvider());
        }

        public static byte[] encode(byte[] input, byte[] key)
                throws IllegalBlockSizeException, BadPaddingException,
                NoSuchAlgorithmException, NoSuchProviderException,
                NoSuchPaddingException, InvalidKeyException {
            init();
            SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
            Cipher encrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,
                    BOUNCY_CASTLE_PROVIDER);
            encrypter.init(Cipher.ENCRYPT_MODE, keySpec);
            return encrypter.doFinal(input);
        }

        public static byte[] decode(byte[] input, byte[] key)
                throws IllegalBlockSizeException, BadPaddingException,
                NoSuchAlgorithmException, NoSuchProviderException,
                NoSuchPaddingException, InvalidKeyException {
            init();
            SecretKey keySpec = new SecretKeySpec(key, ALGORITHM);
            Cipher decrypter = Cipher.getInstance(TRIPLE_DES_TRANSFORMATION,
                    BOUNCY_CASTLE_PROVIDER);
            decrypter.init(Cipher.DECRYPT_MODE, keySpec);
            return decrypter.doFinal(input);
        }
    }

What do the result codes in SVN mean?

Also note that a result code in the second column refers to the properties of the file. For example:

U   filename.1
 U  filename.2  
UU  filename.3

filename.1: the file was updated
filename.2: a property or properties on the file (such as svn:keywords) was updated
filename.3: both the file and its properties were updated

How can I determine the status of a job?

-- Microsoft SQL Server 2008 Standard Edition:
IF EXISTS(SELECT 1 
          FROM msdb.dbo.sysjobs J 
          JOIN msdb.dbo.sysjobactivity A 
              ON A.job_id=J.job_id 
          WHERE J.name=N'Your Job Name' 
          AND A.run_requested_date IS NOT NULL 
          AND A.stop_execution_date IS NULL
         )
    PRINT 'The job is running!'
ELSE
    PRINT 'The job is not running.'

iOS Swift - Get the Current Local Time and Date Timestamp

you can even create a function to return different time stamps depending on your necessity:

func dataatual(_ tipo:Int) -> String {
        let date = Date()
        let formatter = DateFormatter()
        if tipo == 1{
            formatter.dateFormat = "dd/MM/yyyy"
        } else if tipo == 2{
            formatter.dateFormat = "yyyy-MM-dd HH:mm"
        } else {
            formatter.dateFormat = "dd-MM-yyyy"
        }

        return formatter.string(from: date)
    } 

VBA module that runs other modules

Is "Module1" part of the same workbook that contains "moduleController"?
If not, you could call public method of "Module1" using Application.Run someWorkbook.xlsm!methodOfModule.

How does the getView() method work when creating your own custom adapter?

You can also find useful information about getView at the Adapter interface in Adapter.java file. It says;

/**
 * Get a View that displays the data at the specified position in the data set. You can either
 * create a View manually or inflate it from an XML layout file. When the View is inflated, the
 * parent View (GridView, ListView...) will apply default layout parameters unless you use
 * {@link android.view.LayoutInflater#inflate(int, android.view.ViewGroup, boolean)}
 * to specify a root view and to prevent attachment to the root.
 * 
 * @param position The position of the item within the adapter's data set of the item whose view
 *        we want.
 * @param convertView The old view to reuse, if possible. Note: You should check that this view
 *        is non-null and of an appropriate type before using. If it is not possible to convert
 *        this view to display the correct data, this method can create a new view.
 *        Heterogeneous lists can specify their number of view types, so that this View is
 *        always of the right type (see {@link #getViewTypeCount()} and
 *        {@link #getItemViewType(int)}).
 * @param parent The parent that this view will eventually be attached to
 * @return A View corresponding to the data at the specified position.
 */
View getView(int position, View convertView, ViewGroup parent);

What's the best way to add a drop shadow to my UIView

Try this:

UIBezierPath *shadowPath = [UIBezierPath bezierPathWithRect:view.bounds];
view.layer.masksToBounds = NO;
view.layer.shadowColor = [UIColor blackColor].CGColor;
view.layer.shadowOffset = CGSizeMake(0.0f, 5.0f);
view.layer.shadowOpacity = 0.5f;
view.layer.shadowPath = shadowPath.CGPath;

First of all: The UIBezierPath used as shadowPath is crucial. If you don't use it, you might not notice a difference at first, but the keen eye will observe a certain lag occurring during events like rotating the device and/or similar. It's an important performance tweak.

Regarding your issue specifically: The important line is view.layer.masksToBounds = NO. It disables the clipping of the view's layer's sublayers that extend further than the view's bounds.

For those wondering what the difference between masksToBounds (on the layer) and the view's own clipToBounds property is: There isn't really any. Toggling one will have an effect on the other. Just a different level of abstraction.


Swift 2.2:

override func layoutSubviews()
{
    super.layoutSubviews()

    let shadowPath = UIBezierPath(rect: bounds)
    layer.masksToBounds = false
    layer.shadowColor = UIColor.blackColor().CGColor
    layer.shadowOffset = CGSizeMake(0.0, 5.0)
    layer.shadowOpacity = 0.5
    layer.shadowPath = shadowPath.CGPath
}

Swift 3:

override func layoutSubviews()
{
    super.layoutSubviews()

    let shadowPath = UIBezierPath(rect: bounds)
    layer.masksToBounds = false
    layer.shadowColor = UIColor.black.cgColor
    layer.shadowOffset = CGSize(width: 0.0, height: 5.0)
    layer.shadowOpacity = 0.5
    layer.shadowPath = shadowPath.cgPath
}

Best way to find if an item is in a JavaScript array?

If the array is unsorted, there isn't really a better way (aside from using the above-mentioned indexOf, which I think amounts to the same thing). If the array is sorted, you can do a binary search, which works like this:

  1. Pick the middle element of the array.
  2. Is the element you're looking for bigger than the element you picked? If so, you've eliminated the bottom half of the array. If it isn't, you've eliminated the top half.
  3. Pick the middle element of the remaining half of the array, and continue as in step 2, eliminating halves of the remaining array. Eventually you'll either find your element or have no array left to look through.

Binary search runs in time proportional to the logarithm of the length of the array, so it can be much faster than looking at each individual element.

How do I style (css) radio buttons and labels?

This will get your buttons and labels next to each other, at least. I believe the second part can't be done in css alone, and will need javascript. I found a page that might help you with that part as well, but I don't have time right now to try it out: http://www.webmasterworld.com/forum83/6942.htm

<style type="text/css">
.input input {
  float: left;
}
.input label {
  margin: 5px;
}
</style>
<div class="input radio">
    <fieldset>
        <legend>What color is the sky?</legend>
        <input type="hidden" name="data[Submit][question]" value="" id="SubmitQuestion" />

        <input type="radio" name="data[Submit][question]" id="SubmitQuestion1" value="1"  />
        <label for="SubmitQuestion1">A strange radient green.</label>

        <input type="radio" name="data[Submit][question]" id="SubmitQuestion2" value="2"  />
        <label for="SubmitQuestion2">A dark gloomy orange</label>
        <input type="radio" name="data[Submit][question]" id="SubmitQuestion3" value="3"  />
        <label for="SubmitQuestion3">A perfect glittering blue</label>
    </fieldset>
</div>

CSS hide scroll bar if not needed

You can use both .content and .container to overflow:auto. Means if it's text is exceed automatically scroll will come x-axis and y-axis. (no need to give separete x-axis and y-axis commonly give overflow:auto)

.content {overflow:auto;}

pip installation /usr/local/opt/python/bin/python2.7: bad interpreter: No such file or directory

I made the same error using sudo for my installation. (oops)

brew install python
brew linkapps python
brew link --overwrite python 

This brought everything back to normal.

link_to method and click event in Rails

To follow up on Ron's answer if using JQuery and putting it in application.js or the head section you need to wrap it in a ready() section...

$(document).ready(function() {
  $('#my-link').click(function(event){
    alert('Hooray!');
    event.preventDefault(); // Prevent link from following its href
  });
});

Sorting an array in C?

In C, you can use the built in qsort command:

int compare( const void* a, const void* b)
{
     int int_a = * ( (int*) a );
     int int_b = * ( (int*) b );

     if ( int_a == int_b ) return 0;
     else if ( int_a < int_b ) return -1;
     else return 1;
}

qsort( a, 6, sizeof(int), compare )

see: http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/


To answer the second part of your question: an optimal (comparison based) sorting algorithm is one that runs with O(n log(n)) comparisons. There are several that have this property (including quick sort, merge sort, heap sort, etc.), but which one to use depends on your use case.

As a side note, you can sometime do better than O(n log(n)) if you know something about your data - see the wikipedia article on Radix Sort

Bulk Insert Correctly Quoted CSV File in SQL Server

There is another solution for this.

Consider the quotes as part of the fields delimiter, by editing the fmt file.

You can check this out for more information:

http://blogs.msdn.com/b/sqlserverfaq/archive/2010/02/04/how-to-remove-unwanted-quotation-marks-while-importing-a-data-file.aspx

An extract of the link above:

The only way to remove the quotation marks would be to modify the column delimiters specified during the import operation. The only drawback here is that if you inspect the data to be inserted, you will very quickly realize that the column delimiters are different for each column (Delimiters highlighted above).

So to specify different column delimiters for each column, you would need to use a format file if you plan to use Bulk Insert or BCP. If you generate a format file for the above table structure, it would be as follows:

9.0
3
1       SQLCHAR       0       5       "\t"     1     FName              SQL_Latin1_General_CP1_CI_AS
2       SQLCHAR       0       5       "\t"     2     LName              SQL_Latin1_General_CP1_CI_AS
3       SQLCHAR       0       50      "\r\n"   3     Company            SQL_Latin1_General_CP1_CI_AS

Modify the format file to represent the correct column delimiters for each column. The new format file to be used will look like this:

9.0
4
1       SQLCHAR       0       0     "\""      0     FIRST_QUOTE      SQL_Latin1_General_CP1_CI_AS
2       SQLCHAR       0       5     "\",\""   1     FNAME               SQL_Latin1_General_CP1_CI_AS
3       SQLCHAR       0       5     "\",\""   2     LNAME            SQL_Latin1_General_CP1_CI_AS
4       SQLCHAR       0       50    "\"\r\n"  3     COMPANY          SQL_Latin1_General_CP1_CI_AS

Detecting value change of input[type=text] in jQuery

Try this.. credits to https://stackoverflow.com/users/1169519/teemu

for answering my question here: https://stackoverflow.com/questions/24651811/jquery-keyup-doesnt-work-with-keycode-filtering?noredirect=1#comment38213480_24651811

This solution helped me to progress on my project.

$("#your_textbox").on("input propertychange",function(){

   // Do your thing here.
});

Note: propertychange for lower versions of IE.

How can I check if my Element ID has focus?

If you want to use jquery $("..").is(":focus").

You can take a look at this stack

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

You can set the value property using client script after the element is created:

<input type="text" id="fee" />

<script type="text/javascript>
document.getElementById('fee').value = '1000';
</script>

WCF ServiceHost access rights

Running Visual Studio as administrator could fix the issue, but if you use Visual Studio with for example TortoiseSVN, you cannot commit any changes. Another possible solution would be to run the service as administrator and the rest Visual Studio as local user.

How to read strings from a Scanner in a Java console application?

Replace:

System.out.println("Enter EmployeeName:");
                 ename=(scanner.next());

with:

System.out.println("Enter EmployeeName:");
                 ename=(scanner.nextLine());

This is because next() grabs only the next token, and the space acts as a delimiter between the tokens. By this, I mean that the scanner reads the input: "firstname lastname" as two separate tokens. So in your example, ename would be set to firstname and the scanner is attempting to set the supervisorId to lastname

Replace all particular values in a data frame

If you want to replace multiple values in a data frame, looping through all columns might help.

Say you want to replace "" and 100:

na_codes <- c(100, "")
for (i in seq_along(df)) {
    df[[i]][df[[i]] %in% na_codes] <- NA
}

Bootstrap datepicker disabling past dates without current date

It depends on what format you put on the datepicker So first we gave it the format.

    var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!

    var yyyy = today.getFullYear();
    if(dd<10){
        dd='0'+dd;
    } 
    if(mm<10){
        mm='0'+mm;
    } 
    var today = yyyy+'-'+mm+'-'+dd; //Here you put the format you want

Then Pass the datepicker (depends on the version you using, could be startDate or minDate which is my case )

    //Datetimepicker
    $(function () {
        $('#datetimepicker1').datetimepicker({
            minDate: today, //pass today's date
            daysOfWeekDisabled: [0],
            locale: 'es',
            inline: true,
            format: 'YYYY-MM-DD HH:mm', //format of my datetime (to save on mysqlphpadmin)
            sideBySide: true
        });
    });

How do you echo a 4-digit Unicode character in Bash?

Just put "?" in your shell script. In the correct locale and on a Unicode-enabled console it'll print just fine:

$ echo ?
?
$

An ugly "workaround" would be to output the UTF-8 sequence, but that also depends on the encoding used:

$ echo -e '\xE2\x98\xA0'
?
$

OnclientClick and OnClick is not working at the same time?

There are two issues here:

Disabling the button on the client side prevents the postback

To overcome this, disable the button after the JavaScript onclick event. An easy way to do this is to use setTimeout as suggested by this answer.

Also, the OnClientClick code runs even if ASP.NET validation fails, so it's probably a good idea to add a check for Page_IsValid. This ensures that the button will not be disabled if validation fails.

OnClientClick="(function(button) { setTimeout(function () { if (Page_IsValid) button.disabled = true; }, 0); })(this);"

It's neater to put all of this JavaScript code in its own function as the question shows:

OnClientClick="disable(this);"

function disable(button) {
    setTimeout(function () {
        if (Page_IsValid)
            button.disabled = true;
    }, 0);
}

Disabling the button on the client side doesn't disable it on the server side

To overcome this, disable the button on the server side. For example, in the OnClick event handler:

OnClick="Button1_Click"

protected void Button1_Click(object sender, EventArgs e)
{
    ((Button)sender).Enabled = false;
}

Lastly, keep in mind that preventing duplicate button presses doesn't prevent two different users from submitting the same data at the same time. Make sure to account for that on the server side.

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

Seems like IntelliJ IDEA will import missed class automatically, and you can import them by hit Alt + Enter manually.

How do you add an SDK to Android Studio?

I followed almost the same instructions by @Mason G. Zhwiti , but had to instead navigate to this folder to find the SDK:

/Users/{my-username}/Library/Android/sdk

I'm using Android Studio v1.2.2 on Mac OS

How to uninstall jupyter

In my case, I have installed it via pip3 on mac.

pip3 uninstall notebook

Send form data with jquery ajax json

The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.

To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.

$.ajax({
    url: 'test.php',
    type: "POST",
    dataType: 'json',
    data: formToJson($("form")),
    contentType: 'application/json;charset=UTF-8',
    ...
})

How to tell if string starts with a number with Python?

sometimes, you can use regex

>>> import re
>>> re.search('^\s*[0-9]',"0abc")
<_sre.SRE_Match object at 0xb7722fa8>

Undefined symbols for architecture arm64

This issue occurred for me after installing a pod via Podfile and pod install. After trying a bunch of different fixes I finally just imported the Pod manually (dragging the necessary files into my project) and that solved the problem.

How to render a DateTime in a specific format in ASP.NET MVC 3?

My preference is to keep the formatting details with the view and not the viewmodel. So in MVC4/Razor:

@Html.TextBoxFor(model => model.DateTime, "{0:d}");

datetime format reference: http://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.71).aspx

Then I have a JQuery datepicker bound to it, and that put's the date in as a different format...doh!

Looks like I need to set the datepicker's format to the same formatting.

So I'm storing the System.Globalization formatting in a data-* attribute and collecting it when setting up the

@Html.TextBoxFor(
    model => model.DateTime.Date, 
    "{0:d}", 
    new 
    { 
        @class = "datePicker", 
        @data_date_format=System.Globalization.CultureInfo
                          .CurrentUICulture.DateTimeFormat.ShortDatePattern 
    }));

And here's the sucky part: the formats of .net and datepicker do not match, so hackery is needed:

$('.datePicker').each(function(){
    $(this).datepicker({
        dateFormat:$(this).data("dateFormat").toLowerCase().replace("yyyy","yy")
    });
});

that's kind of weak, but should cover a lot of cases.

How do I Alter Table Column datatype on more than 1 column?

Use the following syntax:

  ALTER TABLE your_table
  MODIFY COLUMN column1 datatype,
  MODIFY COLUMN column2 datatype,
  ... ... ... ... ... 
  ... ... ... ... ...

Based on that, your ALTER command should be:

  ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100)

Note that:

  1. There are no second brackets around the MODIFY statements.
  2. I used two separate MODIFY statements for two separate columns.

This is the standard format of the MODIFY statement for an ALTER command on multiple columns in a MySQL table.

Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement

Python datetime - setting fixed hour and minute after using strptime to get day,month,year

Use datetime.replace:

from datetime import datetime
dt = datetime.strptime('26 Sep 2012', '%d %b %Y')
newdatetime = dt.replace(hour=11, minute=59)

How to alias a table in Laravel Eloquent queries (or using Query Builder)?

To use aliases on eloquent models modify your code like this:

Item
    ::from( 'items as items_alias' )
    ->join( 'attachments as att', DB::raw( 'att.item_id' ), '=', DB::raw( 'items_alias.id' ) )
    ->select( DB::raw( 'items_alias.*' ) )
    ->get();

This will automatically add table prefix to table names and returns an instance of Items model. not a bare query result. Adding DB::raw prevents laravel from adding table prefixes to aliases.

How to compare two columns in Excel and if match, then copy the cell next to it

try this formula in column E:

=IF( AND( ISNUMBER(D2), D2=G2), H2, "")

your error is the number test, ISNUMBER( ISMATCH(D2,G:G,0) )

you do check if ismatch is-a-number, (i.e. isNumber("true") or isNumber("false"), which is not!.

I hope you understand my explanation.

How to import a module given the full path?

you can do this using __ import __ and chdir

def import_file(full_path_to_module):
    try:
        import os
        module_dir, module_file = os.path.split(full_path_to_module)
        module_name, module_ext = os.path.splitext(module_file)
        save_cwd = os.getcwd()
        os.chdir(module_dir)
        module_obj = __import__(module_name)
        module_obj.__file__ = full_path_to_module
        globals()[module_name] = module_obj
        os.chdir(save_cwd)
    except Exception as e:
        raise ImportError(e)
    return module_obj


import_file('/home/somebody/somemodule.py')

selecting rows with id from another table

Try this (subquery):

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

Or you can try this (JOIN):

SELECT t.* FROM terms AS t 
   INNER JOIN terms_relation AS tr 
   ON t.id = tr.term_id AND tr.taxonomy = "categ"

If you want to receive all fields from two tables:

SELECT t.id, t.name, t.slug, tr.description, tr.created_at, tr.updated_at 
  FROM terms AS t 
   INNER JOIN terms_relation AS tr 
   ON t.id = tr.term_id AND tr.taxonomy = "categ"

Adjust list style image position?

Here's what I did to get small grey blocks to be on the left side and in the center of the text with an increased lineheight:

line-height:200%;
padding-left:13px;
background-image:url('images/greyblock.gif');
background-repeat:no-repeat;
background-position:left center;

Hope this helps someone :D

How does one get started with procedural generation?

the most important thing is to analyze how roads, cities, blocks and buildings are structured. find out what all eg buildings have in common. look at photos, maps, plans and reality. if you do that you will be one step ahead of people who consider city building as a merely computer-technological matter.

next you should develop solutions on how to create that geometry in tiny, distinct steps. you have to define rules that make up a believable city. if you are into 3d modelling you have to rethink a lot of what you have learned so the computer can follow your instructions in any situation.

in order to not loose track you should set up a lot of operators that are only responsible for little parts of the whole process. that makes debugging, expanding and improving your system much easier. in the next step you should link those operators and check the results by changing parameters.

i have seen too many "city generators" that mainly consist of random-shaped boxes with some window textures on them : (

How to access parent scope from within a custom directive *with own scope* in AngularJS?

Here's a trick I used once: create a "dummy" directive to hold the parent scope and place it somewhere outside the desired directive. Something like:

module.directive('myDirectiveContainer', function () {
    return {
        controller: function ($scope) {
            this.scope = $scope;
        }
    };
});

module.directive('myDirective', function () {
    return {
        require: '^myDirectiveContainer',
        link: function (scope, element, attrs, containerController) {
            // use containerController.scope here...
        }
    };
});

and then

<div my-directive-container="">
    <div my-directive="">
    </div>
</div>

Maybe not the most graceful solution, but it got the job done.

How do I alter the precision of a decimal column in Sql Server?

There may be a better way, but you can always copy the column into a new column, drop it and rename the new column back to the name of the first column.

to wit:

ALTER TABLE MyTable ADD NewColumnName DECIMAL(16, 2);
GO

UPDATE  MyTable
SET     NewColumnName = OldColumnName;
GO

ALTER TABLE CONTRACTS DROP COLUMN OldColumnName;
GO


EXEC sp_rename
    @objname = 'MyTable.NewColumnName',
    @newname = 'OldColumnName',
    @objtype = 'COLUMN'
GO

This was tested on SQL Server 2008 R2, but should work on SQL Server 2000+.

ssh_exchange_identification: Connection closed by remote host under Git bash

We migrated our git host instance/servers this morning to a new data center and while being connected to both: VPN (from remote/home) or when in office network, I got the same error and was not able to connect to clone any GIT repo.

Cloning into 'some_repo_in_git_dev'...
ssh_exchange_identification: Connection closed by remote host
fatal: Could not read from remote repository.

This will help if you are connecting to some or all servers via a jump host server.

Earlier in my ~/.ssh/config file, my setting to connect were:

Host * !ssh.somejumphost.my.company.com
     ProxyCommand ssh -q -W %h:%p ssh.somejumphost.my.company.com

What this means is, for any SSH based connection, it will connect to any * server via the given jump host server except/by ignoring "ssh.somejumphost.my.company.com" server (as we don't want to connect to a jump host via jump host server.

To FIX the issue, all I did was, change the config to ignore git server as well:

Host * !ssh.somejumphost.my.company.com !mycompany-git.server.com !OrMyCompany-some-other-git-instance.server.com
     ProxyCommand ssh -q -W %h:%p ssh.somejumphost.my.company.com

So, now to connect to mycompany-git.server.com while doing git clone (git SSH url), I'm telling SSH not to use a jump host for those two extra git instances/servers.

Fast way of finding lines in one file that are not in another?

This seems quick for me :

comm -1 -3 <(sort file1.txt) <(sort file2.txt) > output.txt

how to add super privileges to mysql database?

On Centos 5 I was getting all sorts of errors trying to make changes to some variable values from the MySQL shell, after having logged in with the proper uid and pw (with root access). The error that I was getting was something like this:

mysql> -- Set some variable value, for example
mysql> SET GLOBAL general_log='ON';
ERROR 1227 (42000): Access denied; you need (at least one of) the SUPER privilege(s) for this operation

In a moment of extreme serendipity I did the following:

OS-Shell> sudo mysql                          # no DB uid, no DB pw

Kindly note that I did not provide the DB uid and password

mysql> show variables;
mysql> -- edit the variable of interest to the desired value, for example
mysql> SET GLOBAL general_log='ON';

It worked like a charm

MySQL remove all whitespaces from the entire column

To replace all spaces :

UPDATE `table` SET `col_name` = REPLACE(`col_name`, ' ', '')

To remove all tabs characters :

UPDATE `table` SET `col_name` = REPLACE(`col_name`, '\t', '' )

To remove all new line characters :

UPDATE `table` SET `col_name` = REPLACE(`col_name`, '\n', '')

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace

To remove first and last space(s) of column :

UPDATE `table` SET `col_name` = TRIM(`col_name`)

http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_trim

Facebook Graph API, how to get users email?

Make sure your Facebook application is published. In order to receive data for email, public_profile and user_friends your app must be made available to public.

You can disable it later for development purposes and still get email field.

Draw text in OpenGL ES

For static text:

  • Generate an image with all words used on your PC (For example with GIMP).
  • Load this as a texture and use it as material for a plane.

For long text that needs to be updated once in a while:

  • Let android draw on a bitmap canvas (JVitela's solution).
  • Load this as material for a plane.
  • Use different texture coordinates for each word.

For a number (formatted 00.0):

  • Generate an image with all numbers and a dot.
  • Load this as material for a plane.
  • Use below shader.
  • In your onDraw event only update the value variable sent to the shader.

    precision highp float;
    precision highp sampler2D;
    
    uniform float uTime;
    uniform float uValue;
    uniform vec3 iResolution;
    
    varying vec4 v_Color;
    varying vec2 vTextureCoord;
    uniform sampler2D s_texture;
    
    void main() {
    
    vec4 fragColor = vec4(1.0, 0.5, 0.2, 0.5);
    vec2 uv = vTextureCoord;
    
    float devisor = 10.75;
    float digit;
    float i;
    float uCol;
    float uRow;
    
    if (uv.y < 0.45) {
        if (uv.x > 0.75) {
            digit = floor(uValue*10.0);
            digit = digit - floor(digit/10.0)*10.0;
            i = 48.0 - 32.0 + digit;
            uRow = floor(i / 10.0);
            uCol = i - 10.0 * uRow;
            fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-1.5) / devisor, uRow / devisor) );
        } else if (uv.x > 0.5) {
            uCol = 4.0;
            uRow = 1.0;
            fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-1.0) / devisor, uRow / devisor) );
        } else if (uv.x > 0.25) {
            digit = floor(uValue);
            digit = digit - floor(digit/10.0)*10.0;
            i = 48.0 - 32.0 + digit;
            uRow = floor(i / 10.0);
            uCol = i - 10.0 * uRow;
            fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-0.5) / devisor, uRow / devisor) );
        } else if (uValue >= 10.0) {
            digit = floor(uValue/10.0);
            digit = digit - floor(digit/10.0)*10.0;
            i = 48.0 - 32.0 + digit;
            uRow = floor(i / 10.0);
            uCol = i - 10.0 * uRow;
            fragColor = texture2D( s_texture, uv / devisor * 2.0 + vec2((uCol-0.0) / devisor, uRow / devisor) );
        } else {
            fragColor = vec4(0.0, 0.0, 0.0, 0.0);
        }
    } else {
        fragColor = vec4(0.0, 0.0, 0.0, 0.0);
    }
    gl_FragColor = fragColor;
    
    }
    

Above code works for a texture atlas where numbers start from 0 at the 7th column of the 2nd row of the font atlas (texture).

Refer to https://www.shadertoy.com/view/Xl23Dw for demonstration (with wrong texture though)

Rename multiple columns by names

names(x)[names(x) %in% c("q","e")]<-c("A","B")

java.util.NoSuchElementException - Scanner reading user input

You need to remove the scanner closing lines: scan.close();

It happened to me before and that was the reason.

Is there an equivalent to e.PageX position for 'touchstart' event as there is for click event?

I tried some of the other answers here, but originalEvent was also undefined. Upon inspection, found a TouchList classed property (as suggested by another poster) and managed to get to pageX/Y this way:

var x = e.changedTouches[0].pageX;

How to write a file or data to an S3 object using boto3

Here's a nice trick to read JSON from s3:

import json, boto3
s3 = boto3.resource("s3").Bucket("bucket")
json.load_s3 = lambda f: json.load(s3.Object(key=f).get()["Body"])
json.dump_s3 = lambda obj, f: s3.Object(key=f).put(Body=json.dumps(obj))

Now you can use json.load_s3 and json.dump_s3 with the same API as load and dump

data = {"test":0}
json.dump_s3(data, "key") # saves json to s3://bucket/key
data = json.load_s3("key") # read json from s3://bucket/key

How to DROP multiple columns with a single ALTER TABLE statement in SQL Server?

ALTER table table_name Drop column column1, Drop column column2,Drop column column3;

for MySQL DB.

Or you can add some column while altering in the same line:

ALTER table table_name Drop column column1, ADD column column2 AFTER column7;

Trigger event on body load complete js/jquery

When the page loads totally (dom, images, ...)

$(window).load(function(){
    // full load
});

When DOM elements load (not necessary all images will be loaded)

$(function(){
    // DOM Ready
});

Then you can trigger any event

$("element").trigger("event");

In UML class diagrams, what are Boundary Classes, Control Classes, and Entity Classes?

Actually, the Robustness Diagrams (or Analysis Diagrams, as they are sometimes called) are just specialized Class Diagrams. They are a part of UML, and have been from the beginning (see Jacobson's book, The Unified Software Development Process - part of the "Three Amigos" series of books). The aforementioned book has a good definition of these three classes on pp 183-185.

Stash only one file out of multiple files that have changed with Git?

When you try to switch between two branches, this situation occurs.

Try to add the files using "git add filepath".

Later execute this line

git stash --keep-index

How do I make a checkbox required on an ASP.NET form?

Scott's answer will work for classes of checkboxes. If you want individual checkboxes, you have to be a little sneakier. If you're just doing one box, it's better to do it with IDs. This example does it by specific check boxes and doesn't require jQuery. It's also a nice little example of how you can get those pesky control IDs into your Javascript.

The .ascx:

<script type="text/javascript">

    function checkAgreement(source, args)
    {                
        var elem = document.getElementById('<%= chkAgree.ClientID %>');
        if (elem.checked)
        {
            args.IsValid = true;
        }
        else
        {        
            args.IsValid = false;
        }
    }

    function checkAge(source, args)
    {
        var elem = document.getElementById('<%= chkAge.ClientID %>');
        if (elem.checked)
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = false;
        }    
    }

</script>

<asp:CheckBox ID="chkAgree" runat="server" />
<asp:Label AssociatedControlID="chkAgree" runat="server">I agree to the</asp:Label>
<asp:HyperLink ID="lnkTerms" runat="server">Terms & Conditions</asp:HyperLink>
<asp:Label AssociatedControlID="chkAgree" runat="server">.</asp:Label>
<br />

<asp:CustomValidator ID="chkAgreeValidator" runat="server" Display="Dynamic"
    ClientValidationFunction="checkAgreement">
    You must agree to the terms and conditions.
    </asp:CustomValidator>

<asp:CheckBox ID="chkAge" runat="server" />
<asp:Label AssociatedControlID="chkAge" runat="server">I certify that I am at least 18 years of age.</asp:Label>        
<asp:CustomValidator ID="chkAgeValidator" runat="server" Display="Dynamic"
    ClientValidationFunction="checkAge">
    You must be 18 years or older to continue.
    </asp:CustomValidator>

And the codebehind:

Protected Sub chkAgreeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgreeValidator.ServerValidate
    e.IsValid = chkAgree.Checked
End Sub

Protected Sub chkAgeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgeValidator.ServerValidate
    e.IsValid = chkAge.Checked
End Sub

How to subtract 30 days from the current date using SQL Server

You can convert it to datetime, and then use DATEADD(DAY, -30, date).

See here.

edit

I suspect many people are finding this question because they want to substract from current date (as is the title of the question, but not what OP intended). The comment of munyul below answers that question more specifically. Since comments are considered ethereal (may be deleted at any given point), I'll repeat it here:

DATEADD(DAY, -30, GETDATE())

Select From all tables - MySQL

Improve to @inno answer

delimiter //

DROP PROCEDURE IF EXISTS get_product;  
CREATE PROCEDURE get_product()
BEGIN
   DECLARE i VARCHAR(100); 
   DECLARE cur1 CURSOR FOR SELECT DISTINCT table_name FROM information_schema.columns WHERE COLUMN_NAME IN ('Product');
   OPEN cur1;

   read_loop: LOOP
       FETCH cur1 INTO i;
    
       SELECT i; -- printing table name
    
       SET @s = CONCAT('select * from ', i, ' where Product like %XYZ%'); 
       PREPARE stmt1 FROM @s;
       EXECUTE stmt1;
       DEALLOCATE PREPARE stmt1;

   END LOOP read_loop;

   CLOSE cur1;
END//

delimiter ;

call get_product();

Symfony 2 EntityManager injection in service

Your class's constructor method should be called __construct(), not __constructor():

public function __construct(EntityManager $entityManager)
{
    $this->em = $entityManager;
}

How do I terminate a thread in C++11?

Tips of using OS-dependent function to terminate C++ thread:

  1. std::thread::native_handle() only can get the thread’s valid native handle type before calling join() or detach(). After that, native_handle() returns 0 - pthread_cancel() will coredump.

  2. To effectively call native thread termination function(e.g. pthread_cancel()), you need to save the native handle before calling std::thread::join() or std::thread::detach(). So that your native terminator always has a valid native handle to use.

More explanations please refer to: http://bo-yang.github.io/2017/11/19/cpp-kill-detached-thread .

Calculate distance between 2 GPS coordinates

Here it is in C# (lat and long in radians):

double CalculateGreatCircleDistance(double lat1, double long1, double lat2, double long2, double radius)
{
    return radius * Math.Acos(
        Math.Sin(lat1) * Math.Sin(lat2)
        + Math.Cos(lat1) * Math.Cos(lat2) * Math.Cos(long2 - long1));
}

If your lat and long are in degrees then divide by 180/PI to convert to radians.

Show row number in row header of a DataGridView

It seems that it doesn't turn it into a string. Try

row.HeaderCell.Value = String.Format("{0}", row.Index + 1);

Creating a PHP header/footer

Besides just using include() or include_once() to include the header and footer, one thing I have found useful is being able to have a custom page title or custom head tags to be included for each page, yet still have the header in a partial include. I usually accomplish this as follows:

In the site pages:

<?php

$PageTitle="New Page Title";

function customPageHeader(){?>
  <!--Arbitrary HTML Tags-->
<?php }

include_once('header.php');

//body contents go here

include_once('footer.php');
?>

And, in the header.php file:

<!doctype html>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <title><?= isset($PageTitle) ? $PageTitle : "Default Title"?></title>
    <!-- Additional tags here -->
    <?php if (function_exists('customPageHeader')){
      customPageHeader();
    }?>
  </head>
  <body>

Maybe a bit beyond the scope of your original question, but it is useful to allow a bit more flexibility with the include.

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

Just do select date(timestamp_column) and you would get the only the date part. Sometimes doing select timestamp_column::date may return date 00:00:00 where it doesn't remove the 00:00:00 part. But I have seen date(timestamp_column) to work perfectly in all the cases. Hope this helps.

Custom Listview Adapter with filter Android

First you create the EditText in the xml file and assign an id, eg con_pag_etPesquisa. After that, we will create two lists, where one is the list view and the other to receive the same content but will remain as a backup. Before moving objects to lists first initializes Them the below:

//Declaring

public EditText etPesquisa;

public ContasPagarAdapter adapterNormal;

public List<ContasPagar> lstBkp;

public List<ContasPagar> lstCp;

//Within the onCreate method, type the following:

etPesquisa = (EditText) findViewById(R.id.con_pag_etPesquisa);

etPesquisa.addTextChangedListener(new TextWatcher(){

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3){
        filter(String.valueOf(cs));
    }
    @Override
    public void beforeTextChanged(CharSequence cs, int arg1, int arg2, int arg3){

    // TODO Auto-generated method stub
    }
    @Override
    public void afterTextChanged(Editable e){

    }

});

//Before moving objects to lists first initializes them as below:

lstCp = new ArrayList<ContasPagar>();

lstBkp = new ArrayList<ContasPagar>();


//When you add objects to the main list, repeat the procedure also for bkp list, as follows:

lstCp.add(cp);

lstBkp.add(cp);


//Now initializes the adapter and let the listener, as follows:

adapterNormal = new ContasPagarAdapter(ContasPagarActivity.this, lstCp);

lvContasPagar.setAdapter(adapterNormal);
                    lvContasPagar.setOnItemClickListener(verificaClickItemContasPagar(lstCp));


//Now create the methods inside actito filter the text entered by the user, as follows:

public void filter(String charText){

    charText = charText.toLowerCase();

    lstCp.clear();

    if (charText.length() == 0){

        lstCp.addAll(lstBkp);

        appendAddItem(lstBkp);

    } 

    else {

        for (int i = 0; i < lstBkp.size(); i++){

            if((lstBkp.get(i).getNome_lancamento() + " - " + String.valueOf(lstBkp.get(i).getCodigo())).toLowerCase().contains(charText)){

                lstCp.add(lstBkp.get(i));

            }

        }

        appendAddItem(lstCp);
    }
}

private void appendAddItem(final List<ContasPagar> novaLista){
    runOnUiThread(new Runnable(){

        @Override
            public void run(){
                adapterNormal.notifyDataSetChanged();               
            }
        });
    }

JFrame in full screen Java

One way is to use the Extended State. This asks the underlying OS to maximize the JFrame.

setExtendedState(getExtendedState() | JFrame.MAXIMIZED_BOTH);

Other approach would be to manually maximize the screen for you requirement.

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(100, 100, (int) dim.getWidth(), (int) dim.getHeight());
setLocationRelativeTo(null);

But this has pitfalls in Ubuntu OS. The work around I found was this.

if (SystemHelper.isUnix()) {
    getContentPane().setPreferredSize(
    Toolkit.getDefaultToolkit().getScreenSize());
    pack();
    setResizable(false);
    show();

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            Point p = new Point(0, 0);
            SwingUtilities.convertPointToScreen(p, getContentPane());
            Point l = getLocation();
            l.x -= p.x;
            l.y -= p.y;
            setLocation(p);
        }
    });
}

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
setBounds(100, 100, (int) dim.getWidth(), (int) dim.getHeight());
setLocationRelativeTo(null);

In Fedora the above problem is not present. But there are complications involved with Gnome or KDE. So better be careful. Hope this helps.

Show DialogFragment with animation growing from a point

If you want to work over APIs you have to do inside your DialogFragemnt->onStart and not inside onCreateDialog

@Override
    public void onStart() 
    {
        if (getDialog() == null) 
        {
            return;
        }

        getDialog().getWindow().setWindowAnimations(
                  R.style.DlgAnimation);

        super.onStart();
    }

JQuery - $ is not defined

It sounds like jQuery isn't loading properly. Which source/version are you using?

Alternatively, it could a be namespace collision, so try using jQuery explicitly instead of using $. If that works, you may like to use noConflict to ensure the other code that's using $ doesn't break.

How to create new folder?

You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:

newpath = r'C:\Program Files\arbitrary' 
if not os.path.exists(newpath):
    os.makedirs(newpath)

If you're trying to make an installer: Windows Installer does a lot of work for you.

Read a file line by line with VB.NET

Like this... I used it to read Chinese characters...

Dim reader as StreamReader = My.Computer.FileSystem.OpenTextFileReader(filetoimport.Text)
Dim a as String

Do
   a = reader.ReadLine
   '
   ' Code here
   '
Loop Until a Is Nothing

reader.Close()

CSS selector for "foo that contains bar"?

No, what you are looking for would be called a parent selector. CSS has none; they have been proposed multiple times but I know of no existing or forthcoming standard including them. You are correct that you would need to use something like jQuery or use additional class annotations to achieve the effect you want.

Here are some similar questions with similar results:

What is the meaning of prepended double colon "::"?

"::" represents scope resolution operator. Functions/methods which have same name can be defined in two different classes. To access the methods of a particular class scope resolution operator is used.

What is the (function() { } )() construct in JavaScript?

An immediately-invoked function expression (IIFE) immediately calls a function. This simply means that the function is executed immediately after the completion of the definition.

Three more common wordings:

// Crockford's preference - parens on the inside
(function() {
  console.log('Welcome to the Internet. Please follow me.');
}());

//The OPs example, parentheses on the outside
(function() {
  console.log('Welcome to the Internet. Please follow me.');
})();

//Using the exclamation mark operator
//https://stackoverflow.com/a/5654929/1175496
!function() {
  console.log('Welcome to the Internet. Please follow me.');
}();

If there are no special requirements for its return value, then we can write:

!function(){}();  // => true
~function(){}(); // => -1
+function(){}(); // => NaN
-function(){}();  // => NaN

Alternatively, it can be:

~(function(){})();
void function(){}();
true && function(){ /* code */ }();
15.0, function(){ /* code */ }();

You can even write:

new function(){ /* code */ }
31.new function(){ /* code */ }() //If no parameters, the last () is not required

Checking if a string can be converted to float in Python

This regex will check for scientific floating point numbers:

^[-+]?(?:\b[0-9]+(?:\.[0-9]*)?|\.[0-9]+\b)(?:[eE][-+]?[0-9]+\b)?$

However, I believe that your best bet is to use the parser in a try.

Convert array of strings to List<string>

From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.

Usage looks like this:

using System.Linq; 

// ...

public void My()
{
    var myArray = new[] { "abc", "123", "zyx" };
    List<string> myList = myArray.ToList();
}

PS. There's also ToArray() method that works in other way.

Using AngularJS date filter with UTC date

An evolved version of ossek solution

Custom filter is more appropriate, then you can use it anywhere in the project

js file

var myApp = angular.module('myApp',[]);

myApp.filter('utcdate', ['$filter','$locale', function($filter, $locale){

    return function (input, format) {
        if (!angular.isDefined(format)) {
            format = $locale['DATETIME_FORMATS']['medium'];
        }

        var date = new Date(input);
        var d = new Date()
        var _utc = new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(),  date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
        return $filter('date')(_utc, format)
    };

 }]);

in template

<p>This will convert UTC time to local time<p>
<span>{{dateTimeInUTC | utcdate :'MMM d, y h:mm:ss a'}}</span>

How to pass values across the pages in ASP.net without using Session

You can use query string to pass value from one page to another..

1.pass the value using querystring

 Response.Redirect("Default3.aspx?value=" + txt.Text + "& number="+n);

2.Retrive the value in the page u want by using any of these methods..

Method1:

    string v = Request.QueryString["value"];
    string n=Request.QueryString["number"];

Method2:

      NameValueCollection v = Request.QueryString;
    if (v.HasKeys())
    {
        string k = v.GetKey(0);
        string n = v.Get(0);
        if (k == "value")
        {
            lbltext.Text = n.ToString();
        }
        if (k == "value1")
        {
            lbltext.Text = "error occured";
        }
    }

NOTE:Method 2 is the fastest method.

How to get the current user in ASP.NET MVC

We can use following code to get the current logged in User in ASP.Net MVC:

var user= System.Web.HttpContext.Current.User.Identity.GetUserName();

Also

var userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; //will give 'Domain//UserName'

Environment.UserName - Will Display format : 'Username'

Write in body request with HttpClient

If your xml is written by java.lang.String you can just using HttpClient in this way

    public void post() throws Exception{
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost("http://www.baidu.com");
        String xml = "<xml>xxxx</xml>";
        HttpEntity entity = new ByteArrayEntity(xml.getBytes("UTF-8"));
        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        String result = EntityUtils.toString(response.getEntity());
    }

pay attention to the Exceptions.

BTW, the example is written by the httpclient version 4.x

How to remove time portion of date in C# in DateTime object only?

The easiest way is something like this and it will return only the date:

var date = DateTime.Now.ToShortDateString();

How to rollback a specific migration?

Migrations change the state of the database using the command

$ bundle exec rake db:migrate

We can undo a single migration step using

  $ bundle exec rake db:rollback

To go all the way back to the beginning, we can use

  $ bundle exec rake db:migrate VERSION=0

As you might guess, substituting any other number for 0 migrates to that version number, where the version numbers come from listing the migrations sequentially

Mongoose, Select a specific field with find

Exclude

Below code will retrieve all fields other than password within each document:

const users = await UserModel.find({}, {
  password: 0 
});
console.log(users);

Output

[
  {
    "_id": "5dd3fb12b40da214026e0658",
    "email": "[email protected]"
  }
]

Include

Below code will only retrieve email field within each document:

const users = await UserModel.find({}, {
  email: 1
});
console.log(users);

Output

[
  {
    "email": "[email protected]"
  }
]

Add zero-padding to a string

myInt.ToString("D4");

What is the difference between Serialization and Marshaling?

Both do one thing in common - that is serializing an Object. Serialization is used to transfer objects or to store them. But:

  • Serialization: When you serialize an object, only the member data within that object is written to the byte stream; not the code that actually implements the object.
  • Marshalling: Term Marshalling is used when we talk about passing Object to remote objects(RMI). In Marshalling Object is serialized(member data is serialized) + Codebase is attached.

So Serialization is part of Marshalling.

CodeBase is information that tells the receiver of Object where the implementation of this object can be found. Any program that thinks it might ever pass an object to another program that may not have seen it before must set the codebase, so that the receiver can know where to download the code from, if it doesn't have the code available locally. The receiver will, upon deserializing the object, fetch the codebase from it and load the code from that location.

Insert image after each list item

Try this:

ul li a:after {
    display: block;
    content: "";
    width: 3px;
    height: 5px;
    background: transparent url('../images/small_triangle.png') no-repeat;
}

You need the content: ""; declaration to give your generated element content, even if that content is "nothing".

Also, I fixed the syntax/ordering of your background declaration.

C++ STL Vectors: Get iterator from index?

way mentioned by @dirkgently ( v.begin() + index ) nice and fast for vectors

but std::advance( v.begin(), index ) most generic way and for random access iterators works constant time too.

EDIT
differences in usage:

std::vector<>::iterator it = ( v.begin() + index );

or

std::vector<>::iterator it = v.begin();
std::advance( it, index );

added after @litb notes.

php delete a single file in directory

The script you downloaded lists the content of a specified folder. You probably put the unlink - call in one of the while-loops that list the files.

EDIT - Now that you posted your code:

echo '<a href="'.unlink($FileLink).'"><img src="images/icons/delete.gif"></a></td>';

Doing this calls the unlink-function each time the line is written, deleting your file. You have to write a link to a script that contains a delete function and pass some parameter that tells your script what to delete.

Example:

<a href="/path/to/script.php?delete='. $FileLink .'">delete</a>

You should not pass the path to a file this script and just delete it though, because malevolent being might use it to just delete everything or do other evil things.

Is if(document.getElementById('something')!=null) identical to if(document.getElementById('something'))?

jquery will provide you with this and more ...

if($("#something").val()){ //do stuff}

It took me a couple of days to pick it up, but it provides you with you with so much more functionality. An example below.

jQuery(document).ready(function() {
    /* finds closest element with class divright/left and 
    makes all checkboxs inside that div class the same as selectAll...
    */
        $("#selectAll").click(function() {
        $(this).closest('.divright').find(':checkbox').attr('checked', this.checked);
    });
});

jQuery - Dynamically Create Button and Attach Event Handler

You can either use onclick inside the button to ensure the event is preserved, or else attach the button click handler by finding the button after it is inserted. The test.html() call will not serialize the event.

What exactly does an #if 0 ..... #endif block do?

It permanently comments out that code so the compiler will never compile it.

The coder can later change the #ifdef to have that code compile in the program if he wants to.

It's exactly like the code doesn't exist.

Remove padding from columns in Bootstrap 3

Wrap your columns in a .row and add to that div a class called "no-gutter"

<div class="container">
  <div class="row no-gutter">
    <h2>OntoExplorer<span style="color:#b92429">.</span></h2>

    <div class="col-md-4">
        <div class="widget">
            <div class="widget-header">
                <h3>Dimensions</h3>
            </div>
            <div class="widget-content">
            </div>
        </div>
    </div>

    <div class="col-md-8">
        <div class="widget">
            <div class="widget-header">
                <h3>Results</h3>
            </div>
            <div class="widget-content">
            </div>
        </div>
    </div>
</div>

Then paste below contents to your CSS file

.row.no-gutter {
  margin-left: 0;
  margin-right: 0;
}

.row.no-gutter [class*='col-']:not(:first-child),
.row.no-gutter [class*='col-']:not(:last-child) {
  padding-right: 0;
  padding-left: 0;
}

vbscript output to console

I came across this post and went back to an approach that I used some time ago which is similar to @MadAntrax's.

The main difference is that it uses a VBScript user-defined class to wrap all the logic for switching to CScript and outputting text to the console, so it makes the main script a bit cleaner.

This assumes that your objective is to stream output to the console, rather than having output go to message boxes.

The cCONSOLE class is below. To use it, include the complete class at the end of your script, and then instantiate it right at the beginning of the script. Here is an example:

    Option Explicit

'// Instantiate the console object, this automatically switches to CSCript if required
Dim CONS: Set CONS = New cCONSOLE

'// Now we can use the Consol object to write to and read from the console
With CONS

    '// Simply write a line
     .print "CSCRIPT Console demo script"

     '// Arguments are passed through correctly, if present
     .Print "Arg count=" & wscript.arguments.count

     '// List all the arguments on the console log
     dim ix
     for ix = 0 to wscript.arguments.count -1
        .print "Arg(" & ix & ")=" & wscript.arguments(ix)
     next

     '// Prompt for some text from the user
     dim sMsg : sMsg = .prompt( "Enter any text:" )

     '// Write out the text in a box
     .Box sMsg

     '// Pause with the message "Hit enter to continue"
     .Pause

End With     




'= =========== End of script - the cCONSOLE class code follows here

Here is the code for the cCONSOLE class

     CLASS cCONSOLE
 '= =================================================================
 '= 
 '=    This class provides automatic switch to CScript and has methods
 '=    to write to and read from the CSCript console. It transparently
 '=    switches to CScript if the script has been started in WScript.
 '=
 '= =================================================================

    Private oOUT
    Private oIN


    Private Sub Class_Initialize()
    '= Run on creation of the cCONSOLE object, checks for cScript operation


        '= Check to make sure we are running under CScript, if not restart
        '= then run using CScript and terminate this instance.
        dim oShell
        set oShell = CreateObject("WScript.Shell")

        If InStr( LCase( WScript.FullName ), "cscript.exe" ) = 0 Then
            '= Not running under CSCRIPT

            '= Get the arguments on the command line and build an argument list
            dim ArgList, IX
            ArgList = ""

            For IX = 0 to wscript.arguments.count - 1
                '= Add the argument to the list, enclosing it in quotes
                argList = argList & " """ & wscript.arguments.item(IX) & """"
            next

            '= Now restart with CScript and terminate this instance
            oShell.Run "cscript.exe //NoLogo """ & WScript.ScriptName & """ " & arglist
            WScript.Quit

        End If

        '= Running under CScript so OK to continue
        set oShell = Nothing

        '= Save references to stdout and stdin for use with Print, Read and Prompt
        set oOUT = WScript.StdOut
        set oIN = WScript.StdIn

        '= Print out the startup box 
            StartBox
            BoxLine Wscript.ScriptName
            BoxLine "Started at " & Now()
            EndBox


    End Sub

    '= Utility methods for writing a box to the console with text in it

            Public Sub StartBox()

                Print "  " & String(73, "_") 
                Print " |" & Space(73) & "|"
            End Sub

            Public Sub BoxLine(sText)

                Print Left(" |" & Centre( sText, 74) , 75) & "|"
            End Sub

            Public Sub EndBox()
                Print " |" & String(73, "_") & "|"
                Print ""
            End Sub

            Public Sub Box(sMsg)
                StartBox
                BoxLine sMsg
                EndBox
            End Sub

    '= END OF Box utility methods


            '= Utility to center given text padded out to a certain width of text
            '= assuming font is monospaced
            Public Function Centre(sText, nWidth)
                dim iLen
                iLen = len(sText)

                '= Check for overflow
                if ilen > nwidth then Centre = sText : exit Function

                '= Calculate padding either side
                iLen = ( nWidth - iLen ) / 2

                '= Generate text with padding
                Centre = left( space(iLen) & sText & space(ilen), nWidth )
            End Function



    '= Method to write a line of text to the console
    Public Sub Print( sText )

        oOUT.WriteLine sText
    End Sub

    '= Method to prompt user input from the console with a message
    Public Function Prompt( sText )
        oOUT.Write sText
        Prompt = Read()
    End Function

    '= Method to read input from the console with no prompting
    Public Function Read()
        Read = oIN.ReadLine
    End Function

    '= Method to provide wait for n seconds
    Public Sub Wait(nSeconds)
        WScript.Sleep  nSeconds * 1000 
    End Sub

    '= Method to pause for user to continue
    Public Sub Pause
        Prompt "Hit enter to continue..."
    End Sub


 END CLASS

Returning binary file from controller in ASP.NET Web API

The overload that you're using sets the enumeration of serialization formatters. You need to specify the content type explicitly like:

httpResponseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");

Spark - repartition() vs coalesce()

But also you should make sure that, the data which is coming coalesce nodes should have highly configured, if you are dealing with huge data. Because all the data will be loaded to those nodes, may lead memory exception. Though reparation is costly, i prefer to use it. Since it shuffles and distribute the data equally.

Be wise to select between coalesce and repartition.

static and extern global variables in C and C++

When you #include a header, it's exactly as if you put the code into the source file itself. In both cases the varGlobal variable is defined in the source so it will work no matter how it's declared.

Also as pointed out in the comments, C++ variables at file scope are not static in scope even though they will be assigned to static storage. If the variable were a class member for example, it would need to be accessible to other compilation units in the program by default and non-class members are no different.

How to write into a file in PHP?

I use the following code to write files on my web directory.

write_file.html

<form action="file.php"method="post">
<textarea name="code">Code goes here</textarea>
<input type="submit"value="submit">
</form>

write_file.php

<?php
// strip slashes before putting the form data into target file
$cd = stripslashes($_POST['code']);

// Show the msg, if the code string is empty
if (empty($cd))
    echo "Nothing to write";

// if the code string is not empty then open the target file and put form data in it
else
{
    $file = fopen("demo.php", "w");
    echo fwrite($file, $cd);

    // show a success msg 
    echo "data successfully entered";
    fclose($file);
}
?>

This is a working script. be sure to change the url in form action and the target file in fopen() function if you want to use it on your site.

Good luck.

Open link in new tab or window

set the target attribute of your <a> element to "_tab"

EDIT: It works, however W3Schools says there is no such target attribute: http://www.w3schools.com/tags/att_a_target.asp

EDIT2: From what I've figured out from the comments. setting target to _blank will take you to a new tab or window (depending on your browser settings). Typing anything except one of the ones below will create a new tab group (I'm not sure how these work):

_blank  Opens the linked document in a new window or tab
_self   Opens the linked document in the same frame as it was clicked (this is default)
_parent Opens the linked document in the parent frame
_top    Opens the linked document in the full body of the window
framename   Opens the linked document in a named frame

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

How to replace text in a column of a Pandas dataframe?

In addition, for those looking to replace more than one character in a column, you can do it using regular expressions:

import re
chars_to_remove = ['.', '-', '(', ')', '']
regular_expression = '[' + re.escape (''. join (chars_to_remove)) + ']'

df['string_col'].str.replace(regular_expression, '', regex=True)

How to make exe files from a node.js app?

I did find any of these solutions met my requirements, so made my own version of node called node2exe that does this. It's available from https://github.com/areve/node2exe

How do I plot list of tuples in Python?

With gnuplot using gplot.py

from gplot import *

l = [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08), 
 (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09), 
 (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)]

gplot.log('y')
gplot(*zip(*l))

enter image description here

How do I use SELECT GROUP BY in DataTable.Select(Expression)?

DataTable's Select method only supports simple filtering expressions like {field} = {value}. It does not support complex expressions, let alone SQL/Linq statements.

You can, however, use Linq extension methods to extract a collection of DataRows then create a new DataTable.

dt = dt.AsEnumerable()
       .GroupBy(r => new {Col1 = r["Col1"], Col2 = r["Col2"]})
       .Select(g => g.OrderBy(r => r["PK"]).First())
       .CopyToDataTable();

overlay opaque div over youtube iframe

Hmm... what's different this time? http://jsfiddle.net/fdsaP/2/

Renders in Chrome fine. Do you need it cross-browser? It really helps being specific.

EDIT: Youtube renders the object and embed with no explicit wmode set, meaning it defaults to "window" which means it overlays everything. You need to either:


a) Host the page that contains the object/embed code yourself and add wmode="transparent" param element to object and attribute to embed if you choose to serve both elements

b) Find a way for youtube to specify those.


JPA Hibernate One-to-One relationship

Try this

@Entity

@Table(name="tblperson")

public class Person {

public int id;

public OtherInfo otherInfo;
@Id //Here Id is autogenerated
@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
    return id;
}
public void setId(int id) {
    this.id = id;
}

@OneToOne(cascade = CascadeType.ALL,targetEntity=OtherInfo.class)
@JoinColumn(name="otherInfo_id") //there should be a column otherInfo_id in Person
public OtherInfo getOtherInfo() {
    return otherInfo;
}
public void setOtherInfo(OtherInfo otherInfo) {
    this.otherInfo= otherInfo;
}
rest of attributes ...
}


@Entity

@Table(name="tblotherInfo")

public class OtherInfo {

private int id;

private Person person;

@Id

@Column(name="id")
@GeneratedValue(strategy=GenerationType.AUTO)
public Long getId() {
    return id;
}
public void setId(Long id) {
    this.id = id;
}

  @OneToOne(mappedBy="OtherInfo",targetEntity=Person.class)   
public College getPerson() {
    return person;
}
public void setPerson(Person person) {
    this.person = person;
}    
 rest of attributes ...
}

Determine .NET Framework version for dll

You can use ILDASM...

ildasm.exe C:\foo.dll /metadata[=MDHEADER] /text /noil

and check for the 'Metadata section' in the output. It would be something like this:

Metadata section: 0x424a5342, version: 1.1, extra: 0, version len: 12, version: v4.0.30319

The 'version' tag will tell you the .NET Framework version. In the above example it is 4.0.30319

Calling a rest api with username and password - how to

You can also use the RestSharp library for example

var userName = "myuser";
var password = "mypassword";
var host = "170.170.170.170:333";
var client = new RestClient("https://" + host + "/method1");            
client.Authenticator = new HttpBasicAuthenticator(userName, password);            
var request = new RestRequest(Method.POST); 
request.AddHeader("Accept", "application/json");
request.AddHeader("Cache-Control", "no-cache");
request.AddHeader("Content-Type", "application/json");            
request.AddParameter("application/json","{}",ParameterType.RequestBody);
IRestResponse response = client.Execute(request);

How to check if a file exists before creating a new file

The easiest way to do this is using ios :: noreplace.

What is the difference between npm install and npm run build?

The main difference is ::

npm install is a npm cli-command which does the predefined thing i.e, as written by Churro, to install dependencies specified inside package.json

npm run command-name or npm run-script command-name ( ex. npm run build ) is also a cli-command predefined to run your custom scripts with the name specified in place of "command-name". So, in this case npm run build is a custom script command with the name "build" and will do anything specified inside it (for instance echo 'hello world' given in below example package.json).

Ponits to note::

  1. One more thing, npm build and npm run build are two different things, npm run build will do custom work written inside package.json and npm build is a pre-defined script (not available to use directly)

  2. You cannot specify some thing inside custom build script (npm run build) script and expect npm build to do the same. Try following thing to verify in your package.json:

    { "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build":"echo 'hello build'" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": {}, "dependencies": {} }

and run npm run build and npm build one by one and you will see the difference. For more about commands kindly follow npm documentation.

Cheers!!

Define a struct inside a class in C++

The other answers here have demonstrated how to define structs inside of classes. There’s another way to do this, and that’s to declare the struct inside the class, but define it outside. This can be useful, for example, if the struct is decently complex and likely to be used standalone in a way that would benefit from being described in detail somewhere else.

The syntax for this is as follows:

class Container {

    ...

    struct Inner; // Declare, but not define, the struct.

    ...

};

struct Container::Inner {
   /* Define the struct here. */
};

You more commonly would see this in the context of defining nested classes rather than structs (a common example would be defining an iterator type for a collection class), but I thought for completeness it would be worth showing off here.

Connecting to TCP Socket from browser using javascript

In order to achieve what you want, you would have to write two applications (in either Java or Python, for example):

  1. Bridge app that sits on the client's machine and can deal with both TCP/IP sockets and WebSockets. It will interact with the TCP/IP socket in question.

  2. Server-side app (such as a JSP/Servlet WAR) that can talk WebSockets. It includes at least one HTML page (including server-side processing code if need be) to be accessed by a browser.

It should work like this

  1. The Bridge will open a WS connection to the web app (because a server can't connect to a client).
  2. The Web app will ask the client to identify itself
  3. The bridge client sends some ID information to the server, which stores it in order to identify the bridge.
    1. The browser-viewable page connects to the WS server using JS.
    2. Repeat step 3, but for the JS-based page
    3. The JS-based page sends a command to the server, including to which bridge it must go.
    4. The server forwards the command to the bridge.
    5. The bridge opens a TCP/IP socket and interacts with it (sends a message, gets a response).
    6. The Bridge sends a response to the server through the WS
    7. The WS forwards the response to the browser-viewable page
    8. The JS processes the response and reacts accordingly
    9. Repeat until either client disconnects/unloads

Note 1: The above steps are a vast simplification and do not include information about error handling and keepAlive requests, in the event that either client disconnects prematurely or the server needs to inform clients that it is shutting down/restarting.

Note 2: Depending on your needs, it might be possible to merge these components into one if the TCP/IP socket server in question (to which the bridge talks) is on the same machine as the server app.

Execute specified function every X seconds

The most beginner-friendly solution is:

Drag a Timer from the Toolbox, give it a Name, set your desired Interval, and set "Enabled" to True. Then double-click the Timer and Visual Studio (or whatever you are using) will write the following code for you:

private void wait_Tick(object sender, EventArgs e)
{
    refreshText(); // Add the method you want to call here.
}

No need to worry about pasting it into the wrong code block or something like that.

The OutputPath property is not set for this project

I have:

  1. Right-click on project with issue -> Unload Project
  2. Right-click on project and choose Edit *.csproj
  3. Copy-paste the configuration from existing configuration which works with specific name and targeting platform (I had Release | x64):

    <PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
      <OutputPath>bin\x64\Release\</OutputPath>
      <DefineConstants>TRACE</DefineConstants>
      <Optimize>true</Optimize>
      <DebugType>pdbonly</DebugType>
      <PlatformTarget>x64</PlatformTarget>
      <ErrorReport>prompt</ErrorReport>
      <CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
      <Prefer32Bit>true</Prefer32Bit>
    </PropertyGroup>
    
  4. Right-click project -> Reload Project
  5. Rebuild project/solution

How to add a href link in PHP?

There is no need to invoke PHP for this. Just put it directly into the HTML:

<a href="http://www.example.com/">...

MySQL Delete all rows from table and reset ID to zero

If you cannot use TRUNCATE (e.g. because of foreign key constraints) you can use an alter table after deleting all rows to restart the auto_increment:

ALTER TABLE mytable AUTO_INCREMENT = 1

jQuery datepicker to prevent past date

If you are dealing with a previously bound date picker then setting

$("#datepicker").datepicker({ minDate: 0 });

will not work. That syntax is applicable only when you are creating the widget.

To set min date for a bound date picker use the following:

$("#datePicker").datepicker("option", "minDate", 0);

Convert pyQt UI to python

The question has already been answered, but if you are looking for a shortcut during development, including this at the top of your python script will save you some time but mostly let you forget about actually having to make the conversion.

import os #Used in Testing Script
os.system("pyuic4 -o outputFile.py inpuiFile.ui")

element not interactable exception in selenium web automation

If it's working in the debug, then wait must be the proper solution.
I will suggest to use the explicit wait, as given below:

WebDriverWait wait = new WebDriverWait(new ChromeDriver(), 5);
wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("#Passwd")));

Python: Finding differences between elements of a list

In the upcoming Python 3.10 release schedule, with the new pairwise function it's possible to slide through pairs of elements and thus map on rolling pairs:

from itertools import pairwise

[y-x for (x, y) in pairwise([1, 3, 6, 7])]
# [2, 3, 1]

The intermediate result being:

pairwise([1, 3, 6, 7])
# [(1, 3), (3, 6), (6, 7)]

Editing the date formatting of x-axis tick labels in matplotlib

While the answer given by Paul H shows the essential part, it is not a complete example. On the other hand the matplotlib example seems rather complicated and does not show how to use days.

So for everyone in need here is a full working example:

from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.dates import DateFormatter

myDates = [datetime(2012,1,i+3) for i in range(10)]
myValues = [5,6,4,3,7,8,1,2,5,4]
fig, ax = plt.subplots()
ax.plot(myDates,myValues)

myFmt = DateFormatter("%d")
ax.xaxis.set_major_formatter(myFmt)

## Rotate date labels automatically
fig.autofmt_xdate()
plt.show()

Retrieving the first digit of a number

int number = 534;
int firstDigit = number/100; 

( / ) operator in java divide the numbers without considering the reminder so when we divide 534 by 100 , it gives us (5) .

but if you want to get the last number , you can use (%) operator

    int lastDigit = number%10; 

which gives us the reminder of the division , so 534%10 , will yield the number 4 .

What replaces cellpadding, cellspacing, valign, and align in HTML5 tables?

Alternatively, can use for particular table

 <table style="width:1000px; height:100px;">
    <tr>
        <td align="center" valign="top">Text</td> //Remove it
        <td class="tableFormatter">Text></td>
    </tr>
</table>

Add this css in external file

.tableFormatter
{
width:100%;
vertical-align:top;
text-align:center;
}

How do I get rid of an element's offset using CSS?

define margin and padding for the element is facing the problem:

#element_id {margin: 0; padding: 0}  

and see if problem exists. IE renders the page with to more unwanted inheritance. you should stop it from doing so.

List and kill at jobs on UNIX

First

ps -ef

to list all processes. Note the the process number of the one you want to kill. Then

kill 1234

were you replace 1234 with the process number that you want.

Alternatively, if you are absolutely certain that there is only one process with a particular name, or you want to kill multiple processes which share the same name

killall processname

How can I add a new column and data to a datatable that already contains data?

Here is an alternate solution to reduce For/ForEach looping, this would reduce looping time and updates quickly :)

 dt.Columns.Add("MyRow", typeof(System.Int32));
 dt.Columns["MyRow"].Expression = "'0'";

python JSON only get keys in first level

for key in data.keys():
    print key

How to prepare a Unity project for git?

Since Unity 4.3 you also have to enable External option from preferences, so full setup process looks like:

  1. Enable External option in Unity ? Preferences ? Packages ? Repository
  2. Switch to Hidden Meta Files in Editor ? Project Settings ? Editor ? Version Control Mode
  3. Switch to Force Text in Editor ? Project Settings ? Editor ? Asset Serialization Mode
  4. Save scene and project from File menu

Note that the only folders you need to keep under source control are Assets and ProjectSettigns.

More information about keeping Unity Project under source control you can find in this post.

is not JSON serializable

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.

Does C have a "foreach" loop construct?

There is no foreach in C.

You can use a for loop to loop through the data but the length needs to be know or the data needs to be terminated by a know value (eg. null).

char* nullTerm;
nullTerm = "Loop through my characters";

for(;nullTerm != NULL;nullTerm++)
{
    //nullTerm will now point to the next character.
}

How to do joins in LINQ on multiple fields in single join

The solution with the anonymous type should work fine. LINQ can only represent equijoins (with join clauses, anyway), and indeed that's what you've said you want to express anyway based on your original query.

If you don't like the version with the anonymous type for some specific reason, you should explain that reason.

If you want to do something other than what you originally asked for, please give an example of what you really want to do.

EDIT: Responding to the edit in the question: yes, to do a "date range" join, you need to use a where clause instead. They're semantically equivalent really, so it's just a matter of the optimisations available. Equijoins provide simple optimisation (in LINQ to Objects, which includes LINQ to DataSets) by creating a lookup based on the inner sequence - think of it as a hashtable from key to a sequence of entries matching that key.

Doing that with date ranges is somewhat harder. However, depending on exactly what you mean by a "date range join" you may be able to do something similar - if you're planning on creating "bands" of dates (e.g. one per year) such that two entries which occur in the same year (but not on the same date) should match, then you can do it just by using that band as the key. If it's more complicated, e.g. one side of the join provides a range, and the other side of the join provides a single date, matching if it falls within that range, that would be better handled with a where clause (after a second from clause) IMO. You could do some particularly funky magic by ordering one side or the other to find matches more efficiently, but that would be a lot of work - I'd only do that kind of thing after checking whether performance is an issue.

file_get_contents behind a proxy?

Depending on how the proxy login works stream_context_set_default might help you.

$context  = stream_context_set_default(
  array(
    'http'=>array(
      'header'=>'Authorization: Basic ' . base64_encode('username'.':'.'userpass')
    )
  )
);
$result = file_get_contents('http://..../...');

Java - checking if parseInt throws exception

You can use the try..catch statement in java, to capture an exception that may arise from Integer.parseInt().

Example:

try {
  int i = Integer.parseint(stringToParse);
  //parseInt succeded
} catch(Exception e)
{
   //parseInt failed
}

how to bold words within a paragraph in HTML/CSS?

I know this question is old but I ran across it and I know other people might have the same problem. All these answers are okay but do not give proper detail or actual TRUE advice.

When wanting to style a specific section of a paragraph use the span tag.

<p><span style="font-weight:900">Andy Warhol</span> (August 6, 1928 - February 22, 1987) 

was an American artist who was a leading figure in the visual art movement known as pop 

art.</p>

Andy Warhol (August 6, 1928 - February 22, 1987) was an American artist who was a leading figure in the visual art movement known as pop art.

As the code shows, the span tag styles on the specified words: "Andy Warhol". You can further style a word using any CSS font styling codes.

{font-weight; font-size; text-decoration; font-family; margin; color}, etc. 

Any of these and more can be used to style a word, group of words, or even specified paragraphs without having to add a class to the CSS Style Sheet Doc. I hope this helps someone!

EditText, inputType values (xml)

You can use the properties tab in eclipse to set various values.

here are all the possible values

  • none
  • text
  • textCapCharacters
  • textCapWords
  • textCapSentences
  • textAutoCorrect
  • textAutoComplete
  • textMultiLine
  • textImeMultiLine
  • textNoSuggestions
  • textUri
  • textEmailAddress
  • textEmailSubject
  • textShortMessage
  • textLongMessage
  • textPersonName
  • textPostalAddress
  • textPassword
  • textVisiblePassword
  • textWebEditText
  • textFilter
  • textPhonetic
  • textWebEmailAddress
  • textWebPassword
  • number
  • numberSigned
  • numberDecimal
  • numberPassword
  • phone
  • datetime
  • date
  • time

Check here for explanations: http://developer.android.com/reference/android/widget/TextView.html#attr_android:inputType

Is it possible to compile a program written in Python?

I think Compiling Python Code would be a good place to start:

Python source code is automatically compiled into Python byte code by the CPython interpreter. Compiled code is usually stored in PYC (or PYO) files, and is regenerated when the source is updated, or when otherwise necessary.

To distribute a program to people who already have Python installed, you can ship either the PY files or the PYC files. In recent versions, you can also create a ZIP archive containing PY or PYC files, and use a small “bootstrap script” to add that ZIP archive to the path.

To “compile” a Python program into an executable, use a bundling tool, such as Gordon McMillan’s installer (alternative download) (cross-platform), Thomas Heller’s py2exe (Windows), Anthony Tuininga’s cx_Freeze (cross-platform), or Bob Ippolito’s py2app (Mac). These tools puts your modules and data files in some kind of archive file, and creates an executable that automatically sets things up so that modules are imported from that archive. Some tools can embed the archive in the executable itself.

Replace special characters in a string with _ (underscore)

string = string.replace(/[&\/\\#,+()$~%.'":*?<>{}]/g,'_');

Alternatively, to change all characters except numbers and letters, try:

string = string.replace(/[^a-zA-Z0-9]/g,'_');

AngularJS dynamic routing

Here is another solution that works good.

(function() {
    'use strict';

    angular.module('cms').config(route);
    route.$inject = ['$routeProvider'];

    function route($routeProvider) {

        $routeProvider
            .when('/:section', {
                templateUrl: buildPath
            })
            .when('/:section/:page', {
                templateUrl: buildPath
            })
            .when('/:section/:page/:task', {
                templateUrl: buildPath
            });



    }

    function buildPath(path) {

        var layout = 'layout';

        angular.forEach(path, function(value) {

            value = value.charAt(0).toUpperCase() + value.substring(1);
            layout += value;

        });

        layout += '.tpl';

        return 'client/app/layouts/' + layout;

    }

})();

Error: Cannot find module 'webpack'

On windows, I have observed that this issue shows up if you do not have administrative rights (i.e., you are not a local administrator) on the machine.

As someone else suggested, the solution seems to be to install locally by not using the -g hint.

C# Parsing JSON array of objects

string jsonData1=@"[{""name"":""0"",""price"":""40"",""count"":""1"",""productId"":""4"",""catid"":""4"",""productTotal"":""40"",""orderstatus"":""0"",""orderkey"":""123456789""}]";

                  string jsonData = jsonData1.Replace("\"", "");


                  DataSet ds = new DataSet();
                  DataTable dt = new DataTable();
       JArray array= JArray.Parse(jsonData);

couldnot parse , if the vaule is a string..

look at name : meals , if name : 1 then it will parse

HTML5 textarea placeholder not appearing

This one has always been a gotcha for me and many others. In short, the opening and closing tags for the <textarea> element must be on the same line, otherwise a newline character occupies it. The placeholder will therefore not be displayed since the input area contains content (a newline character is, technically, valid content).

Good:

<textarea></textarea>

Bad:

<textarea>
</textarea>

Update (2020)

This is not true anymore, according to the HTML5 parsing spec:

If the next token is a U+000A LINE FEED (LF) character token, 
then ignore that token and move on to the next one. (Newlines 
at the start of textarea elements are ignored as an authoring 
convenience.)

You might still have trouble if you editor insists on ending lines with CRLF, though.

Changing Background Image with CSS3 Animations

Your code can work well with some adaptations :

div {
  background-position: 50% 100%;
  background-repeat: no-repeat;
  background-size: contain;
  animation: animateSectionBackground infinite 240s;
}

@keyframes animateSectionBackground {
  00%, 11% { background-image: url(/assets/images/bg-1.jpg); }
  12%, 24% { background-image: url(/assets/images/bg-2.jpg); }
  25%, 36% { background-image: url(/assets/images/bg-3.jpg); }
  37%, 49% { background-image: url(/assets/images/bg-4.jpg); }
  50%, 61% { background-image: url(/assets/images/bg-5.jpg); }
  62%, 74% { background-image: url(/assets/images/bg-6.jpg); }
  75%, 86% { background-image: url(/assets/images/bg-7.jpg); }
  87%, 99% { background-image: url(/assets/images/bg-8.jpg); }
}

Here is the explanation of the percentage to suit your situation:

First you need to calculate the "chunks". If you had 8 differents background, you need to do : 100% / 8 = 12.5% (to simplify you can let fall the decimals) => 12%

After that you obtain that :

@keyframes animateSectionBackground {
  00% { background-image: url(/assets/images/bg-1.jpg); }
  12% { background-image: url(/assets/images/bg-2.jpg); }
  25% { background-image: url(/assets/images/bg-3.jpg); }
  37% { background-image: url(/assets/images/bg-4.jpg); }
  50% { background-image: url(/assets/images/bg-5.jpg); }
  62% { background-image: url(/assets/images/bg-6.jpg); }
  75% { background-image: url(/assets/images/bg-7.jpg); }
  87% { background-image: url(/assets/images/bg-8.jpg); }
}

If you execute this code, you will see the transition will be permanantly. If you want the backgrounds stay fixed while a moment, you can do like this :

@keyframes animateSectionBackground {
  00%, 11% { background-image: url(/assets/images/bg-1.jpg); }
  12%, 24% { background-image: url(/assets/images/bg-2.jpg); }
  25%, 36% { background-image: url(/assets/images/bg-3.jpg); }
  37%, 49% { background-image: url(/assets/images/bg-4.jpg); }
  50%, 61% { background-image: url(/assets/images/bg-5.jpg); }
  62%, 74% { background-image: url(/assets/images/bg-6.jpg); }
  75%, 86% { background-image: url(/assets/images/bg-7.jpg); }
  87%, 99% { background-image: url(/assets/images/bg-8.jpg); }
}

That mean you want :

  • bg-1 stay fixed from 00% to 11%
  • bg-2 stay fixed from 12% to 24%
  • etc

By putting 11%, the transtion duration will be 1% (12% - 11% = 1%). 1% of 240s (total duration) => 2.4 seconds.

You can adapt according to your needs.

PHP: How to use array_filter() to filter array keys?

PHP 5.6 introduced a third parameter to array_filter(), flag, that you can set to ARRAY_FILTER_USE_KEY to filter by key instead of value:

$my_array = ['foo' => 1, 'hello' => 'world'];
$allowed  = ['foo', 'bar'];
$filtered = array_filter(
    $my_array,
    function ($key) use ($allowed) {
        return in_array($key, $allowed);
    },
    ARRAY_FILTER_USE_KEY
);

Clearly this isn't as elegant as array_intersect_key($my_array, array_flip($allowed)), but it does offer the additional flexibility of performing an arbitrary test against the key, e.g. $allowed could contain regex patterns instead of plain strings.

You can also use ARRAY_FILTER_USE_BOTH to have both the value and the key passed to your filter function. Here's a contrived example based upon the first, but note that I'd not recommend encoding filtering rules using $allowed this way:

$my_array = ['foo' => 1, 'bar' => 'baz', 'hello' => 'wld'];
$allowed  = ['foo' => true, 'bar' => true, 'hello' => 'world'];
$filtered = array_filter(
    $my_array,
    function ($val, $key) use ($allowed) { // N.b. $val, $key not $key, $val
        return isset($allowed[$key]) && (
            $allowed[$key] === true || $allowed[$key] === $val
        );
    },
    ARRAY_FILTER_USE_BOTH
); // ['foo' => 1, 'bar' => 'baz']

Where are Magento's log files located?

You can find them in /var/log within your root Magento installation

There will usually be two files by default, exception.log and system.log.

If the directories or files don't exist, create them and give them the correct permissions, then enable logging within Magento by going to System > Configuration > Developer > Log Settings > Enabled = Yes

Is there an exponent operator in C#?

A good power function would be

public long Power(int number, int power) {
    if (number == 0) return 0;
    long t = number;
    int e = power;
    int result = 1;
    for(i=0; i<sizeof(int); i++) {
        if (e & 1 == 1) result *= t;
        e >>= 1;
        if (e==0) break;
        t = t * t;
    }
}

The Math.Pow function uses the processor power function and is more efficient.

Python: download a file from an FTP server

urllib2.urlopen handles ftp links.

how to do file upload using jquery serialization

You can upload files via AJAX by using the FormData method. Although IE7,8 and 9 do not support FormData functionality.

$.ajax({
    url: "ajax.php", 
    type: "POST",             
    data: new FormData('form'),
    contentType: false,       
    cache: false,             
    processData:false, 
    success: function(data) {
        $("#response").html(data);
    }
});

How to change navigation bar color in iOS 7 or 6?

If you want to have a solid color for your navigation bar in iOS 6 similar to iOS 7 use this:

[[UINavigationBar appearance] setBackgroundImage:[[UIImage alloc] init] forBarMetrics:UIBarMetricsDefault];
[[UINavigationBar appearance] setBackgroundColor:[UIColor greenColor]];

in iOS 7 use the barTintColor like this:

navigationController.navigationBar.barTintColor = [UIColor greenColor];

or

 [[UINavigationBar appearance] setBarTintColor:[UIColor greenColor]];

Java balanced expressions check {[()]}

I hope this code can help:

import java.util.Stack;

public class BalancedParenthensies {

    public static void main(String args[]) {

        System.out.println(balancedParenthensies("{(a,b)}"));
        System.out.println(balancedParenthensies("{(a},b)"));
        System.out.println(balancedParenthensies("{)(a,b}"));
    }

    public static boolean balancedParenthensies(String s) {
        Stack<Character> stack  = new Stack<Character>();
        for(int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if(c == '[' || c == '(' || c == '{' ) {     
                stack.push(c);
            } else if(c == ']') {
                if(stack.isEmpty() || stack.pop() != '[') {
                    return false;
                }
            } else if(c == ')') {
                if(stack.isEmpty() || stack.pop() != '(') {
                    return false;
                }           
            } else if(c == '}') {
                if(stack.isEmpty() || stack.pop() != '{') {
                    return false;
                }
            }

        }
        return stack.isEmpty();
    }
}

Catch multiple exceptions in one line (except block)

If you frequently use a large number of exceptions, you can pre-define a tuple, so you don't have to re-type them many times.

#This example code is a technique I use in a library that connects with websites to gather data

ConnectErrs  = (URLError, SSLError, SocketTimeoutError, BadStatusLine, ConnectionResetError)

def connect(url, data):
    #do connection and return some data
    return(received_data)

def some_function(var_a, var_b, ...):
    try: o = connect(url, data)
    except ConnectErrs as e:
        #do the recovery stuff
    blah #do normal stuff you would do if no exception occurred

NOTES:

  1. If you, also, need to catch other exceptions than those in the pre-defined tuple, you will need to define another except block.

  2. If you just cannot tolerate a global variable, define it in main() and pass it around where needed...

How to check String in response body with mockMvc

Another option is:

when:

def response = mockMvc.perform(
            get('/path/to/api')
            .header("Content-Type", "application/json"))

then:

response.andExpect(status().isOk())
response.andReturn().getResponse().getContentAsString() == "what you expect"

Subset dataframe by multiple logical conditions of rows to remove

This answer is more meant to explain why, not how. The '==' operator in R is vectorized in a same way as the '+' operator. It matches the elements of whatever is on the left side to the elements of whatever is on the right side, per element. For example:

> 1:3 == 1:3
[1] TRUE TRUE TRUE

Here the first test is 1==1 which is TRUE, the second 2==2 and the third 3==3. Notice that this returns a FALSE in the first and second element because the order is wrong:

> 3:1 == 1:3
[1] FALSE  TRUE FALSE

Now if one object is smaller then the other object then the smaller object is repeated as much as it takes to match the larger object. If the size of the larger object is not a multiplication of the size of the smaller object you get a warning that not all elements are repeated. For example:

>  1:2 == 1:3
[1]  TRUE  TRUE FALSE
Warning message:
In 1:2 == 1:3 :
  longer object length is not a multiple of shorter object length

Here the first match is 1==1, then 2==2, and finally 1==3 (FALSE) because the left side is smaller. If one of the sides is only one element then that is repeated:

> 1:3 == 1
[1]  TRUE FALSE FALSE

The correct operator to test if an element is in a vector is indeed '%in%' which is vectorized only to the left element (for each element in the left vector it is tested if it is part of any object in the right element).

Alternatively, you can use '&' to combine two logical statements. '&' takes two elements and checks elementwise if both are TRUE:

> 1:3 == 1 & 1:3 != 2
[1]  TRUE FALSE FALSE

jQuery event handlers always execute in order they were bound - any way around this?

You can do a custom namespace of events.

$('span').bind('click.doStuff1',function(){doStuff1();});
$('span').bind('click.doStuff2',function(){doStuff2();});

Then, when you need to trigger them you can choose the order.

$('span').trigger('click.doStuff1').trigger('click.doStuff2');

or

$('span').trigger('click.doStuff2').trigger('click.doStuff1');

Also, just triggering click SHOULD trigger both in the order they were bound... so you can still do

$('span').trigger('click'); 

How do I get the current timezone name in Postgres 9.3?

I don't think this is possible using PostgreSQL alone in the most general case. When you install PostgreSQL, you pick a time zone. I'm pretty sure the default is to use the operating system's timezone. That will usually be reflected in postgresql.conf as the value of the parameter "timezone". But the value ends up as "localtime". You can see this setting with the SQL statement.

show timezone;

But if you change the timezone in postgresql.conf to something like "Europe/Berlin", then show timezone; will return that value instead of "localtime".

So I think your solution will involve setting "timezone" in postgresql.conf to an explicit value rather than the default "localtime".

Change background color of iframe issue

It is possible. With vanilla Javascript, you can use the function below for reference.

function updateIframeBackground(iframeId) {
    var x = document.getElementById(iframeId);
    var y = (x.contentWindow || x.contentDocument);
    if (y.document) y = y.document;
    y.body.style.backgroundColor = "#2D2D2D";
}

https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_iframe_contentdocument

How to change letter spacing in a Textview?

This answer is based on Pedro's answer but adjusted so it also works if text attribute is already set:

package nl.raakict.android.spc.widget;
import android.content.Context;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ScaleXSpan;
import android.util.AttributeSet;
import android.widget.TextView;


public class LetterSpacingTextView extends TextView {
    private float letterSpacing = LetterSpacing.BIGGEST;
    private CharSequence originalText = "";


    public LetterSpacingTextView(Context context) {
        super(context);
    }

    public LetterSpacingTextView(Context context, AttributeSet attrs){
        super(context, attrs);
        originalText = super.getText();
        applyLetterSpacing();
        this.invalidate();
    }

    public LetterSpacingTextView(Context context, AttributeSet attrs, int defStyle){
        super(context, attrs, defStyle);
    }

    public float getLetterSpacing() {
        return letterSpacing;
    }

    public void setLetterSpacing(float letterSpacing) {
        this.letterSpacing = letterSpacing;
        applyLetterSpacing();
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        originalText = text;
        applyLetterSpacing();
    }

    @Override
    public CharSequence getText() {
        return originalText;
    }

    private void applyLetterSpacing() {
        if (this == null || this.originalText == null) return;
        StringBuilder builder = new StringBuilder();
        for(int i = 0; i < originalText.length(); i++) {
            String c = ""+ originalText.charAt(i);
            builder.append(c.toLowerCase());
            if(i+1 < originalText.length()) {
                builder.append("\u00A0");
            }
        }
        SpannableString finalText = new SpannableString(builder.toString());
        if(builder.toString().length() > 1) {
            for(int i = 1; i < builder.toString().length(); i+=2) {
                finalText.setSpan(new ScaleXSpan((letterSpacing+1)/10), i, i+1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        super.setText(finalText, BufferType.SPANNABLE);
    }

    public class LetterSpacing {
        public final static float NORMAL = 0;
        public final static float NORMALBIG = (float)0.025;
        public final static float BIG = (float)0.05;
        public final static float BIGGEST = (float)0.2;
    }
}

If you want to use it programatically:

LetterSpacingTextView textView = new LetterSpacingTextView(context);
textView.setSpacing(10); //Or any float. To reset to normal, use 0 or LetterSpacingTextView.Spacing.NORMAL
textView.setText("My text");
//Add the textView in a layout, for instance:
((LinearLayout) findViewById(R.id.myLinearLayout)).addView(textView);

Oracle SQL Query for listing all Schemas in a DB

Either of the following SQL will return all schema in Oracle DB.

  1. select owner FROM all_tables group by owner;
  2. select distinct owner FROM all_tables;

How to serialize Joda DateTime with Jackson JSON processor?

As @Kimble has said, with Jackson 2, using the default formatting is very easy; simply register JodaModule on your ObjectMapper.

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JodaModule());

For custom serialization/de-serialization of DateTime, you need to implement your own StdScalarSerializer and StdScalarDeserializer; it's pretty convoluted, but anyway.

For example, here's a DateTime serializer that uses the ISODateFormat with the UTC time zone:

public class DateTimeSerializer extends StdScalarSerializer<DateTime> {

    public DateTimeSerializer() {
        super(DateTime.class);
    }

    @Override
    public void serialize(DateTime dateTime,
                          JsonGenerator jsonGenerator,
                          SerializerProvider provider) throws IOException, JsonGenerationException {
        String dateTimeAsString = ISODateTimeFormat.withZoneUTC().print(dateTime);
        jsonGenerator.writeString(dateTimeAsString);
    }
}

And the corresponding de-serializer:

public class DateTimeDesrializer extends StdScalarDeserializer<DateTime> {

    public DateTimeDesrializer() {
        super(DateTime.class);
    }

    @Override
    public DateTime deserialize(JsonParser jsonParser,
                                DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        try {
            JsonToken currentToken = jsonParser.getCurrentToken();
            if (currentToken == JsonToken.VALUE_STRING) {
                String dateTimeAsString = jsonParser.getText().trim();
                return ISODateTimeFormat.withZoneUTC().parseDateTime(dateTimeAsString);
            }
        } finally {
            throw deserializationContext.mappingException(getValueClass());
        }
    }

Then tie these together with a module:

public class DateTimeModule extends SimpleModule {

    public DateTimeModule() {
        super();
        addSerializer(DateTime.class, new DateTimeSerializer());
        addDeserializer(DateTime.class, new DateTimeDeserializer());
    }
}

Then register the module on your ObjectMapper:

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new DateTimeModule());

Call JavaScript function from C#

.aspx file in header section

<head>
    <script type="text/javascript">
        <%=YourScript %>
        function functionname1(arg1,arg2){content}
    </script>
</head>

.cs file

public string YourScript = "";
public string functionname(arg)
{
    if (condition)
    {
        YourScript = "functionname1(arg1,arg2);";
    }
}

Round up to Second Decimal Place in Python

The round funtion stated does not works for definate integers like :

a=8
round(a,3)
8.0
a=8.00
round(a,3)
8.0
a=8.000000000000000000000000
round(a,3)
8.0

but , works for :

r=400/3.0
r
133.33333333333334
round(r,3)
133.333

Morever the decimals like 2.675 are rounded as 2.67 not 2.68.
Better use the other method provided above.

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

What is "stdafx.h" used for in Visual Studio?

I just ran into this myself since I'm trying to create myself a bare bones framework but started out by creating a new Win32 Program option in Visual Studio 2017. "stdafx.h" is unnecessary and should be removed. Then you can remove the stupid "stdafx.h" and "stdafx.cpp" that is in your Solution Explorer as well as the files from your project. In it's place, you'll need to put

#include <Windows.h>

instead.

clearing a char array c

void clearArray (char *input[]){
    *input = ' '; 
}

python time + timedelta equivalent

If it's worth adding another file / dependency to your project, I've just written a tiny little class that extends datetime.time with the ability to do arithmetic. If you go past midnight, it just wraps around:

>>> from nptime import nptime
>>> from datetime import timedelta
>>> afternoon = nptime(12, 24) + timedelta(days=1, minutes=36)
>>> afternoon
nptime(13, 0)
>>> str(afternoon)
'13:00:00'

It's available from PyPi as nptime ("non-pedantic time"), or on GitHub: https://github.com/tgs/nptime

The documentation is at http://tgs.github.io/nptime/

Python strip() multiple characters?

Because that's not what strip() does. It removes leading and trailing characters that are present in the argument, but not those characters in the middle of the string.

You could do:

name= name.replace('(', '').replace(')', '').replace ...

or:

name= ''.join(c for c in name if c not in '(){}<>')

or maybe use a regex:

import re
name= re.sub('[(){}<>]', '', name)

excel delete row if column contains value from to-remove-list

I've found a more reliable method (at least on Excel 2016 for Mac) is:

Assuming your long list is in column A, and the list of things to be removed from this is in column B, then paste this into all the rows of column C:

= IF(COUNTIF($B$2:$B$99999,A2)>0,"Delete","Keep")

Then just sort the list by column C to find what you have to delete.