text:
// Copyright 2015, EMC, Inc.
/* jshint node:true */

'use strict';

describe('Http.Api.Tags', function () {
    var configuration;
    var lookupService;
    var workflowApiService;
    var Promise;
    var Errors;
    var nodesApi;
    var tagsApi;

    helper.httpServerBefore();

    before(function () {
        configuration = helper.injector.get('Services.Configuration');
        lookupService = helper.injector.get('Services.Lookup');
        workflowApiService = helper.injector.get('Http.Services.Api.Workflows');
        Promise = helper.injector.get('Promise');
        Errors = helper.injector.get('Errors');
        nodesApi = helper.injector.get('Http.Services.Api.Nodes');
        tagsApi = helper.injector.get('Http.Services.Api.Tags');
    });

    beforeEach('set up mocks', function() {
        lookupService.ipAddressToMacAddress = this.sandbox.stub().resolves();
        lookupService.ipAddressToNodeId = this.sandbox.stub().resolves();
        this.sandbox.stub(configuration);
        this.sandbox.stub(workflowApiService);
    });

    helper.httpServerAfter();

    var input = {
        name: 'tag-name',
        rules: [
            {
                path: 'dmi.dmi.base_board.manufacturer',
                contains: 'Intel'
            },
            {
                path: 'dmi.memory.total',
                equals: '32946864kB'
            }
        ]
    };

    describe('2.0 Tags', function() {
        beforeEach(function() {
            this.sandbox.stub(tagsApi, 'findTags').resolves([input]);
            this.sandbox.stub(tagsApi, 'getTag').resolves(input);
            this.sandbox.stub(tagsApi, 'destroyTag').resolves([]);
            this.sandbox.stub(tagsApi, 'createTag').resolves([]);
            this.sandbox.stub(tagsApi, 'regenerateTags');
        });

        it('should create a tag', function() {
            tagsApi.findTags.resolves([]);
            return helper.request().post('/api/2.0/tags')
                .send(input)
                .expect('Content-Type', /^application\/json/)
                .expect(201)
                .then(function (req) {
                    var tag = req.body;
                    expect(tag).to.have.property('name').that.equals(input.name);
                    expect(tag).to.have.property('rules').that.deep.equals(input.rules);
                    expect(tagsApi.createTag).to.have.been.calledOnce;
                    expect(tagsApi.regenerateTags).to.have.been.calledOnce;
                });
        });

        it('should 409 creating a tag that already exists', function() {
            return helper.request().post('/api/2.0/tags')
                .send(input)
                .expect(409);
        });

        it('should get tags', function() {
            return helper.request().get('/api/2.0/tags')
                .expect('Content-Type', /^application\/json/)
                .expect(200)
                .then(function (res) {
                    var tag = res.body[0];
                    expect(tag).to.have.property('name').that.equals(input.name);
                    expect(tag).to.have.property('rules').that.deep.equals(input.rules);
                });
        });

        it('should return a tag from GET /tags/:id', function () {
            return helper.request().get('/api/2.0/tags/tag-name')
                .expect('Content-Type', /^application\/json/)
                .expect(200)
                .then(function(res) {
                    var tag = res.body;
                    expect(tag).to.have.property('name').that.equals(input.name);
                    expect(tag).to.have.property('rules').that.deep.equals(input.rules);
                });
        });

        it('should return a tag from GET /tags/:id with special characters', function () {
            return helper.request().get('/api/2.0/tags/tag name')
                .expect('Content-Type', /^application\/json/)
                .expect(200)
                .then(function(res) {
                    var tag = res.body;
                    expect(tagsApi.getTag).to.have.been.calledWith('tag name');
                    expect(tag).to.have.property('name').that.equals(input.name);
                    expect(tag).to.have.property('rules').that.deep.equals(input.rules);
                });
        });

        it('should 404 an invalid GET /tags/:id', function () {
            tagsApi.getTag.resetBehavior();
            tagsApi.getTag.rejects(new Errors.NotFoundError());
            return helper.request().get('/api/2.0/tags/bad-tag-name')
                .expect('Content-Type', /^application\/json/)
                .expect(404);
        });

        it('should destroy a tag', function() {
            return helper.request().delete('/api/2.0/tags/tag-name')
                .expect(204);
        });

        it('should 404 an invalid tag', function() {
            tagsApi.getTag.resetBehavior();
            tagsApi.getTag.rejects(new Errors.NotFoundError());
            return helper.request().delete('/api/2.0/tags/bad-tag-name')
                .expect(204);
        });

        describe('POST /tags/:tagName/nodes/workflows', function() {
            it('should support specify workflow name via body', function() {
                this.sandbox.stub(nodesApi, 'getNodesByTag').withArgs('tag001').resolves([
                    { id: 'nodeId1' },
                    { id: 'nodeId2' }
                ]);
                this.sandbox.stub(nodesApi, 'setNodeWorkflow')
                    .onFirstCall().resolves({ id: 'graphId1' })
                    .onSecondCall().resolves({ id: 'graphId2' });
                return helper.request()
                    .post('/api/2.0/tags/tag001/nodes/workflows')
                    .send({ name: 'Graph.test', domain: 'test', options: { test: true} })
                    .expect('Content-Type', /^application\/json/)
                    .expect(202, [ {id: 'graphId1'}, {id: 'graphId2'}])
                    .then(function() {
                        expect(nodesApi.getNodesByTag).to.be.calledWith('tag001');
                        expect(nodesApi.setNodeWorkflow).to.be.calledTwice;
                        expect(nodesApi.setNodeWorkflow.firstCall).to.be.calledWith(
                            {name: 'Graph.test', domain: 'test', options: { test: true } },
                            'nodeId1' );
                        expect(nodesApi.setNodeWorkflow.secondCall).to.be.calledWith(
                            {name: 'Graph.test', domain: 'test', options: { test: true } },
                            'nodeId2' );
                    });
            });

            it('should support specify workflow name via query', function() {
                this.sandbox.stub(nodesApi, 'getNodesByTag').withArgs('tag001').resolves([
                    { id: 'nodeId1' },
                    { id: 'nodeId2' }
                ]);
                this.sandbox.stub(nodesApi, 'setNodeWorkflow')
                    .onFirstCall().resolves({ id: 'graphId1' })
                    .onSecondCall().resolves({ id: 'graphId2' });
                return helper.request()
                    .post('/api/2.0/tags/tag001/nodes/workflows?name=Graph.test')
                    .send({ domain: 'test',  options: { test: true} })
                    .expect('Content-Type', /^application\/json/)
                    .expect(202, [ {id: 'graphId1'}, {id: 'graphId2'}])
                    .then(function() {
                        expect(nodesApi.getNodesByTag).to.be.calledWith('tag001');
                        expect(nodesApi.setNodeWorkflow).to.be.calledTwice;
                        expect(nodesApi.setNodeWorkflow.firstCall).to.be.calledWith(
                            {name: 'Graph.test', domain: 'test', options: { test: true } },
                            'nodeId1' );
                        expect(nodesApi.setNodeWorkflow.secondCall).to.be.calledWith(
                            {name: 'Graph.test', domain: 'test', options: { test: true } },
                            'nodeId2' );
                    });
            });

            it('should succeed if no nodes are binded with tag', function() {
                this.sandbox.stub(nodesApi, 'getNodesByTag').withArgs('tag001').resolves([]);
                this.sandbox.stub(nodesApi, 'setNodeWorkflow').resolves({id: 'graphId'});
                return helper.request()
                    .post('/api/2.0/tags/tag001/nodes/workflows')
                    .send({ name: 'Graph.test', options: { test: true} })
                    .expect('Content-Type', /^application\/json/)
                    .expect(202)
                    .then(function() {
                        expect(nodesApi.getNodesByTag).to.be.calledWith('tag001');
                        expect(nodesApi.setNodeWorkflow).to.not.be.called;
                    });
            });

            it('should 404 if tag name is not existing', function() {
                this.sandbox.stub(nodesApi, 'getNodesByTag').withArgs('tag001')
                    .rejects(new Errors.NotFoundError('fail to find tag with name tag001'));
                return helper.request()
                    .post('/api/2.0/tags/tag001/nodes/workflows')
                    .send({ name: 'Graph.test', options: { test: true} })
                    .expect(404);
            });

            it('should 400 if run workflow fails for first node', function() {
                this.sandbox.stub(nodesApi, 'getNodesByTag').withArgs('tag001').resolves([
                    { id: 'nodeId1' },
                    { id: 'nodeId2' }
                ]);
                this.sandbox.stub(nodesApi, 'setNodeWorkflow')
                    .onFirstCall().rejects(new Error('graph error'))
                    .onSecondCall().resolves({ id: 'graphId2' });
                return helper.request()
                    .post('/api/2.0/tags/tag001/nodes/workflows')
                    .send({ name: 'Graph.test', options: { test: true} })
                    .expect(400);
            });

            it('should 400 if run workflow fails for second node', function() {
                this.sandbox.stub(nodesApi, 'getNodesByTag').withArgs('tag001').resolves([
                    { id: 'nodeId1' },
                    { id: 'nodeId2' }
                ]);
                this.sandbox.stub(nodesApi, 'setNodeWorkflow')
                    .onFirstCall().resolves({ id: 'graphId1' })
                    .onSecondCall().rejects(new Error('graph error'));
                return helper.request()
                    .post('/api/2.0/tags/tag001/nodes/workflows')
                    .send({ name: 'Graph.test', options: { test: true} })
                    .expect(400);
            });
        });
    });
});


text:
<?php

namespace Commando;

use Illuminate\Console\Command;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Input\InputArgument;

class TestCommande extends Command {
	protected $name = 'commando:config';
	protected $description = 'Configuration Commando';

	public function __construct()
	{
		parent::__construct();
	}
	public function fire()
	{
		$this->comment('=====================================');
		$file=__dir__.'/../../config/config.xml';
		$xml=simplexml_load_file($file);

		$url= $this->askBoucle('Logo link (http://....)','url');
		$xml->url=$url;

		foreach($xml->topics->topic as $topic){
			$ask='btn label for '.(String)$topic;
			$topic->attributes()->btn = $this->askBoucle($ask,'label');
		}

		$xml->asXML($file);
	}

	private function askBoucle($label,$error='nom invalide',$default=null)
	{
		$data='';
		do
		{
			// Ask the user to input value
			$data = trim($this->ask($label.' : ',$default));

			// Check if the value is valid.
			if ( strlen($data)<2 )
			{
				// Return an error message
				$this->error($error.' - merci de recommencer.');
			}
		}
		while( strlen($data)<2 );
		return $data;
	}
}

redpajama_set_name: RedPajamaGithub


text:
import discord
import logging

from database.viking import Role
from discord.ext import commands
from model.role import DiscordRole, DiscordRoleError
from utilities.event import RoleEvent
from utilities.member import MemberInterface
from utilities.role import (
    check_for_role,
    get_role_by_id
)

log = logging.getLogger(__name__)

class Roles(commands.Cog):
    def __init__(self, viking):
        self.viking = viking
        self.event = RoleEvent(self.viking)

    # Event Listeners

    @commands.Cog.listener()
    async def on_guild_role_create(self, role):
        """
        An event that is called when a role is created.
        """

        await self.viking.update(role.guild.id)
        await self.event.role_create(role)

    @commands.Cog.listener()
    async def on_guild_role_delete(self, role):
        """
        An event that is called when a role is deleted.
        """

        await self.viking.update(role.guild.id)
        await self.event.role_add()
        await self.event.role_delete(role.id)

    @commands.Cog.listener()
    async def on_guild_role_update(self, before, after):
        """
        An event that is called when a role is updated.
        """

        await self.viking.update(before.guild.id)
        await self.event.role_update(after)

        # If the role hierarchy is changed, assign the role with the
        # higher position as the top role in the database.

        if before < after:
            await self.event.role_replace(after)

    # Commands

    @commands.command(hidden=True)
    @commands.bot_has_guild_permissions(manage_roles=True)
    @commands.has_guild_permissions(manage_roles=True)
    async def addrole(self, ctx, name, *, identifier):
        """
        *addrole <role> <identifier>

        A command that adds a role to a member by name, nickname or ID.
        """

        interface = MemberInterface(ctx, identifier)
        discord_id = await interface.get()

        if discord_id is None:
            return

        member = ctx.guild.get_member(discord_id)
        role = discord.utils.get(ctx.guild.roles, name=name)

        try:
            await member.add_roles(role)
        except discord.HTTPException:
            await ctx.send(f"{member} could not be assigned the {role} role.")
        else:
            log.info(f"{ctx.author} assigned the role {role} to {member}.")

    @commands.command(hidden=True)
    @commands.bot_has_guild_permissions(manage_roles=True)
    @commands.has_guild_permissions(manage_roles=True)
    async def createrole(self, ctx, *, name):
        """
        *createrole <name>

        A command that creates a role with no permissions.
        """

        check = await check_for_role(self, name)

        if check is None:
            try:
                permissions = discord.Permissions.none()
                await ctx.guild.create_role(name=name, permissions=permissions)
            except discord.HTTPException:
                await ctx.send(f"{name} could not be created.")
            else:
                log.info(f"{ctx.author} created the role {name}.")
        else:
            await ctx.send('A role with that name already exists.')

    @commands.command(hidden=True)
    @commands.bot_has_guild_permissions(manage_roles=True)
    @commands.has_guild_permissions(manage_roles=True)
    async def deleterole(self, ctx, *, name):
        """
        *deleterole <name>

        A command that deletes a role.
        """

        check = await check_for_role(self, name)

        if check is not None:
            for guild in self.viking.guilds:
                role = discord.utils.get(guild.roles, name=name)

            try:
                await role.delete()
            except discord.HTTPException:
                return await ctx.send(f"{name} could not be deleted.")
            else:
                log.info(f"{ctx.author} deleted the role {name}.")
        else:
            await ctx.send('No role found.')

    @commands.command(hidden=True)
    @commands.bot_has_guild_permissions(manage_roles=True)
    @commands.has_guild_permissions(manage_roles=True)
    async def removerole(self, ctx, name, *, identifier):
        """
        *removerole <role> <identifier>

        A command that removes a role from a member by name, nickname or ID.
        """

        interface = MemberInterface(ctx, identifier)
        discord_id = await interface.get()

        if discord_id is None:
            return

        member = ctx.guild.get_member(discord_id)
        role = discord.utils.get(ctx.guild.roles, name=name)

        try:
            await member.remove_roles(role)
        except discord.HTTPException:
            await ctx.send(f"The {role} role could not be removed from {member}.")
        else:
            log.info(f"{ctx.author} removed the role {role} from {member}.")

    @commands.command()
    async def role(self, ctx, *, identifier):
        """
        *role <identifier>

        A command that displays an overview of a role.
        """

        try:
            role_id = await get_role_by_id(self, identifier)
        except DiscordRoleError:
            await ctx.send('No role found.')
        else:
            embed = discord.Embed(color=self.viking.color)

            row = dict(
                await Role
                .query.execution_options(return_model=False)
                .where(Role.id == role_id)
                .gino.first()
            )

            role = DiscordRole(row)

            embed.add_field(
                inline=False,
                name='Role ID',
                value=role.id
            )
            embed.add_field(
                inline=False,
                name='Name',
                value=role.name
            )
            embed.add_field(
                inline=False,
                name='Colour',
                value=role.colour
            )
            embed.add_field(
                inline=False,
                name='Hoist',
                value=role.hoist
            )
            embed.add_field(
                inline=False,
                name='Position',
                value=role.position
            )
            embed.add_field(
                inline=False,
                name='Mentionable',
                value=role.mentionable
            )
            embed.add_field(
                inline=False,
                name='Created At',
                value=role.created
            )

            await ctx.send(embed=embed)

async def setup(viking):
    roles = Roles(viking)
    await viking.add_cog(roles)


text:
namespace {

using namespace cddd::cqrs;

TEST(domain_event_test, is_event_when_using_the_same_event_type_should_return_true) {
   // Given
   std::unique_ptr<domain_event> target{new basic_domain_event<fake_event>{{}, 1}};

   // When
   bool actual = is_event<fake_event>(*target);

   // Then
   ASSERT_TRUE(actual);
}

TEST(domain_event_test, is_event_when_using_the_different_event_type_should_return_false) {
   // Given
   std::unique_ptr<domain_event> target{new basic_domain_event<fake_event>{{}, 1}};

   // When
   bool actual = is_event<int>(*target);

   // Then
   ASSERT_FALSE(actual);
}

TEST(domain_event_test, unsafe_event_cast_when_using_the_same_event_type_should_cast_the_event) {
   // Given
   std::unique_ptr<domain_event> target{new basic_domain_event<fake_event>{{}, 1}};

   // When
   ASSERT_NO_THROW(unsafe_event_cast<fake_event>(*target));
}

TEST(domain_event_test, safe_event_cast_when_using_the_different_event_type_should_throw_bad_cast) {
   // Given
   std::unique_ptr<domain_event> target{new basic_domain_event<fake_event>{{}, 1}};

   // When
   ASSERT_THROW(safe_event_cast<int>(*target), std::bad_cast);
}

}


text:
const assert = require('assert')
const normalizeURI = require('../lib/normalize-uri')

suite('normalizeURI(uri, targetPlatform)', () => {
  test('posix to posix', () => {
    assert.equal(normalizeURI('/home/src/main.js', '/'), '/home/src/main.js')
    assert.equal(normalizeURI('src/main.js', '/'), 'src/main.js')
  })

  test('posix to win32', () => {
    assert.equal(normalizeURI('/home/src/main.js', '\\'), '\\home\\src\\main.js')
    assert.equal(normalizeURI('src/main.js', '\\'), 'src\\main.js')
  })

  test('win32 to posix', () => {
    assert.equal(normalizeURI('C:\\home\\src\\main.js', '/'), 'C:/home/src/main.js')
    assert.equal(normalizeURI('src\\main.js', '/'), 'src/main.js')
  })

  test('win32 to win32', () => {
    assert.equal(normalizeURI('C:\\home\\src\\main.js', '\\'), 'C:\\home\\src\\main.js')
    assert.equal(normalizeURI('src\\main.js', '\\'), 'src\\main.js')
  })
})


text:
<?php
require_once("../modelo/conexion.php");

    $mysqli->real_query("SELECT id_producto,producto,p_venta,imagen from t_productos limit 0,10");
                $query=$mysqli->store_result();
                if($query){
                    while($row = $query->fetch_assoc()){
                          echo '

';
                                    echo $row["p_venta"];
                                echo '

';
                                    echo $row["producto"];
                                echo '

                                comprar

';
                            }
                        }
?>


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.book.vero.c3_15_broadcast3_sender" >
    <permission android:name="com.vero.authority1"/>
    <uses-permission android:name="com.vero.authority1"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".demo01_childThread_to_parent"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Demo02_Authority_Bro_sender"
            android:label="@string/title_activity_demo02__authority__bro_sender" >
        </activity>
    </application>

</manifest>


text:
<?xml version="1.0"?>
<package>
    <id>simplepay_payments</id>
    <type>payment</type>
    <version>1.0.0</version>
    <minversion>1.0.0</minversion>
    <cartversions>
        <item>1.2</item>
    </cartversions>
    <package_content>
        <extensions>
            <extension>simplepay_payments</extension>
        </extensions>
    </package_content>
</package>


text:
import logging
import re
import urllib

from tornado.auth import httpclient, OAuthMixin
from tornado.escape import xhtml_escape
from tornado.httputil import url_concat
from tornado.options import options

class DoubanMixin(OAuthMixin):
    """Douban OAuth authentication.

    Register your apps at http://www.douban.com/service/apikey/apply
    Then copy your CONSUMER KEY and CONSUMER SECRET to the application
    setings 'douban_consumer_key' and 'douban_consumer_secret'.

    Example usage::

        define('douban_consumer_key', 'key')
        define('douban_consumer_secret', 'secret')

        class DoubanHandler(tornado.web.RequestHandler, DoubanMixin):
            @tornado.web.asynchronous
            def get(self):
                if self.get_argument("oauth_token", None):
                    self.get_authenticated_user(self._on_auth)
                    return
                self.authorize_redirect()

            def _on_auth(self, user):
                if not user:
                    raise tornado.web.HTTPError(500, "Douban auth failed")
                # do something else
                self.finish()

    """
    _OAUTH_VERSION = "1.0"
    _OAUTH_REQUEST_TOKEN_URL = "http://www.douban.com/service/auth/request_token"
    _OAUTH_ACCESS_TOKEN_URL = "http://www.douban.com/service/auth/access_token"
    _OAUTH_AUTHORIZE_URL = "http://www.douban.com/service/auth/authorize"
    _OAUTH_AUTHENTICATE_URL = "http://www.douban.com/service/auth/authenticate"
    _OAUTH_NO_CALLBACKS = False

    # def authenticate_redirect(self, callback_uri = None):
    #     """Just like authorize_redirect(), but auto-redirects if authorized.

    #     This is generally the right interface to use if you are using
    #     Twitter for single-sign on.
    #     """
    #     http = httpclient.AsyncHTTPClient()
    #     http.fetch(self._oauth_request_token_url(callback_uri = callback_uri), self.async_callback(
    #         self._on_request_token, self._OAUTH_AUTHENTICATE_URL, None))

    def douban_request(self, path, callback, access_token=None,
            post_args=None, **args):
        url = "http://api.douban.com" + path
        if access_token:
            all_args = {}
            all_args.update(args)
            #all_args.update(post_args or {})
            #consumer_token = self._oauth_consumer_token()
            method = "POST" if post_args is not None else "GET"
            oauth = self._oauth_request_parameters(
                url, access_token, all_args, method=method)
            args.update(oauth)

        callback = self.async_callback(self._on_douban_request, callback)
        http = httpclient.AsyncHTTPClient()
        if post_args is not None:
            headers = _to_header(args)
            headers['Content-Type'] = 'application/atom+xml; charset=utf-8'
            http.fetch(url, method="POST", headers=headers,
                       body=post_args, callback=callback)
        else:
            http.fetch(url_concat(url, args), callback=callback)

    def _do_callback(self, data):
        if data:
            print data

    def douban_saying(self, access_token=None, content=None, **args):
        """ douban miniblog
        Example usage::

            class MainHandler(RequestHandler, DoubanMixin):
                @authenticated
                @asynchronous
                def get(self):
                    self.douban_saying(
                        self.async_callback(self._on_saying),
                        access_token=user["access_token"],
                        content="test content"
                    )

                def _on_saying(self, xml):
                    if not xml:
                        raise HTTPError(500, 'Douban saying failed')
                    self.write(xml)
                    self.finish()
        """
        callback = self.async_callback(self._do_callback)
        path = "/miniblog/saying"
        if not access_token or not content:
            raise Exception("none access token")
        try:
            content = content.encode('utf-8')
        except UnicodeDecodeError:
            pass
        content = xhtml_escape(content)
        post_args = '<entry><content>%s</content></entry>' % content
        self.douban_request(path, callback, access_token, post_args, **args)

    def _on_douban_request(self, callback, response):
        if response.error:
            logging.warning(
                "Error response %s fetching %s", response.error,
                response.request.url)
            callback(None)
            return
        callback(response.body)

    def _oauth_consumer_token(self):
        token = dict(
            key=options.douban_key,
            secret=options.douban_secret
        )
        return token

    def _oauth_get_user(self, access_token, callback):
        callback = self.async_callback(self._parse_user_response, callback)
        self.douban_request(
            "/people/%40me",
            access_token=access_token, callback=callback
        )

    def _parse_user_response(self, callback, xml):
        user = {}
        _uid = re.findall(r'<db:uid>(\S+?)</db:uid>', xml)
        _nick = re.findall(r'<title>(.*?)</title>', xml)
        _loc = re.findall(r'<db:location\s+id="(\S+?)">', xml)
        _avatar = re.findall(r'<link\s+href="(\S+?)"\s+rel="icon"', xml)
        if _uid:
            user['uid'] = _uid[0]
        if _nick:
            user['nickname'] = _nick[0]
        if _loc:
            user['location'] = _loc[0]
        if _avatar:
            user['avatar'] = _avatar[0]
        callback(user)

def _to_header(kw):
    s = ", ".join(['%s="%s"' % (k, _quote(v)) for k, v in kw.iteritems() if k.startswith('oauth_')])
    h = 'OAuth realm="", %s' % s
    return {'Authorization': h}

def _quote(s):
    return urllib.quote(str(s), '~')


text:
package com.cisco.oss.foundation.directory.utils;

import static java.net.HttpURLConnection.*;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.google.common.io.ByteStreams;
import com.google.common.io.CharStreams;
import com.cisco.oss.foundation.directory.exception.ErrorCode;
import com.cisco.oss.foundation.directory.exception.ServiceException;

/**
 * Convenient Http Client util methods to invoke remote RESTful Service.
 *
 *
 */
public final class HttpUtils {

    public static enum HttpMethod {
        GET, PUT, POST, DELETE
    }

    /**
     * prevent to create instance
     */
    private HttpUtils() { }

    /**
     * Invoke REST Service using POST method.
     *
     * @param urlStr
     *            the REST service URL String
     * @param body
     *            the Http Body String.
     * @return the HttpResponse.
     * @throws IOException
     * @throws ServiceException
     */
    public static HttpResponse postJson(String urlStr, String body) throws IOException, ServiceException {

        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
        if (urlConnection instanceof HttpsURLConnection) {
            setTLSConnection((HttpsURLConnection)urlConnection);
        }
        urlConnection.addRequestProperty("Accept", "application/json");

        urlConnection.setRequestMethod("POST");

        urlConnection.addRequestProperty("Content-Type", "application/json");
        urlConnection.addRequestProperty("Content-Length",
                Integer.toString(body.length()));
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);

        OutputStream out = urlConnection.getOutputStream();
        out.write(body.getBytes());
        ByteStreams.copy(new ByteArrayInputStream(body.getBytes()), out);
        return getHttpResponse(urlConnection);
    }

    /**
     * Invoke REST Service using POST method.
     *
     * @param urlStr
     *            the REST service URL String
     * @param body
     *            the Http Body String.
     * @param headers
     *            the Http header Map.
     * @return the HttpResponse.
     * @throws IOException
     * @throws ServiceException
     */
    public static HttpResponse postJson(String urlStr, String body, Map<String, String> headers) throws IOException, ServiceException {
        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
        if (urlConnection instanceof HttpsURLConnection) {
            setTLSConnection((HttpsURLConnection)urlConnection);
        }

        urlConnection.addRequestProperty("Accept", "application/json");

        urlConnection.setRequestMethod("POST");

        addCustomHeaders(urlConnection, headers);

        urlConnection.addRequestProperty("Content-Type", "application/json");
        urlConnection.addRequestProperty("Content-Length",
                Integer.toString(body.length()));
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setUseCaches(false);

        OutputStream out = urlConnection.getOutputStream();
        out.write(body.getBytes());
        ByteStreams.copy(new ByteArrayInputStream(body.getBytes()), out);
        return getHttpResponse(urlConnection);
    }

    /**
     * Invoke REST Service using PUT method.
     *
     * @param urlStr
     *            the REST Service URL String.
     * @param body
     *            the Http Body String.
     * @return the HttpResponse.
     * @throws IOException
     * @throws ServiceException
     */
    public static HttpResponse putJson(String urlStr, String body) throws IOException, ServiceException {
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Content-Type", "application/json");
        return put(urlStr, body, headers);
    }

    /**
     * Invoke REST Service using PUT method.
     *
     * It accepts the JSON message.
     *
     * @param urlStr
     *            the REST Service URL String.
     * @param body
     *            the Http Body String.
     * @param headers
     *            the Http header Map.
     * @return the HttpResponse.
     * @throws IOException
     * @throws ServiceException
     */
    public static HttpResponse put(String urlStr, String body,
            Map<String, String> headers) throws IOException, ServiceException {
        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
        if (urlConnection instanceof HttpsURLConnection) {
            setTLSConnection((HttpsURLConnection)urlConnection);
        }

        urlConnection.addRequestProperty("Accept", "application/json");

        urlConnection.setRequestMethod("PUT");
        addCustomHeaders(urlConnection, headers);

        urlConnection.addRequestProperty("Content-Type", "application/json");
        if (body != null && body.length() > 0)
            urlConnection.addRequestProperty("Content-Length",
                    Integer.toString(body.length()));
        else
            urlConnection.addRequestProperty("Content-Length", "0");
        urlConnection.setDoOutput(true);

        OutputStream out = urlConnection.getOutputStream();
        if (body != null && body.length() > 0)
            ByteStreams.copy(new ByteArrayInputStream(body.getBytes()), out);

        return getHttpResponse(urlConnection);

    }

    /**
     * Invoke REST Service using GET method.
     *
     * @param urlStr
     *            the REST service URL String.
     * @return the HttpResponse.
     * @throws IOException
     * @throws ServiceException
     */
    public static HttpResponse getJson(String urlStr) throws IOException, ServiceException {
        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
        if (urlConnection instanceof HttpsURLConnection) {
            setTLSConnection((HttpsURLConnection)urlConnection);
        }
        urlConnection.addRequestProperty("Accept", "application/json");

        return getHttpResponse(urlConnection);
    }

    /**
     * Invoke REST Service using GET method.
     *
     * @param urlStr
     *            the REST service URL String.
     * @param headers
     *            the Http header Map.
     * @return the HttpResponse.
     * @throws IOException
     * @throws ServiceException
     */
    public static HttpResponse getJson(String urlStr, Map<String, String> headers) throws IOException, ServiceException {
        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
        if (urlConnection instanceof HttpsURLConnection) {
            setTLSConnection((HttpsURLConnection)urlConnection);
        }
        urlConnection.addRequestProperty("Accept", "application/json");
        addCustomHeaders(urlConnection, headers);

        return getHttpResponse(urlConnection);
    }
    /**
     * Invoke REST Service using DELETE method.
     *
     * @param urlStr
     *            the REST URL String.
     * @return the HttpResponse.
     * @throws IOException
     * @throws ServiceException
     */
    public static HttpResponse deleteJson(String urlStr) throws IOException, ServiceException {
        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
        if (urlConnection instanceof HttpsURLConnection) {
            setTLSConnection((HttpsURLConnection)urlConnection);
        }
        urlConnection.addRequestProperty("Accept", "application/json");

        urlConnection.setRequestMethod("DELETE");

        return getHttpResponse(urlConnection);
    }

    /**
     * Invoke REST Service using DELETE method.
     *
     * @param urlStr
     *            the REST URL String.
     * @param headers
     *            the Http header Map.
     * @return the HttpResponse.
     * @throws IOException
     * @throws ServiceException
     */
    public static HttpResponse deleteJson(String urlStr, Map<String, String> headers) throws IOException, ServiceException {
        URL url = new URL(urlStr);
        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();
        if (urlConnection instanceof HttpsURLConnection) {
            setTLSConnection((HttpsURLConnection)urlConnection);
        }
        urlConnection.addRequestProperty("Accept", "application/json");
        addCustomHeaders(urlConnection, headers);

        urlConnection.setRequestMethod("DELETE");

        return getHttpResponse(urlConnection);
    }

    private static HttpsURLConnection setTLSConnection(
            HttpsURLConnection secureConn) throws ServiceException {
        try {
            // TODO enable the cert authentication later
            TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] certs,
                        String authType) {
                }

                public void checkServerTrusted(X509Certificate[] certs,
                        String authType) {
                }
            } };
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init(null, trustAllCerts, null);
            secureConn.setSSLSocketFactory(ctx.getSocketFactory());

            secureConn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            return secureConn;
        } catch (Throwable e) {
            throw new ServiceException(
                    ErrorCode.SERVICE_DIRECTORY_SSLRUNTIMEEXCEPTION,
                    ErrorCode.SERVICE_DIRECTORY_SSLRUNTIMEEXCEPTION
                            .getMessageTemplate(), e);
        }
    }

    private static HttpResponse getHttpResponse(HttpURLConnection urlConnection) throws IOException {
        BufferedReader in = null;
        try {
            int errorCode = urlConnection.getResponseCode();
            // HTTP_OK (200), HTTP_CREATED (201), HTTP_ACCEPTED (202)
            if (((errorCode == HTTP_OK) || (errorCode == HTTP_CREATED) || errorCode == HTTP_ACCEPTED) ) {
                in = new BufferedReader(new InputStreamReader(
                        urlConnection.getInputStream()));
            } else {
                InputStream error = urlConnection.getErrorStream();
                if (error != null) {
                    in = new BufferedReader(new InputStreamReader(error));
                }
            }

            String json = null;
            if (in != null) {
                json = CharStreams.toString(in);
            }
            return new HttpResponse(errorCode, json);
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }

    private static void addCustomHeaders(HttpURLConnection urlConnection,
            Map<String, String> headers) {

        if (headers != null) {
            for (Entry<String, String> entry : headers.entrySet()) {
                urlConnection.addRequestProperty(entry.getKey(),
                        entry.getValue());
            }
        }
    }

}