commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
79f351e0dcb138d2fe55319f0018b2638dd59804 | Add unit tests for security_groups_client | vedujoshi/tempest,LIS/lis-tempest,Juniper/tempest,xbezdick/tempest,flyingfish007/tempest,masayukig/tempest,cisco-openstack/tempest,izadorozhna/tempest,rakeshmi/tempest,bigswitch/tempest,sebrandon1/tempest,Tesora/tesora-tempest,sebrandon1/tempest,Tesora/tesora-tempest,openstack/tempest,Juniper/tempest,rakeshmi/tempest,vedujoshi/tempest,izadorozhna/tempest,zsoltdudas/lis-tempest,openstack/tempest,masayukig/tempest,zsoltdudas/lis-tempest,tonyli71/tempest,cisco-openstack/tempest,LIS/lis-tempest,bigswitch/tempest,flyingfish007/tempest,tonyli71/tempest,xbezdick/tempest | tempest/tests/services/compute/test_security_groups_client.py | tempest/tests/services/compute/test_security_groups_client.py | # Copyright 2015 NEC Corporation. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslotest import mockpatch
from tempest_lib import exceptions as lib_exc
from tempest.services.compute.json import security_groups_client
from tempest.tests import fake_auth_provider
from tempest.tests.services.compute import base
class TestSecurityGroupsClient(base.BaseComputeServiceTest):
FAKE_SECURITY_GROUP_INFO = [{
"description": "default",
"id": "3fb26eb3-581b-4420-9963-b0879a026506",
"name": "default",
"rules": [],
"tenant_id": "openstack"
}]
def setUp(self):
super(TestSecurityGroupsClient, self).setUp()
fake_auth = fake_auth_provider.FakeAuthProvider()
self.client = security_groups_client.SecurityGroupsClient(
fake_auth, 'compute', 'regionOne')
def _test_list_security_groups(self, bytes_body=False):
self.check_service_client_function(
self.client.list_security_groups,
'tempest.common.service_client.ServiceClient.get',
{"security_groups": self.FAKE_SECURITY_GROUP_INFO},
to_utf=bytes_body)
def test_list_security_groups_with_str_body(self):
self._test_list_security_groups()
def test_list_security_groups_with_bytes_body(self):
self._test_list_security_groups(bytes_body=True)
def _test_show_security_group(self, bytes_body=False):
self.check_service_client_function(
self.client.show_security_group,
'tempest.common.service_client.ServiceClient.get',
{"security_group": self.FAKE_SECURITY_GROUP_INFO[0]},
to_utf=bytes_body,
security_group_id='fake-id')
def test_show_security_group_with_str_body(self):
self._test_show_security_group()
def test_show_security_group_with_bytes_body(self):
self._test_show_security_group(bytes_body=True)
def _test_create_security_group(self, bytes_body=False):
post_body = {"name": "test", "description": "test_group"}
self.check_service_client_function(
self.client.create_security_group,
'tempest.common.service_client.ServiceClient.post',
{"security_group": self.FAKE_SECURITY_GROUP_INFO[0]},
to_utf=bytes_body,
kwargs=post_body)
def test_create_security_group_with_str_body(self):
self._test_create_security_group()
def test_create_security_group_with_bytes_body(self):
self._test_create_security_group(bytes_body=True)
def _test_update_security_group(self, bytes_body=False):
req_body = {"name": "test", "description": "test_group"}
self.check_service_client_function(
self.client.update_security_group,
'tempest.common.service_client.ServiceClient.put',
{"security_group": self.FAKE_SECURITY_GROUP_INFO[0]},
to_utf=bytes_body,
security_group_id='fake-id',
kwargs=req_body)
def test_update_security_group_with_str_body(self):
self._test_update_security_group()
def test_update_security_group_with_bytes_body(self):
self._test_update_security_group(bytes_body=True)
def test_delete_security_group(self):
self.check_service_client_function(
self.client.delete_security_group,
'tempest.common.service_client.ServiceClient.delete',
{}, status=202, security_group_id='fake-id')
def test_is_resource_deleted_true(self):
mod = ('tempest.services.compute.json.security_groups_client.'
'SecurityGroupsClient.show_security_group')
self.useFixture(mockpatch.Patch(mod, side_effect=lib_exc.NotFound))
self.assertTrue(self.client.is_resource_deleted('fake-id'))
def test_is_resource_deleted_false(self):
mod = ('tempest.services.compute.json.security_groups_client.'
'SecurityGroupsClient.show_security_group')
self.useFixture(mockpatch.Patch(mod, return_value='success'))
self.assertFalse(self.client.is_resource_deleted('fake-id'))
| apache-2.0 | Python | |
ca30516df8037cfb0745f84481f7ada936447a8a | Support of old profile names | zhenkyn/vkfeedd,zhenkyn/vkfeedd,tol1k/vkfeed,kostkost/vkfeed,ALERTua/vkfeed,flyer2001/vkrss,KonishchevDmitry/vkfeed,antonsotin/vkfeedtrue,Densvin/RSSVK,ALERTua/vkfeed,Evorvian/vkfeed,KonishchevDmitry/vkfeed,flyer2001/vkrss,greengeez/vkfeed,schelkovo/rss,greengeez/vkfeed,lokineverdie/parservkrss1488,lokineverdie/parservkrss1488,antonsotin/vkfeedtrue,ByKRAK/app,Evorvian/vkfeed,schelkovo/rss,KonishchevDmitry/vkfeed,ByKRAK/app,tol1k/vkfeed,Densvin/RSSVK,antonsotin/vkfeedtrue,kostkost/vkfeed | vkfeed/pages/main.py | vkfeed/pages/main.py | # -*- coding: utf-8 -*-
'''Generates the main page.'''
import re
from google.appengine.ext import webapp
import vkfeed.util
class MainPage(webapp.RequestHandler):
'''Generates the main page.'''
def get(self):
'''Processes a GET request.'''
self.response.out.write(vkfeed.util.render_template('main.html'))
def post(self):
'''Processes a POST request.'''
profile_url = self.request.get('profile_url', '')
match = re.match(r'''^
\s*
(?:https?://(?:www\.)?(?:vk\.com|vkontakte\.ru)/)?
(?P<profile_id>[a-zA-Z0-9._-]{5,})/?
\s*
$''', profile_url, re.IGNORECASE | re.VERBOSE)
if match:
self.redirect('/feed/' + match.group('profile_id') + '/wall')
else:
self.response.out.write(vkfeed.util.render_template('main.html', {
'post_error': u'''
Неверно указан URL профиля.
Адрес должен быть вида http://vkontakte.ru/имя_профиля.
Имя профиля должно удовлетворять требованиям, предъявляемым администрацией ВКонтакте.
'''
}))
| # -*- coding: utf-8 -*-
'''Generates the main page.'''
import re
from google.appengine.ext import webapp
import vkfeed.util
class MainPage(webapp.RequestHandler):
'''Generates the main page.'''
def get(self):
'''Processes a GET request.'''
self.response.out.write(vkfeed.util.render_template('main.html'))
def post(self):
'''Processes a POST request.'''
profile_url = self.request.get('profile_url', '')
match = re.match(r'''^
\s*
(?:https?://(?:www\.)?(?:vk\.com|vkontakte\.ru)/)?
(?P<profile_id>[a-zA-Z0-9_-]{5,})/?
\s*
$''', profile_url, re.IGNORECASE | re.VERBOSE)
if match:
self.redirect('/feed/' + match.group('profile_id') + '/wall')
else:
self.response.out.write(vkfeed.util.render_template('main.html', {
'post_error': u'''
Неверно указан URL профиля.
Адрес должен быть вида http://vkontakte.ru/имя_профиля.
Имя профиля должно удовлетворять требованиям, предъявляемым администрацией ВКонтакте.
'''
}))
| bsd-2-clause | Python |
970516424632cb8cb3d70a1409f82822ff925c9f | Add cli keys lib for the saltkeys command | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | salt/cli/key.py | salt/cli/key.py | '''
The actual saltkey functional code
'''
import os
import sys
import shutil
class Key(object):
'''
The object that encapsulates saltkey actions
'''
def __init__(self, opts):
self.opts = opts
def _list_pre(self):
'''
List the unaccepted keys
'''
pre_dir = os.path.join(self.opts['pki_dir'], 'minions_pre')
if not os.path.isdir(pre_dir):
err = 'The minions_pre directory is not present, ensure that the'\
+ ' master server has been started'
sys.stderr.write(err + '\n')
sys.exit(42)
print 'Unaccepted Keys:'
for fn_ in os.listdir(pre_dir):
print fn_
def _list_accepted(self):
'''
List the accepted public keys
'''
minions = os.path.join(self.opts['pki_dir'], 'minions')
if not os.path.isdir(minions):
err = 'The minions directory is not present, ensure that the'\
+ ' master server has been started'
sys.stderr.write(err + '\n')
sys.exit(42)
print 'Accepted Keys:'
for fn_ in os.listdir(minions):
print fn_
def _list_all(self):
'''
List all keys
'''
self._list_pre()
self.list_accepted()
def _accept(self, key):
pre_dir = os.path.join(self.opts['pki_dir'], 'minions_pre')
minions = os.path.join(self.opts['pki_dir'], 'minions')
if not os.path.isdir(minions):
err = 'The minions directory is not present, ensure that the'\
+ ' master server has been started'
sys.stderr.write(err + '\n')
sys.exit(42)
if not os.path.isdir(pre_dir):
err = 'The minions_pre directory is not present, ensure that the'\
+ ' master server has been started'
sys.stderr.write(err + '\n')
sys.exit(42)
pre = os.listdir(pre_dir)
if not pre.count(key):
err = 'The named host is unavailable, please accept an available'\
+ ' key'
sys.stderr.write(err + '\n')
sys.exit(43)
shutil.move(os.path.join(pre_dir, key), os.path.join(minions, key))
def _accept_all(self):
'''
Accept all keys in pre
'''
pre_dir = os.path.join(self.opts['pki_dir'], 'minions_pre')
minions = os.path.join(self.opts['pki_dir'], 'minions')
if not os.path.isdir(minions):
err = 'The minions directory is not present, ensure that the'\
+ ' master server has been started'
sys.stderr.write(err + '\n')
sys.exit(42)
if not os.path.isdir(pre_dir):
err = 'The minions_pre directory is not present, ensure that the'\
+ ' master server has been started'
sys.stderr.write(err + '\n')
sys.exit(42)
for key in os.listdir(pre_dir):
self._accept(key)
def run(self):
'''
Run the logic for saltkey
'''
if opts['list']:
self._list()
elif opts['list_all']:
self._list_all()
elif opts['accept']:
self._accept(opts['accept'])
elif opts['accept_all']:
self._accept_all()
else:
self._list_all()
| apache-2.0 | Python | |
e67eb99442732339c8aee8a856ceb135fd8ff85d | move to python, mainly for json comparison | ministryofjustice/courtfinder-govuk-publisher-test,ministryofjustice/courtfinder-govuk-publisher-test | scripts/test.py | scripts/test.py | #!/usr/bin/env python
import requests
import json
base_url='http://127.0.0.1:8000/court/'
court_file='../data/sample_court.json'
oauth_token='foobar'
with open('../data/sample_court.json') as f:
sample_court_json = f.read()
headers = {'Authorization': 'Bearer '+oauth_token}
def is_in(small, big):
s = json.loads(small)
b = json.loads(big)
return all(item in b.items() for item in s.items())
def check(request, status_code, body=None, win='.'):
if request.status_code != status_code:
print "Different status codes: expected %d, got %d" % (status_code, request.status_code)
elif body:
if not is_in(request.text, body):
print "Different objects: expected %s, got %s" % (body, request.text)
else:
print win,
def list():
return requests.get(base_url, headers=headers)
def get(uuid):
return requests.get(base_url+uuid, headers=headers)
def put(uuid, json, auth=True):
if auth:
return requests.put(base_url+uuid, headers=headers, data=json)
else:
return requests.put(base_url+uuid, data=json)
def delete(uuid):
return requests.delete(base_url+uuid, headers=headers)
if __name__ == "__main__":
# hidden uuid to delete every court in the database
check(delete('all-the-things'), 200)
check(put('foo-bar', '[]', auth=False), 403)
check(list(), 200, '[]')
check(get('22984u-3482u49u'), 404)
check(put('22984u-3482u49u', sample_court_json), 201)
check(list(), 200, sample_court_json)
| mit | Python | |
4dfd34f002c613ab0f73f07fe4cae30e2ef9be6f | add a simple export tool for JSON performance scenarios | ejona86/grpc,stanley-cheung/grpc,vjpai/grpc,stanley-cheung/grpc,vjpai/grpc,grpc/grpc,ejona86/grpc,ejona86/grpc,jtattermusch/grpc,nicolasnoble/grpc,stanley-cheung/grpc,nicolasnoble/grpc,stanley-cheung/grpc,jtattermusch/grpc,ejona86/grpc,donnadionne/grpc,donnadionne/grpc,grpc/grpc,grpc/grpc,stanley-cheung/grpc,donnadionne/grpc,ejona86/grpc,donnadionne/grpc,ctiller/grpc,grpc/grpc,ejona86/grpc,ctiller/grpc,donnadionne/grpc,grpc/grpc,vjpai/grpc,ctiller/grpc,stanley-cheung/grpc,vjpai/grpc,grpc/grpc,nicolasnoble/grpc,donnadionne/grpc,ejona86/grpc,ctiller/grpc,nicolasnoble/grpc,grpc/grpc,stanley-cheung/grpc,vjpai/grpc,stanley-cheung/grpc,stanley-cheung/grpc,ctiller/grpc,vjpai/grpc,ctiller/grpc,ctiller/grpc,nicolasnoble/grpc,vjpai/grpc,jtattermusch/grpc,donnadionne/grpc,nicolasnoble/grpc,jtattermusch/grpc,nicolasnoble/grpc,donnadionne/grpc,jtattermusch/grpc,jtattermusch/grpc,ctiller/grpc,jtattermusch/grpc,jtattermusch/grpc,nicolasnoble/grpc,grpc/grpc,nicolasnoble/grpc,ejona86/grpc,ejona86/grpc,jtattermusch/grpc,ejona86/grpc,stanley-cheung/grpc,stanley-cheung/grpc,vjpai/grpc,vjpai/grpc,nicolasnoble/grpc,grpc/grpc,ctiller/grpc,ejona86/grpc,vjpai/grpc,jtattermusch/grpc,ctiller/grpc,vjpai/grpc,donnadionne/grpc,donnadionne/grpc,donnadionne/grpc,jtattermusch/grpc,vjpai/grpc,jtattermusch/grpc,stanley-cheung/grpc,ctiller/grpc,nicolasnoble/grpc,ejona86/grpc,nicolasnoble/grpc,donnadionne/grpc,grpc/grpc,ctiller/grpc,grpc/grpc,grpc/grpc | tools/run_tests/performance/scenario_config_exporter.py | tools/run_tests/performance/scenario_config_exporter.py | #!/usr/bin/env python3
# Copyright 2020 The gRPC Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# Helper script to extract JSON scenario definitions from scenario_config.py
import json
import re
import scenario_config
import sys
def get_json_scenarios(language_name, scenario_name_regex='.*', category='all'):
"""Returns list of scenarios that match given constraints."""
result = []
scenarios = scenario_config.LANGUAGES[language_name].scenarios()
for scenario_json in scenarios:
if re.search(scenario_name_regex, scenario_json['name']):
# if the 'CATEGORIES' key is missing, treat scenario as part of 'scalable' and 'smoketest'
# this matches the behavior of run_performance_tests.py
scenario_categories = scenario_json.get('CATEGORIES',
['scalable', 'smoketest'])
# TODO(jtattermusch): consider adding filtering for 'CLIENT_LANGUAGE' and 'SERVER_LANGUAGE'
# fields, before the get stripped away.
if category in scenario_categories or category == 'all':
scenario_json_stripped = scenario_config.remove_nonproto_fields(
scenario_json)
result.append(scenario_json_stripped)
return result
def dump_to_json_files(json_scenarios, filename_prefix='scenario_dump_'):
"""Dump a list of json scenarios to json files"""
for scenario in json_scenarios:
filename = "%s%s.json" % (filename_prefix, scenario['name'])
print('Writing file %s' % filename, file=sys.stderr)
with open(filename, 'w') as outfile:
json.dump(scenario, outfile, indent=2)
if __name__ == "__main__":
# example usage: extract C# scenarios and dump them as .json files
scenarios = get_json_scenarios('csharp',
scenario_name_regex='.*',
category='scalable')
dump_to_json_files(scenarios, 'scenario_dump_')
| apache-2.0 | Python | |
6dd7e2da8c87a663fe1fa68df4b727f2c12c4b21 | Create emailer.py | jvillacortam/SES_mailer | emailer.py | emailer.py | import threading
import boto, time
#Fill this array with a DB or CSV
emails = ['success@simulator.amazonses.com','success@simulator.amazonses.com','success@simulator.amazonses.com','success@simulator.amazonses.com','success@simulator.amazonses.com']
class SES():
client = None
def __init__(self):
self.access_key = '[PROVIDE ACCESS KEY HERE]'
self.secret_key = '[PROVIDE SECRET KEY HERE]'
self.burst = 5 #Default will be override
def get_ses_client(self):
if not self.client:
self.client = boto.connect_ses(self.access_key, self.secret_key)
dict_quota = self.client.get_send_quota()
self.burst = int(round(float(dict_quota['GetSendQuotaResponse']['GetSendQuotaResult']['MaxSendRate'])))
return self.client
SES = SES()
def send_email(recipient):
client = SES.get_ses_client()
success.append((recipient,'SUCCESS'))
client.send_email("test@test.com",'Testing','<html><h1>Test</html>',recipient,format='html')
print "Email sent to: " + str(recipient)
success = []
counter = 0
thread_list = []
global_start_time = time.clock()
start_time = time.clock()
for email in emails:
counter += 1
t = threading.Thread(target=send_email, args=(email,))
t.daemon = True
thread_list.append(t)
if counter % SES.burst == 0:
for thread in thread_list:
thread.start()
for thread in thread_list:
thread.join()
end_time = time.clock()
elapsed = end_time - start_time
if elapsed < 1:
sleep_time = 1 - elapsed
print "Sleeping Main Thread for: " + str(sleep_time)
time.sleep(sleep_time)
#Clear
start_time = time.clock()
thread_list = []
# Demonstrates that the main process waited for threads to complete
global_end_time = time.clock()
global_elapsed = global_end_time - global_start_time
print "Done - Elapsed: " + str(elapsed)
| apache-2.0 | Python | |
eec91552f05ca02fa8a8b9ad05bc732c5c099719 | Update postgresql.py | aaronkaplan/intelmq-old,aaronkaplan/intelmq-old,aaronkaplan/intelmq-old,Phantasus/intelmq,s4n7h0/intelmq | src/bots/outputs/postgresql/postgresql.py | src/bots/outputs/postgresql/postgresql.py | import sys
import psycopg2
from lib.bot import *
from lib.utils import *
from lib.event import *
class PostgreSQLBot(Bot):
def init(self):
try:
self.logger.debug("Connecting to PostgreSQL")
self.con = psycopg2.connect(
database=self.parameters.database,
user=self.parameters.user,
password=self.parameters.password,
host=self.parameters.host,
port=self.parameters.port
)
self.cur = self.con.cursor()
self.logger.info("Connected to PostgreSQL")
except psycopg2.DatabaseError, e:
self.logger.error("Problem found when bot tried to connect to PostgreSQL (%s)." % e)
self.stop()
def process(self):
event = self.receive_message()
if event:
evdict = event.to_dict()
keys = ", ".join(evdict.keys())
values = evdict.values()
fvalues = len(values) * "%s, "
query = "INSERT INTO logentry (" + keys + ") VALUES (" + fvalues[:-2] + ")"
try:
self.cur.execute(query, values)
except psycopg2.DatabaseError, e:
self.logger.error("Problem found when bot tried to insert data into PostgreSQL (%s)." % e)
self.stop()
self.con.commit()
self.acknowledge_message()
if __name__ == "__main__":
bot = PostgreSQLBot(sys.argv[1])
bot.start()
| import sys
import psycopg2
from lib.bot import *
from lib.utils import *
from lib.event import *
class PostgreSQLBot(Bot):
def init(self):
try:
self.logger.debug("Connecting to PostgreSQL")
self.con = psycopg2.connect(
database=self.parameters.database,
user=self.parameters.user,
password=self.parameters.password,
host=self.parameters.host,
port=self.parameters.port
)
self.cur = self.con.cursor()
self.logger.info("Connected to PostgreSQL")
except psycopg2.DatabaseError, e:
self.logger.error("Problem found when bot tried to connect to PostgreSQL (%s)." % e)
self.stop()
def process(self):
event = self.receive_message()
if event:
evdict = event.to_dict()
keys = ", ".join(evdict.keys())
values = evdict.values()
fvalues = len(VALUES) * "%s, "
query = "INSERT INTO logentry (" + keys + ") VALUES (" + fvalues[:-2] + ")"
try:
self.cur.execute(query, values)
except psycopg2.DatabaseError, e:
self.logger.error("Problem found when bot tried to insert data into PostgreSQL (%s)." % e)
self.stop()
self.con.commit()
self.acknowledge_message()
if __name__ == "__main__":
bot = PostgreSQLBot(sys.argv[1])
bot.start()
| agpl-3.0 | Python |
9a0c4225b542c2406e63f692a96222b2a8bd9940 | Use get_page_models instead of get_page_types in replace_text command | iansprice/wagtail,thenewguy/wagtail,kaedroho/wagtail,quru/wagtail,hamsterbacke23/wagtail,nealtodd/wagtail,kaedroho/wagtail,nutztherookie/wagtail,gogobook/wagtail,davecranwell/wagtail,mixxorz/wagtail,zerolab/wagtail,thenewguy/wagtail,zerolab/wagtail,kurtw/wagtail,torchbox/wagtail,torchbox/wagtail,rsalmaso/wagtail,JoshBarr/wagtail,FlipperPA/wagtail,Toshakins/wagtail,zerolab/wagtail,nealtodd/wagtail,iansprice/wagtail,serzans/wagtail,gasman/wagtail,hamsterbacke23/wagtail,kurtrwall/wagtail,jnns/wagtail,mikedingjan/wagtail,rsalmaso/wagtail,kurtw/wagtail,zerolab/wagtail,nutztherookie/wagtail,nealtodd/wagtail,chrxr/wagtail,timorieber/wagtail,nimasmi/wagtail,Toshakins/wagtail,takeflight/wagtail,serzans/wagtail,inonit/wagtail,davecranwell/wagtail,rsalmaso/wagtail,serzans/wagtail,takeflight/wagtail,kaedroho/wagtail,inonit/wagtail,torchbox/wagtail,FlipperPA/wagtail,serzans/wagtail,mikedingjan/wagtail,nilnvoid/wagtail,wagtail/wagtail,thenewguy/wagtail,iansprice/wagtail,nilnvoid/wagtail,rsalmaso/wagtail,JoshBarr/wagtail,rsalmaso/wagtail,gogobook/wagtail,chrxr/wagtail,davecranwell/wagtail,hamsterbacke23/wagtail,nimasmi/wagtail,mikedingjan/wagtail,hamsterbacke23/wagtail,chrxr/wagtail,thenewguy/wagtail,gasman/wagtail,wagtail/wagtail,timorieber/wagtail,nilnvoid/wagtail,wagtail/wagtail,kaedroho/wagtail,inonit/wagtail,gasman/wagtail,nutztherookie/wagtail,nilnvoid/wagtail,wagtail/wagtail,takeflight/wagtail,inonit/wagtail,timorieber/wagtail,davecranwell/wagtail,kurtw/wagtail,quru/wagtail,gasman/wagtail,mixxorz/wagtail,torchbox/wagtail,iansprice/wagtail,jnns/wagtail,jnns/wagtail,takeflight/wagtail,FlipperPA/wagtail,nimasmi/wagtail,JoshBarr/wagtail,mikedingjan/wagtail,mixxorz/wagtail,FlipperPA/wagtail,Toshakins/wagtail,nutztherookie/wagtail,timorieber/wagtail,kaedroho/wagtail,kurtrwall/wagtail,mixxorz/wagtail,zerolab/wagtail,chrxr/wagtail,gasman/wagtail,nealtodd/wagtail,jnns/wagtail,JoshBarr/wagtail,gogobook/wagtail,wagtail/wagtail,kurtw/wagtail,Toshakins/wagtail,nimasmi/wagtail,quru/wagtail,gogobook/wagtail,kurtrwall/wagtail,kurtrwall/wagtail,thenewguy/wagtail,quru/wagtail,mixxorz/wagtail | wagtail/wagtailcore/management/commands/replace_text.py | wagtail/wagtailcore/management/commands/replace_text.py | from django.core.management.base import BaseCommand
from django.db import models
from modelcluster.models import get_all_child_relations
from wagtail.wagtailcore.models import PageRevision, get_page_models
def replace_in_model(model, from_text, to_text):
text_field_names = [field.name for field in model._meta.fields if isinstance(field, models.TextField) or isinstance(field, models.CharField)]
updated_fields = []
for field in text_field_names:
field_value = getattr(model, field)
if field_value and (from_text in field_value):
updated_fields.append(field)
setattr(model, field, field_value.replace(from_text, to_text))
if updated_fields:
model.save(update_fields=updated_fields)
class Command(BaseCommand):
args = "<from text> <to text>"
def handle(self, from_text, to_text, **options):
for revision in PageRevision.objects.filter(content_json__contains=from_text):
revision.content_json = revision.content_json.replace(from_text, to_text)
revision.save(update_fields=['content_json'])
for page_class in get_page_models():
self.stdout.write("scanning %s" % page_class._meta.verbose_name)
child_relation_names = [rel.get_accessor_name() for rel in get_all_child_relations(page_class)]
for page in page_class.objects.all():
replace_in_model(page, from_text, to_text)
for child_rel in child_relation_names:
for child in getattr(page, child_rel).all():
replace_in_model(child, from_text, to_text)
| from django.core.management.base import BaseCommand
from django.db import models
from modelcluster.models import get_all_child_relations
from wagtail.wagtailcore.models import PageRevision, get_page_types
def replace_in_model(model, from_text, to_text):
text_field_names = [field.name for field in model._meta.fields if isinstance(field, models.TextField) or isinstance(field, models.CharField)]
updated_fields = []
for field in text_field_names:
field_value = getattr(model, field)
if field_value and (from_text in field_value):
updated_fields.append(field)
setattr(model, field, field_value.replace(from_text, to_text))
if updated_fields:
model.save(update_fields=updated_fields)
class Command(BaseCommand):
args = "<from text> <to text>"
def handle(self, from_text, to_text, **options):
for revision in PageRevision.objects.filter(content_json__contains=from_text):
revision.content_json = revision.content_json.replace(from_text, to_text)
revision.save(update_fields=['content_json'])
for content_type in get_page_types():
self.stdout.write("scanning %s" % content_type.name)
page_class = content_type.model_class()
child_relation_names = [rel.get_accessor_name() for rel in get_all_child_relations(page_class)]
for page in page_class.objects.all():
replace_in_model(page, from_text, to_text)
for child_rel in child_relation_names:
for child in getattr(page, child_rel).all():
replace_in_model(child, from_text, to_text)
| bsd-3-clause | Python |
dfcab560e684afc1463896c98b7a7eeffedf127d | Add oed command. | kivhift/qmk,kivhift/qmk | src/commands/oxford-english-dictionary.py | src/commands/oxford-english-dictionary.py | #
# Copyright (c) 2014 Joshua Hughes <kivhift@gmail.com>
#
import urllib
import webbrowser
import qmk
class OEDCommand(qmk.Command):
'''Look up the given argument using Oxford's dictionary search. A new tab
will be opened with the results.'''
def __init__(self):
self._name = 'oed'
self._help = self.__doc__
self.__baseURL = (
'http://www.oxforddictionaries.com/search/english/?q=%s')
@qmk.Command.actionRequiresArgument
def action(self, arg):
webbrowser.open_new_tab(self.__baseURL % urllib.quote_plus(
'-'.join(arg.split()).encode('utf-8')))
def commands(): return [ OEDCommand() ]
| mit | Python | |
6080a7475daef38037b8e8462a7a734380179e3f | Add script to find out click annotations missing help text | valohai/valohai-cli | scripts/ensure_click_help.py | scripts/ensure_click_help.py | import ast
import argparse
import sys
def stringify_name(name: ast.AST):
if isinstance(name, ast.Attribute):
return f"{stringify_name(name.value)}.{stringify_name(name.attr)}"
if isinstance(name, ast.Name):
return name.id
if isinstance(name, str):
return name
raise NotImplementedError(f"unstringifiable name/node {name} ({type(name)})")
class EnsureClickHelpWalker(ast.NodeVisitor):
def __init__(self, add_message):
self.add_message = add_message
def visit_FunctionDef(self, node):
for deco in node.decorator_list:
self.process_decorator(deco)
def process_decorator(self, deco):
if isinstance(deco, ast.Call):
deco_name = stringify_name(deco.func)
if deco_name in ("click.option",):
kwargs = {stringify_name(kw.arg): kw.value for kw in deco.keywords}
if "help" not in kwargs:
self.add_message(deco, f"missing `help=`")
def process_file(filename):
with open(filename, "r") as infp:
tree = ast.parse(infp.read(), filename=filename)
messages = []
def add_message(node, message):
messages.append(f"{filename}:{node.lineno}: {message}")
EnsureClickHelpWalker(add_message=add_message).visit(tree)
return messages
def main():
ap = argparse.ArgumentParser()
ap.add_argument("files", metavar="FILE", nargs="*")
args = ap.parse_args()
n_messages = 0
for file in args.files:
for message in process_file(file):
print(message)
n_messages += 1
sys.exit(n_messages)
if __name__ == "__main__":
main()
| mit | Python | |
55e247b407cf677c68c564f60a5cd2d5885e1a25 | add new package (#24929) | LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/py-pydocstyle/package.py | var/spack/repos/builtin/packages/py-pydocstyle/package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyPydocstyle(PythonPackage):
"""Python docstring style checker."""
homepage = "https://github.com/PyCQA/pydocstyle/"
pypi = "pydocstyle/pydocstyle-6.1.1.tar.gz"
version('6.1.1', sha256='1d41b7c459ba0ee6c345f2eb9ae827cab14a7533a88c5c6f7e94923f72df92dc')
variant('toml', default=True, description='Allow pydocstyle to read pyproject.toml')
depends_on('python@3.6:', type=('build', 'run'))
depends_on('py-setuptools', type=('build', 'run'))
depends_on('py-snowballstemmer', type=('build', 'run'))
depends_on('py-toml', when='+toml', type=('build', 'run'))
| lgpl-2.1 | Python | |
d570a0f32375cc4719bb6815da25a5b3168f2313 | Add execute script | pcostesi/hookit,pcostesi/hookit | execute.py | execute.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from hookit import *
def consume_event(event):
event.dispatched = True
event.save()
return event
def process_events(events):
for event in events:
print event
consume_event(event)
#recipe = find_recipe(event)
#run_recipe(recipe)
if __name__ == '__main__':
try:
PushEvent.create_table()
Recipe.create_table()
except:
pass
events = PushEvent.select().where(PushEvent.dispatched==False)
process_events(events)
| mit | Python | |
b838c9eb504f4510537d66d504c9d4d2e1a81de5 | add tools for extracting some info | DeercoderPractice/tools,DeercoderPractice/tools | extract.py | extract.py | #!/usr/bin/env python
handler = open("pinpow1800MW.out", "r+")
lines = handler.readlines()
output = open("data.out", "w+")
writing = False
for line in lines:
# print line
if "Material powers" in line:
writing = True
elif "--------------------------------------------------------------" in line:
if writing == True:
output.write(line)
output.write("\n")
writing = False
if writing == True:
output.write(line)
handler.close()
output.close()
| apache-2.0 | Python | |
3154563f5b21b8728d6ed9eadd1ed031cd223131 | Update classifier | PlutusApp/templates,PlutusApp/templates,PlutusApp/templates | scilearn.py | scilearn.py | from sklearn import tree
import json
data = 0
with open('./training_data/data.txt') as json_data:
data = json.load(json_data)
targets = 0
with open('./training_data/targets.txt') as json_data:
targets = json.load(json_data)
print(data)
clf = tree.DecisionTreeClassifier()
clf = clf.fit(data,targets)
print('Loaded model ...')
while(1):
print('Enter data')
mi = double(raw_input('Enter monthly income'))
me = double(raw_input('Enter monthly expenditure'))
ti = mi*12
rcs = double(raw_input('Enter rate of change of savings'))
age = double(raw_input('Enter age'))
ta = double(raw_input('Enter monthly bank balance'))
print('Predicting ...')
print(clf.predict([[mi, me, ti, rcs, age, ta]]))
| mit | Python | |
a142472b86044395e428abea2fa5ff28b892d1fb | Create attr-utils module; create attribute memoization helper | fire-uta/iiix-data-parser | attr_utils.py | attr_utils.py | def _set_attr( obj, attr_name, value_to_set ):
setattr( obj, attr_name, value_to_set )
return getattr( obj, attr_name )
def _memoize_attr( obj, attr_name, value_to_set ):
return getattr( obj, attr_name, _set_attr( obj, attr_name, value_to_set ) )
| mit | Python | |
c563972de0260201300ef2e9b97746d20f02b824 | add quadruplets.py | pepincho/Python101-and-Algo1-Courses,pepincho/HackBulgaria,pepincho/Python101-and-Algo1-Courses,pepincho/HackBulgaria | Algo-1/week2/3-Quadruplets/quadruplets.py | Algo-1/week2/3-Quadruplets/quadruplets.py | # Returns the number of quadruplets that sum to zero.
# a - [int]
# b - [int]
# d - [int]
# c - [int]
# a + b == -(c + d)
# sort
# binary search
def zero_quadruplets_count(a, b, c, d):
left_sums = []
right_sums = []
result = 0
for i in a:
for j in b:
left_sums.append(i + j)
for i in c:
for j in d:
right_sums.append(i + j)
for i in left_sums:
for j in right_sums:
if i + j == 0:
result += 1
return result
def main():
a = [5, 3, 4]
b = [-2, -1, 6]
c = [-1, -2, 4]
d = [-1, -2, 7]
print(zero_quadruplets_count(a, b, c, d))
if __name__ == '__main__':
main()
| mit | Python | |
74e261b0f68426cd9d82e7b8f832d0f9913dd4ae | Test for apikeys, was missing in bd40e3122bf448946c4ea505c28b4a947b26d5e1 | amiv-eth/amivapi,amiv-eth/amivapi,amiv-eth/amivapi | amivapi/tests/test_apikeys.py | amivapi/tests/test_apikeys.py | from amivapi.tests import util
class APIKeyTest(util.WebTest):
def test_get_users_with_apikey(self):
apikey = u"dsfsjkdfsdhkfhsdkfjhsdfjh"
self.app.config['APIKEYS'][apikey] = {
'name': 'Testkey',
'users': {'GET': 1},
}
items = self.api.get("/users", token=apikey, status_code=200).\
json['_items']
# Can we see the root user?
self.assertTrue(util.find_by_pair(items, "id", 0) is not None)
| agpl-3.0 | Python | |
72ffe438270fb54a1ce163faff6d2083079c77e2 | Add unit test of utils module. | gvkalra/python-anydo,gvkalra/python-anydo | anydo/lib/tests/test_utils.py | anydo/lib/tests/test_utils.py | # -*- coding: utf-8 -*-
import unittest
import re
import sys
import os.path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from anydo.lib import utils
class UtilsTests(unittest.TestCase):
def setUp(self):
self.pattern = re.compile('(^([\w-]+)==$)', flags=re.U)
def test_create_uuid(self):
self.assertTrue(self.pattern.match(utils.create_uuid()))
def test_encode_string(self):
self.assertEqual(utils.encode_string('test'), 'test')
self.assertEqual(utils.encode_string('1234'), '1234')
self.assertEqual(utils.encode_string('test1234 Äë'), 'test1234 Äë')
# "テスト" means "test" in Japansese.
if sys.version_info < (3, 0):
word = ('\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88 123eA'
'\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88')
else:
word = 'テスト 123eAテスト'
self.assertEqual(utils.encode_string('テスト 123eAテスト'), word)
| mit | Python | |
75ca02b335c4aa20cbb139e68c660e1242800cc0 | Add the init method to the user model. | yiyangyi/cc98-tornado | model/user.py | model/user.py | #!/usr/bin/env python
# coding=utf-8
class UserModel(Query):
def __init__(self, db):
self.db = db
self.table_name = 'user'
super(UserModel, self).__init__()
| mit | Python | |
6ebcd970d980a93c1fca66463e74b52b451eef61 | Create a new wifi download test for ChromeOS | TheTypoMaster/chromium-crosswalk,pozdnyakov/chromium-crosswalk,mogoweb/chromium-crosswalk,Fireblend/chromium-crosswalk,Chilledheart/chromium,nacl-webkit/chrome_deps,ondra-novak/chromium.src,bright-sparks/chromium-spacewalk,Just-D/chromium-1,hgl888/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,Chilledheart/chromium,PeterWangIntel/chromium-crosswalk,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,Pluto-tv/chromium-crosswalk,zcbenz/cefode-chromium,pozdnyakov/chromium-crosswalk,keishi/chromium,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,rogerwang/chromium,zcbenz/cefode-chromium,M4sse/chromium.src,axinging/chromium-crosswalk,littlstar/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,mogoweb/chromium-crosswalk,jaruba/chromium.src,Jonekee/chromium.src,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,ltilve/chromium,anirudhSK/chromium,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,anirudhSK/chromium,bright-sparks/chromium-spacewalk,markYoungH/chromium.src,dushu1203/chromium.src,keishi/chromium,pozdnyakov/chromium-crosswalk,markYoungH/chromium.src,zcbenz/cefode-chromium,rogerwang/chromium,bright-sparks/chromium-spacewalk,Just-D/chromium-1,Just-D/chromium-1,hgl888/chromium-crosswalk,ltilve/chromium,mohamed--abdel-maksoud/chromium.src,keishi/chromium,zcbenz/cefode-chromium,ondra-novak/chromium.src,Jonekee/chromium.src,chuan9/chromium-crosswalk,M4sse/chromium.src,junmin-zhu/chromium-rivertrail,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,dushu1203/chromium.src,chuan9/chromium-crosswalk,timopulkkinen/BubbleFish,fujunwei/chromium-crosswalk,robclark/chromium,ondra-novak/chromium.src,ChromiumWebApps/chromium,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,krieger-od/nwjs_chromium.src,ltilve/chromium,hgl888/chromium-crosswalk,littlstar/chromium.src,timopulkkinen/BubbleFish,axinging/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Fireblend/chromium-crosswalk,robclark/chromium,PeterWangIntel/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,dednal/chromium.src,anirudhSK/chromium,robclark/chromium,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,dushu1203/chromium.src,ltilve/chromium,littlstar/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,robclark/chromium,mogoweb/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,Jonekee/chromium.src,ondra-novak/chromium.src,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk,dednal/chromium.src,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,ChromiumWebApps/chromium,robclark/chromium,nacl-webkit/chrome_deps,markYoungH/chromium.src,junmin-zhu/chromium-rivertrail,keishi/chromium,mogoweb/chromium-crosswalk,M4sse/chromium.src,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,Just-D/chromium-1,patrickm/chromium.src,ltilve/chromium,Pluto-tv/chromium-crosswalk,timopulkkinen/BubbleFish,jaruba/chromium.src,keishi/chromium,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,Pluto-tv/chromium-crosswalk,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,hgl888/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,Fireblend/chromium-crosswalk,jaruba/chromium.src,TheTypoMaster/chromium-crosswalk,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,hgl888/chromium-crosswalk,zcbenz/cefode-chromium,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,ltilve/chromium,keishi/chromium,M4sse/chromium.src,Pluto-tv/chromium-crosswalk,axinging/chromium-crosswalk,hujiajie/pa-chromium,ondra-novak/chromium.src,jaruba/chromium.src,mogoweb/chromium-crosswalk,littlstar/chromium.src,hgl888/chromium-crosswalk,rogerwang/chromium,jaruba/chromium.src,axinging/chromium-crosswalk,keishi/chromium,ltilve/chromium,ChromiumWebApps/chromium,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,zcbenz/cefode-chromium,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,chuan9/chromium-crosswalk,patrickm/chromium.src,rogerwang/chromium,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,patrickm/chromium.src,robclark/chromium,dushu1203/chromium.src,ondra-novak/chromium.src,axinging/chromium-crosswalk,fujunwei/chromium-crosswalk,dednal/chromium.src,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk-efl,rogerwang/chromium,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,dednal/chromium.src,PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,mogoweb/chromium-crosswalk,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,pozdnyakov/chromium-crosswalk,hgl888/chromium-crosswalk-efl,robclark/chromium,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,krieger-od/nwjs_chromium.src,keishi/chromium,Just-D/chromium-1,nacl-webkit/chrome_deps,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,dednal/chromium.src,rogerwang/chromium,M4sse/chromium.src,Fireblend/chromium-crosswalk,anirudhSK/chromium,fujunwei/chromium-crosswalk,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,bright-sparks/chromium-spacewalk,Chilledheart/chromium,anirudhSK/chromium,hgl888/chromium-crosswalk-efl,dushu1203/chromium.src,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,patrickm/chromium.src,Just-D/chromium-1,ondra-novak/chromium.src,dushu1203/chromium.src,Jonekee/chromium.src,axinging/chromium-crosswalk,bright-sparks/chromium-spacewalk,mohamed--abdel-maksoud/chromium.src,crosswalk-project/chromium-crosswalk-efl,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,anirudhSK/chromium,Fireblend/chromium-crosswalk,littlstar/chromium.src,junmin-zhu/chromium-rivertrail,timopulkkinen/BubbleFish,mogoweb/chromium-crosswalk,patrickm/chromium.src,markYoungH/chromium.src,nacl-webkit/chrome_deps,jaruba/chromium.src,timopulkkinen/BubbleFish,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,fujunwei/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk-efl,keishi/chromium,TheTypoMaster/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,hgl888/chromium-crosswalk,junmin-zhu/chromium-rivertrail,M4sse/chromium.src,dednal/chromium.src,markYoungH/chromium.src,Fireblend/chromium-crosswalk,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,bright-sparks/chromium-spacewalk,rogerwang/chromium,ChromiumWebApps/chromium,ltilve/chromium,crosswalk-project/chromium-crosswalk-efl,rogerwang/chromium,krieger-od/nwjs_chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,junmin-zhu/chromium-rivertrail,patrickm/chromium.src,dushu1203/chromium.src,dednal/chromium.src,Chilledheart/chromium,hgl888/chromium-crosswalk,hujiajie/pa-chromium,chuan9/chromium-crosswalk,rogerwang/chromium,junmin-zhu/chromium-rivertrail,ondra-novak/chromium.src,jaruba/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,hgl888/chromium-crosswalk-efl,ChromiumWebApps/chromium,patrickm/chromium.src,dednal/chromium.src,hujiajie/pa-chromium,dednal/chromium.src,mohamed--abdel-maksoud/chromium.src,M4sse/chromium.src,markYoungH/chromium.src,hujiajie/pa-chromium,zcbenz/cefode-chromium,markYoungH/chromium.src,Jonekee/chromium.src,ChromiumWebApps/chromium,pozdnyakov/chromium-crosswalk,fujunwei/chromium-crosswalk,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,Fireblend/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,krieger-od/nwjs_chromium.src,anirudhSK/chromium,nacl-webkit/chrome_deps,M4sse/chromium.src,Chilledheart/chromium,nacl-webkit/chrome_deps,nacl-webkit/chrome_deps,anirudhSK/chromium,krieger-od/nwjs_chromium.src,TheTypoMaster/chromium-crosswalk,jaruba/chromium.src,rogerwang/chromium,robclark/chromium,krieger-od/nwjs_chromium.src,robclark/chromium,nacl-webkit/chrome_deps,keishi/chromium,chuan9/chromium-crosswalk,dednal/chromium.src,Pluto-tv/chromium-crosswalk,robclark/chromium,krieger-od/nwjs_chromium.src,M4sse/chromium.src,PeterWangIntel/chromium-crosswalk,fujunwei/chromium-crosswalk,Pluto-tv/chromium-crosswalk,Chilledheart/chromium,hujiajie/pa-chromium,crosswalk-project/chromium-crosswalk-efl,Just-D/chromium-1,zcbenz/cefode-chromium,anirudhSK/chromium,keishi/chromium,pozdnyakov/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,littlstar/chromium.src,markYoungH/chromium.src,M4sse/chromium.src,jaruba/chromium.src,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,ltilve/chromium,anirudhSK/chromium,Jonekee/chromium.src,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,ChromiumWebApps/chromium,ChromiumWebApps/chromium,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,timopulkkinen/BubbleFish,markYoungH/chromium.src,littlstar/chromium.src,axinging/chromium-crosswalk,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,junmin-zhu/chromium-rivertrail,jaruba/chromium.src,markYoungH/chromium.src,mogoweb/chromium-crosswalk,patrickm/chromium.src,anirudhSK/chromium | chrome/test/functional/wifi_downloads.py | chrome/test/functional/wifi_downloads.py | #!/usr/bin/python
# Copyright (c) 2011 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import hashlib
import logging
import os
import time
import pyauto_functional # Must be imported before pyauto
import pyauto
import pyauto_utils
import chromeos_network
class WifiDownloadsTest(chromeos_network.PyNetworkUITest):
"""TestCase for ChromeOS Wifi Downloads
This test makes a few assumptions. It needs to have access to the power
strip used in pyautolib/chromeos/wifi_downloads.py. It also assumes access
to the server 172.22.12.98:8080. If the server is passed a filname in the
format <integer>.lf, it will generate a file of size <integer> in KB. In
addition the name of the file returned is the md5 checksum of the file.
"""
def setUp(self):
chromeos_network.PyNetworkUITest.setUp(self)
self.InitWifiPowerStrip()
# The power strip is a shared resource and if we every crash in the middle
# of a test we will be in an unknown state. This returns us to 'all off'.
self.PowerDownAllRouters()
# Downloading files of a large size, can take a while, bump the timeout
self.changer = pyauto.PyUITest.ActionTimeoutChanger(self, 4 * 1000 * 60)
def _Md5Checksum(self, file_path):
"""Returns the md5 checksum of a file at a given path.
Args:
file_path: The complete path of the file to generate the md5 checksum for.
"""
file_handle = open(file_path, 'rb')
m = hashlib.md5()
while True:
data = file_handle.read(8192)
if not data:
break
m.update(data)
file_handle.close()
return m.hexdigest()
def _ConnectToRouterAndVerify(self, router_name):
"""Generic routine for connecting to a router.
Args:
router_name: The name of the router to connect to.
"""
router = self.GetRouterConfig(router_name)
self.RouterPower(router_name, True)
self.assertTrue(self.WaitUntilWifiNetworkAvailable(router['ssid']),
'Wifi network %s never showed up.' % router['ssid'])
# Verify connect did not have any errors.
error = self.ConnectToWifiRouter(router_name)
self.assertFalse(error, 'Failed to connect to wifi network %s. '
'Reason: %s.' % (router['ssid'], error))
# Verify the network we connected to.
ssid = self.GetConnectedWifi()
self.assertEqual(ssid, router['ssid'],
'Did not successfully connect to wifi network %s.' % ssid)
def _DownloadAndVerifyFile(self, download_url):
"""Downloads a file at a given URL and validates it
This method downloads a file from a server whose filename matches the md5
checksum. Then we manually generate the md5 and check it against the
filename.
Args:
download_url: URL of the file to download.
"""
start = time.time()
# Make a copy of the download directory now to work around segfault
downloads_dir = self.GetDownloadDirectory().value()
self.DownloadAndWaitForStart(download_url)
self.WaitForAllDownloadsToComplete()
end = time.time()
logging.info('Download took %2.2f seconds to complete' % (end - start))
downloaded_files = os.listdir(downloads_dir)
self.assertEqual(len(downloaded_files), 1, msg='Expected only one file in '
'the Downloads folder, there are more.')
self.assertFalse(len(downloaded_files) == 0, msg='Expected only one file in'
' the Downloads folder, there are none.')
filename = os.path.splitext(downloaded_files[0])[0]
file_path = os.path.join(self.GetDownloadDirectory().value(),
downloaded_files[0])
md5_sum = self._Md5Checksum(file_path)
self.assertEqual(filename, md5_sum, 'The checksums do not match. The '
'download is incomplete.')
def testDownload1MBFile(self):
"""Test downloading a 1MB file from a wireless router."""
download_url = 'http://172.22.12.98:8080/1024.lf'
self._ConnectToRouterAndVerify('Nfiniti')
self._DownloadAndVerifyFile(download_url)
self.DisconnectFromWifiNetwork()
def testDownload10MBFile(self):
"""Test downloading a 10MB file from a wireless router."""
download_url = 'http://172.22.12.98:8080/10240.lf'
self._ConnectToRouterAndVerify('Belkin_N+')
self._DownloadAndVerifyFile(download_url)
self.DisconnectFromWifiNetwork()
def testDownload100MBFile(self):
"""Test downloading a 10MB file from a wireless router."""
download_url = 'http://172.22.12.98:8080/102400.lf'
self._ConnectToRouterAndVerify('Trendnet_639gr')
self._DownloadAndVerifyFile(download_url)
self.DisconnectFromWifiNetwork()
if __name__ == '__main__':
pyauto_functional.Main()
| bsd-3-clause | Python | |
7875ebfb51d21cfd92d08288e03a3642e7ceb33e | Create pset3.py | gaurav61/MIT6.00x | pset3.py | pset3.py | # PROBLEM 1 : Radiation Exposure
def radiationExposure(start, stop, step):
'''
Computes and returns the amount of radiation exposed
to between the start and stop times. Calls the
function f (defined for you in the grading script)
to obtain the value of the function at any point.
start: integer, the time at which exposure begins
stop: integer, the time at which exposure ends
step: float, the width of each rectangle. You can assume that
the step size will always partition the space evenly.
returns: float, the amount of radiation exposed to
between start and stop times.
'''
# FILL IN YOUR CODE HERE...
ans=0.0
i=start
while i<stop:
ans=ans+(step*f(i))
i=i+step
return ans
# PROBLEM 2 : Hangman Part 1: Is the Word Guessed
def isWordGuessed(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: boolean, True if all the letters of secretWord are in lettersGuessed;
False otherwise
'''
# FILL IN YOUR CODE HERE...
for i in secretWord:
if i not in lettersGuessed:
return False
return True
# PROBLEM 3 : Printing Out the User's Guess
def getGuessedWord(secretWord, lettersGuessed):
'''
secretWord: string, the word the user is guessing
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters and underscores that represents
what letters in secretWord have been guessed so far.
'''
# FILL IN YOUR CODE HERE...
srr=''
for i in secretWord:
if i not in lettersGuessed:
srr=srr+'_ '
else:
srr=srr+i+' '
# PROBLEM 4 : Printing Out all Available Letters
def getAvailableLetters(lettersGuessed):
'''
lettersGuessed: list, what letters have been guessed so far
returns: string, comprised of letters that represents what letters have not
yet been guessed.
'''
# FILL IN YOUR CODE HERE...
srr=''
for i in 'abcdefghijklmnopqrstuvwxyz':
if i not in lettersGuessed:
srr=srr+i
return srr
# PROBLEM 5 : Hangman Part 2: The Game/Complex Tests
def getAvailableLetters(lettersGuessed):
srr=''
for i in 'abcdefghijklmnopqrstuvwxyz':
if i not in lettersGuessed:
srr=srr+i
return srr
def isWordGuessed(secretWord, lettersGuessed):
for i in secretWord:
if i not in lettersGuessed:
return False
return True
def isWordGuessed2(secretWord, lettersGuessed):
for i in secretWord:
if i in lettersGuessed:
return True
return False
def getWordGuessed(secretWord, lettersGuessed):
srr=''
for i in secretWord:
if i not in lettersGuessed:
srr=srr+'_ '
else:
srr=srr+i
return srr
def hangman(secretWord):
flag=0
print ('Welcome to the game, Hangman!')
print 'I am thinking of a word that is '+str(len(secretWord))+' letters long'
print('-------------')
g=8
l=[]
while g>0:
print 'You have '+str(g)+' guesses left'
print 'Available Letters: '+getAvailableLetters(l)
opt=raw_input('Please guess a letter: ')
opt=opt.lower()
if opt in l:
print 'Oops! You\'ve already guessed that letter: '+getWordGuessed(secretWord,l)
print('-------------')
continue
l.append(opt)
if isWordGuessed2(secretWord,l[len(l)-1:len(l)])==True:
print 'Good guess: '+getWordGuessed(secretWord,l)
print('-------------')
else:
print 'Oops! That letter is not in my word: '+getWordGuessed(secretWord,l)
print('-------------')
g-=1
if isWordGuessed(secretWord,l)==True:
flag=1
break
if flag==1:
print 'Congratulations, you won!'
else:
print 'Sorry, you ran out of guesses. The word was '+secretWord
| mit | Python | |
d065ee15d2c189e2b0885d111aaaa109ca02ab99 | add stupid image extract program | JamisHoo/Distributed-Image-Search-Engine,JamisHoo/Distributed-Image-Search-Engine,JamisHoo/Distributed-Image-Search-Engine,JamisHoo/Distributed-Image-Search-Engine | src/image_extract.py | src/image_extract.py | #!/usr/bin/env python
###############################################################################
# Copyright (c) 2015 Jamis Hoo
# Distributed under the MIT license
# (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
#
# Project:
# Filename: image_extract.py
# Version: 1.0
# Author: Jamis Hoo
# E-mail: hjm211324@gmail.com
# Date: Jul 27, 2015
# Time: 15:15:10
# Description:
###############################################################################
from __future__ import print_function
import socket
import functools
import pyhdfs
LISTEN_ADDR = "localhost"
LISTEN_PORT = 20003
HDFS_HOST = "localhost:50070"
HDFS_IMAGENET = "/imagenet/"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((LISTEN_ADDR, LISTEN_PORT))
sock.listen(1)
hdfs_client = pyhdfs.HdfsClient(hosts = HDFS_HOST)
def process_query(query, client_sock):
global hdfs_client
global sock
counter, position = query.split(":")
block_no, offset, length = map(functools.partial(int, base = 16), position.split(","))
image = hdfs_client.open(HDFS_IMAGENET + format(block_no, "08x"), offset = offset, length = length).read()
client_sock.send(counter + ":" + image)
while True:
client_sock, client_addr = sock.accept()
try:
buff = ""
while True:
buff += client_sock.recv(1024 * 1024)
pos = buff.find("\n")
if pos != -1:
process_query(buff[: pos], client_sock)
buff = buff[pos + 1:]
except Exception as e:
print("Connection failed. ")
print(e)
| mit | Python | |
36a2f0de9f525ea030e4cc805b8ccc7eb29c8098 | Add dependency function (not finished yet) | howl-anderson/vimapt,howl-anderson/vimapt | src/vimapt/library/vimapt/Dependency.py | src/vimapt/library/vimapt/Dependency.py | import networkx as nx
class Dependency(object):
def __init__(self, package_name):
self.package_name = package_name
self.dependency_graph = nx.DiGraph()
self.dependency_graph.add_node(self.package_name)
self.top_node_name = self.package_name
def parse(self, dependency_specification):
node_name = self.get_node_name(dependency_specification)
dependency_specification_list = self.get_dependency_specification_list(dependency_specification)
for child_dependency_specification in dependency_specification_list:
child_node_name = self.get_node_name(child_dependency_specification)
self.dependency_graph.add_node(child_node_name)
self.dependency_graph.add_edge(node_name, child_node_name)
self.parse(child_dependency_specification)
def get_dependency_specification_list(self, dependency_specification):
return []
def get_node_name(self, dependency_specification):
return [] | mit | Python | |
ac3d92025c033a77718467fe611d15055f87f1b7 | add member.py (in models package) | dsarkozi/care4care-sdp-grp4 | Care4Care/C4CApplication/models/member.py | Care4Care/C4CApplication/models/member.py | from django.db import models
class Member(models.Model):
mail = models.EmailField(primary_key=True)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=30)
picture = models.ImageField()
birthday = models.DateField()
tag = models.SmallIntegerField()
status = models.BooleanField()
mobile = models.CharField(max_length=15)
telephone = models.CharField(max_length=15)
register_date = models.DateField()
dash_board_text = models.TextField()
adresse = models.CharField(max_length=200)
visibility = models.SmallIntegerField()
time_credit = models.BigIntegerField()
accepted = models.BooleanField()
| agpl-3.0 | Python | |
bea711b4560cf0373188f9e198fb2aa228227ee4 | add python ver | heLomaN/let_mosquito_go | mosquitogo.py | mosquitogo.py | #!/usr/bin/env python3
import wave
from struct import pack
from math import sin, pi
RATE=44100
## GENERATE MONO FILE ##
wv = wave.open('mg.wav', 'w')
wv.setparams((1, 2, RATE, 0, 'NONE', 'not compressed'))
maxVol=2**15-1.0 #maximum amplitude
wvData=b""
for i in range(0, RATE*3):
wvData+=pack('h', round(maxVol*sin(i*2*pi*18000.0/RATE)))
wv.writeframes(wvData)
wv.close()
import os
os.system("aplay mg.wav")
| apache-2.0 | Python | |
e7b85a4afc9f40073e59a51f9335a72afb543d87 | Add flask service. | supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer,supersaiyanmode/HomePiServer | app/services/flask/service.py | app/services/flask/service.py | from .base import BaseService
def configure_flask_logging(app):
for handler in logging.getLogger().handlers:
app.logger.addHandler(handler)
class FlaskServer(BaseService):
def __init__(self):
params = {
"template_folder": "../templates",
"static_folder": "../static"
}
self.flask_app = Flask(__name__, **params)
for prefix, controller in scan_blueprint():
self.flask_app.register_blueprint(controller, url_prefix=prefix)
configure_flask_logging(self.flask_app)
def service_start(self, *args, **kwargs):
from app.main import create_app
flask_app, sock_app = create_app()
port = flask_app.config["PORT"]
sock_app.run(flask_app, host="0.0.0.0", debug=True, use_reloader=False)
def service_stop(self):
pass
| mit | Python | |
6b364f7f76fd897000d9e6f9140a2ad7794bc1ed | make it easier to create superuser | avlach/univbris-ocf,avlach/univbris-ocf,avlach/univbris-ocf,avlach/univbris-ocf | src/python/scripts/create-superuser.py | src/python/scripts/create-superuser.py | '''
Created on Jun 30, 2010
@author: jnaous
'''
def run():
from django.contrib.auth.models import User
import os
if "SUPERUSER_PASSWD" not in os.environ:
print "SUPERUSER_PASSWD environment is not set. Set this var to the\
password of the super user."
return
if "SUPERUSER_USERNAME" not in os.environ:
print "SUPERUSER_USERNAME environment is not set. Set this var to the\
username of the super user."
return
if "SUPERUSER_EMAIL" not in os.environ:
print "SUPERUSER_EMAIL environment is not set. Set this var to the\
email address of the super user."
return
username = os.environ["SUPERUSER_USERNAME"]
password = os.environ["SUPERUSER_PASSWD"]
email = os.environ["SUPERUSER_EMAIL"]
print "Creating superuser %s" % username
User.objects.create_superuser(username, email, password)
| bsd-3-clause | Python | |
fac2449c5e1e5c3509ca39e7e40a75c4b1b0bfa9 | Create items.py | Alex55ok/Huxiu_Startup_Data | items.py | items.py | # -*- coding: utf-8 -*-
from scrapy.item import Item,Field
class HuxiuItem(Item):
huxiuNo = Field()
Name = Field()
Website = Field()
CompanyName = Field()
FoundDate = Field()
District = Field()
CompanyScale = Field()
FinancingStage = Field()
Tag = Field()
Intro = Field()
BreifIntro = Field()
FinancingStage1 = Field()
FinancingDate1 = Field()
FinancingVC1 = Field()
FinancingAmount1 = Field()
FinancingUnit1 = Field()
FinancingStage2 = Field()
FinancingDate2 = Field()
FinancingVC2 = Field()
FinancingAmount2 = Field()
FinancingUnit2 = Field()
FinancingStage3 = Field()
FinancingDate3 = Field()
FinancingVC3 = Field()
FinancingAmount3 = Field()
FinancingUnit3 = Field()
FinancingStage4 = Field()
FinancingDate4 = Field()
FinancingVC4 = Field()
FinancingAmount4 = Field()
FinancingUnit4 = Field()
FinancingStage5 = Field()
FinancingDate5 = Field()
FinancingVC5 = Field()
FinancingAmount5 = Field()
FinancingUnit5 = Field()
Founders1 = Field()
Position1 = Field()
FounderIntro1 = Field()
Founders2 = Field()
Position2 = Field()
FounderIntro2 = Field()
Founders3 = Field()
Position3 = Field()
FounderIntro3 = Field()
Founders4 = Field()
Position4 = Field()
FounderIntro4 = Field()
Founders5 = Field()
Position5 = Field()
FounderIntro5 = Field()
| mit | Python | |
a66cfb92b119810d7220d017ea6d214d8476ca6e | Add Tester to _strategies.py | ranjinidas/Axelrod,marcharper/Axelrod,ranjinidas/Axelrod,marcharper/Axelrod | axelrod/strategies/_strategies.py | axelrod/strategies/_strategies.py | from alternator import *
from appeaser import *
from averagecopier import *
from cooperator import *
from darwin import *
from defector import *
from forgiver import *
from geller import *
from gobymajority import *
from grudger import *
from grumpy import *
from hunter import *
from inverse import *
from mathematicalconstants import *
from memoryone import *
from meta import *
from mindcontrol import *
from mindreader import *
from oncebitten import *
from punisher import *
from qlearner import *
from rand import *
from retaliate import *
from titfortat import *
basic_strategies = [
Alternator,
Cooperator,
Defector,
Random,
TitForTat,
]
ordinary_strategies = [
AlternatorHunter,
Appeaser,
AntiTitForTat,
ArrogantQLearner,
AverageCopier,
Bully,
CautiousQLearner,
CooperatorHunter,
Davis,
DefectorHunter,
FoolMeOnce,
ForgetfulFoolMeOnce,
ForgetfulGrudger,
Forgiver,
ForgivingTitForTat,
GTFT,
GoByMajority,
GoByMajority10,
GoByMajority20,
GoByMajority40,
GoByMajority5,
Feld,
Golden,
Grofman,
Grudger,
Grumpy,
HardTitForTat,
HardTitFor2Tats,
HesitantQLearner,
Inverse,
InversePunisher,
Joss,
LimitedRetaliate,
LimitedRetaliate2,
LimitedRetaliate3,
MathConstantHunter,
MetaHunter,
MetaMajority,
MetaMinority,
MetaWinner,
NiceAverageCopier,
OnceBitten,
OppositeGrudger,
Pi,
Punisher,
RandomHunter,
Retaliate,
Retaliate2,
Retaliate3,
RiskyQLearner,
Shubik,
SneakyTitForTat,
StochasticWSLS,
SuspiciousTitForTat,
Tester,
TitFor2Tats,
TrickyCooperator,
TrickyDefector,
Tullock,
TwoTitsForTat,
WinStayLoseShift,
ZDExtort2,
ZDGTFT2,
e,
]
# These are strategies that do not follow the rules of Axelrods tournament
cheating_strategies = [
Darwin,
Geller,
GellerCooperator,
GellerDefector,
MindBender,
MindController,
MindReader,
MindWarper,
ProtectedMindReader,
]
| from alternator import *
from appeaser import *
from averagecopier import *
from cooperator import *
from darwin import *
from defector import *
from forgiver import *
from geller import *
from gobymajority import *
from grudger import *
from grumpy import *
from hunter import *
from inverse import *
from mathematicalconstants import *
from memoryone import *
from meta import *
from mindcontrol import *
from mindreader import *
from oncebitten import *
from punisher import *
from qlearner import *
from rand import *
from retaliate import *
from titfortat import *
basic_strategies = [
Alternator,
Cooperator,
Defector,
Random,
TitForTat,
]
ordinary_strategies = [
AlternatorHunter,
Appeaser,
AntiTitForTat,
ArrogantQLearner,
AverageCopier,
Bully,
CautiousQLearner,
CooperatorHunter,
Davis,
DefectorHunter,
FoolMeOnce,
ForgetfulFoolMeOnce,
ForgetfulGrudger,
Forgiver,
ForgivingTitForTat,
GTFT,
GoByMajority,
GoByMajority10,
GoByMajority20,
GoByMajority40,
GoByMajority5,
Feld,
Golden,
Grofman,
Grudger,
Grumpy,
HardTitForTat,
HardTitFor2Tats,
HesitantQLearner,
Inverse,
InversePunisher,
Joss,
LimitedRetaliate,
LimitedRetaliate2,
LimitedRetaliate3,
MathConstantHunter,
MetaHunter,
MetaMajority,
MetaMinority,
MetaWinner,
NiceAverageCopier,
OnceBitten,
OppositeGrudger,
Pi,
Punisher,
RandomHunter,
Retaliate,
Retaliate2,
Retaliate3,
RiskyQLearner,
Shubik,
SneakyTitForTat,
StochasticWSLS,
SuspiciousTitForTat,
TitFor2Tats,
TrickyCooperator,
TrickyDefector,
Tullock,
TwoTitsForTat,
WinStayLoseShift,
ZDExtort2,
ZDGTFT2,
e,
]
# These are strategies that do not follow the rules of Axelrods tournament
cheating_strategies = [
Darwin,
Geller,
GellerCooperator,
GellerDefector,
MindBender,
MindController,
MindReader,
MindWarper,
ProtectedMindReader,
]
| mit | Python |
91f21f0e66be8290de94bfb23b50aa8bdeec3b18 | Add files via upload | shenlinqijing/predl,shenlinqijing/predl | classfy.py | classfy.py | #! /usr/bin/env python
#coding=utf-8
import numpy as np
import sys,os
# 设置当前的工作环境在caffe下
caffe_root = '/home/dandan/DL/caffe/'
# 我们也把caffe/python也添加到当前环境
sys.path.insert(0, caffe_root + 'python')
import caffe
os.chdir(caffe_root)#更换工作目录
# 设置网络结构
#net_file=caffe_root + 'models/bvlc_reference_caffenet/deploy.prototxt'
net_file=caffe_root + 'models/vgg/VGG_ILSVRC_16_layers_deploy.prototxt'
# 添加训练之后的参数
#caffe_model=caffe_root + 'models/bvlc_reference_caffenet/bvlc_reference_caffenet.caffemodel'
caffe_model=caffe_root + 'models/vgg/vgg_sexy_train_iter_15000.caffemodel'
# 均值文件
mean_file=caffe_root + 'python/caffe/imagenet/ilsvrc_2012_mean.npy'
# 这里对任何一个程序都是通用的,就是处理图片
# 把上面添加的两个变量都作为参数构造一个Net
net = caffe.Net(net_file,caffe_model,caffe.TEST)
# 得到data的形状,这里的图片是默认matplotlib底层加载的
transformer = caffe.io.Transformer({'data': net.blobs['data'].data.shape})
# matplotlib加载的image是像素[0-1],图片的数据格式[weight,high,channels],RGB
# caffe加载的图片需要的是[0-255]像素,数据格式[channels,weight,high],BGR,那么就需要转换
# channel 放到前面
transformer.set_transpose('data', (2,0,1))
#transformer.set_mean('data', np.load(mean_file).mean(1).mean(1))
transformer.set_mean('data', np.array([104, 117, 123]))
# 图片像素放大到[0-255]
transformer.set_raw_scale('data', 255)
# RGB-->BGR 转换
transformer.set_channel_swap('data', (2,1,0))
# 这里才是加载图片
im=caffe.io.load_image(caffe_root+'examples/images/5.jpg')
# 用上面的transformer.preprocess来处理刚刚加载图片
net.blobs['data'].data[...] = transformer.preprocess('data',im)
for layer_name, blob in net.blobs.iteritems():
print layer_name + '\t' + str(blob.data.shape)
#注意,网络开始向前传播啦
out = net.forward()
print net.blobs['prob'].data[0]
result=net.blobs['prob'].data[0].flatten()
print ("sexy:%.2f"%result[0])
print ("norm:%.2f"%result[1])
#imagenet_labels_filename = caffe_root + 'data/ilsvrc12/synset_words.txt'
#labels = np.loadtxt(imagenet_labels_filename, str, delimiter='\t')
#top_k = net.blobs['prob'].data[0].flatten().argsort()[-1:-2:-1]
#for i in np.arange(top_k.size):
# print top_k[i] , net.blobs['prob'].data[0][top_k[i]]
| mit | Python | |
3c1c434d1b88cff110f84dac99db6465c6df2519 | Add command line tool | janten/lcfam | lcfam.py | lcfam.py | #!/usr/bin/env python
import sys, warnings
from skimage import io, color, img_as_ubyte
if len(sys.argv) != 4:
print 'Usage: %s <cfam.png> <fam.png> <outfile.png>' % sys.argv[0]
sys.exit(1)
fam = io.imread(sys.argv[2])
fam_norm = fam.astype(float) / 255
cfam = io.imread(sys.argv[1])[:, :, 0:3]
cfam_lab = color.rgb2lab(cfam)
cfam_lightness = cfam_lab[:, :, 0].astype(float) / 100
lcfam_lab = cfam_lab
lcfam_lightness = fam_norm * 100
lcfam_lab[:, :, 0] = lcfam_lightness
lcfam = color.lab2rgb(lcfam_lab)
warnings.simplefilter("ignore")
io.imsave(sys.argv[3], lcfam); | mit | Python | |
77dcd404e3b5a65268dc4ff2ecdd25c27358967f | add script for automatic robot checking WIP | bit-bots/bitbots_misc,bit-bots/bitbots_misc,bit-bots/bitbots_misc | bitbots_bringup/scripts/check_robot.py | bitbots_bringup/scripts/check_robot.py | #!/usr/bin/python3
import rospy
import rosnode
import roslaunch
import rospkg
import rostopic
from bitbots_msgs.msg import FootPressure
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
left_pressure = None
right_pressure = None
def pressure_cb(msg, is_left=True):
global left_pressure
global right_pressure
if is_left:
left_pressure = msg
else:
right_pressure = msg
def is_motion_started():
node_names = rosnode.get_node_names("/")
started = True
if not "ros_control" in node_names:
print("ros control not running")
started = False
# todo rest of nodes
return
def check_pressure(msg, min, max, foot_name):
if min > msg.left_front > max:
print(bcolors.WARNING + " " + foot_name + " left_front out of limits. Min %f, Max %f, Value %f" + bcolors.ENDC,
min, max, msg.left_front)
if min > msg.left_back > max:
print(bcolors.WARNING + " " + foot_name + " left_back out of limits. Min %f, Max %f, Value %f" + bcolors.ENDC,
min, max, msg.left_front)
if min > msg.right_back > max:
print(bcolors.WARNING + " " + foot_name + " right_back out of limits. Min %f, Max %f, Value %f" + bcolors.ENDC,
min, max, msg.left_front)
if min > msg.right_front > max:
print(
bcolors.WARNING + " " + foot_name + " right_front out of limits. Min %f, Max %f, Value %f" + bcolors.ENDC,
min, max, msg.left_front)
if __name__ == '__main__':
print("### This script will check the robot hardware and motions. Please follow the instructions\n")
# start necessary software
print("First the motion software will be started. Please hold the robot and press enter.\n")
input("Press Enter to continue...")
uuid = roslaunch.rlutil.get_or_generate_uuid(None, False)
roslaunch.configure_logging(uuid)
rospack = rospkg.RosPack()
launch = roslaunch.parent.ROSLaunchParent(uuid, [rospack.get_path('rospy_tutorials') + "/launch/test_node.launch"])
launch.start()
while True:
if is_motion_started():
break
else:
print("Waiting for software to be started \n")
rospy.sleep(1)
# check publishing frequency of imu, servos, pwm, goals, pressure, robot_state
# the topics which will be checked with minimal publishing rate
topics_to_check = {"/imu_data/raw": 100, "/imu_data": 100, "/joint_states": 100, "/pwm_states": 100,
"/motor_goals": 100, "/robot_state": 100, "/foot_pressure/left": 100, "foot_pressure/right": 100}
rt = rostopic.ROSTopicHz(-1)
for topic in topics_to_check.keys():
msg_class, real_topic, _ = rostopic.get_topic_class(topic)
rospy.Subscriber(real_topic, msg_class, rt.callback_hz, callback_args=topic, tcp_nodelay=True)
print("Please wait a few seconds for topics to be evaluated\n")
rospy.sleep(5)
print("Topics have been evaluated:\n")
for topic in topics_to_check.keys():
rate = rt.get_hz(topic)
if rate < topics_to_check[topic]:
print(bcolors.WARNING + " Topic %s: %f \n" + bcolors.ENDC, topic, rate)
else:
print(" Topic %s: %f \n", topic, rate)
# check pressure values when robot in air
#todo maybe call zero service
print("\nWe will check the foot pressure sensors next\n")
input("Please hold the robot in the air so that the feet don't touch the ground and press enter.")
left_pressure_sub = rospy.Subscriber("/foot_pressure/left", FootPressure, pressure_cb, callback_args=True,
tcp_nodelay=True)
right_pressure_sub = rospy.Subscriber("/foot_pressure/right", FootPressure, pressure_cb, callback_args=False,
tcp_nodelay=True)
rospy.sleep(0.5)
while (not left_pressure) and (not right_pressure):
print("Waiting to receive pressure msgs\n")
print("Pressure messages received\n")
check_pressure(left_pressure, -1, 1, "left")
check_pressure(right_pressure, -1, 1, "right")
# check pressure values when robot in walkready
input("Please put the robot standing on the ground and press enter")
check_pressure(left_pressure, 20, 40, "left")
check_pressure(right_pressure, 20, 40, "right")
# check walk motion
# check kick motion
# check stand up front
# check stand up back
# shutdown the launch
launch.shutdown()
| mit | Python | |
0a0a9addea16d5adf4d9edb3d56e1d890b6214e5 | Add tests for new complext date time field. | nzlosh/st2,punalpatel/st2,pixelrebel/st2,dennybaa/st2,StackStorm/st2,lakshmi-kannan/st2,nzlosh/st2,jtopjian/st2,peak6/st2,pinterb/st2,Plexxi/st2,tonybaloney/st2,jtopjian/st2,grengojbo/st2,emedvedev/st2,dennybaa/st2,armab/st2,StackStorm/st2,dennybaa/st2,tonybaloney/st2,jtopjian/st2,tonybaloney/st2,armab/st2,pixelrebel/st2,lakshmi-kannan/st2,pixelrebel/st2,emedvedev/st2,Plexxi/st2,Itxaka/st2,emedvedev/st2,nzlosh/st2,StackStorm/st2,alfasin/st2,grengojbo/st2,pinterb/st2,nzlosh/st2,Plexxi/st2,peak6/st2,peak6/st2,pinterb/st2,punalpatel/st2,grengojbo/st2,StackStorm/st2,lakshmi-kannan/st2,Itxaka/st2,Itxaka/st2,alfasin/st2,alfasin/st2,armab/st2,punalpatel/st2,Plexxi/st2 | st2common/tests/unit/test_db_fields.py | st2common/tests/unit/test_db_fields.py | # Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import time
import datetime
import unittest2
from st2common.fields import ComplexDateTimeField
class ComplexDateTimeFieldTestCase(unittest2.TestCase):
def test_round_trip_conversion(self):
datetime_values = [
datetime.datetime(2015, 1, 1, 15, 0, 0).replace(microsecond=500),
datetime.datetime(2015, 1, 1, 15, 0, 0).replace(microsecond=0),
datetime.datetime(2015, 1, 1, 15, 0, 0).replace(microsecond=999999)
]
microsecond_values = []
# Calculate microsecond values
for value in datetime_values:
seconds = time.mktime(value.timetuple())
microseconds_reminder = value.time().microsecond
result = int(seconds * 1000000) + microseconds_reminder
microsecond_values.append(result)
field = ComplexDateTimeField()
# datetime to us
for index, value in enumerate(datetime_values):
actual_value = field._datetime_to_microseconds_since_epoch(value=value)
expected_value = microsecond_values[index]
expected_microseconds = value.time().microsecond
self.assertEqual(actual_value, expected_value)
self.assertTrue(str(actual_value).endswith(str(expected_microseconds)))
# us to datetime
for index, value in enumerate(microsecond_values):
actual_value = field._microseconds_since_epoch_to_datetime(data=value)
expected_value = datetime_values[index]
self.assertEqual(actual_value, expected_value)
| apache-2.0 | Python | |
1b6966cf0e90da0ac060a43349bbe4ce0f5fc365 | Create a model-based form for whitelist requests | Jonpro03/Minecrunch_Web,Jonpro03/Minecrunch_Web,Jonpro03/Minecrunch_Web | src/whitelist/whitelist_form.py | src/whitelist/whitelist_form.py | from django.forms import ModelForm
from whitelist.models import Player
class WhitelistForm(ModelForm):
""" Automatically generate a form based on the Player model
"""
class Meta:
model = Player
fields = ('ign', 'email')
| mit | Python | |
bf6ce0b61c1f66cbb88c3e5d12174242e04c9c87 | Add PROJECT_CONSTANTS configuration file | elc1798/chessley-tan,elc1798/chessley-tan,elc1798/chessley-tan | static/neural-net/PROJECT_CONSTANTS.py | static/neural-net/PROJECT_CONSTANTS.py | import os
PGN_FILE_DIRECTORY = os.path.dirname(os.path.realpath(__file__)) + "/game-files"
| mit | Python | |
adfc4d376338a185c56ee3a1932801e6a8c26917 | Add spectra making script | sbird/vw_spectra | make_spectra.py | make_spectra.py | import halospectra as hs
import randspectra as rs
import sys
snapnum=sys.argv[1]
sim=sys.argv[2]
#base="/n/hernquistfs1/mvogelsberger/projects/GFM/Production/Cosmo/Cosmo"+str(sim)+"_V6/L25n512/output/"
#savedir="/n/home11/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6_512/snapdir_"+str(snapnum).rjust(3,'0')
base="/n/hernquistfs1/mvogelsberger/projects/GFM/Production/Cosmo/Cosmo"+str(sim)+"_V6/L25n256/output/"
savedir="/n/home11/spb/scratch/Cosmo/Cosmo"+str(sim)+"_V6/snapdir_"+str(snapnum).rjust(3,'0')
halo = hs.HaloSpectra(snapnum, base,3, savefile="halo_spectra_DLA.hdf5", savedir=savedir)
#halo = rs.RandSpectra(snapnum, base,savefile=savedir+"/rand_spectra.hdf5")
halo.get_tau("Si",2,2)
halo.get_tau("H",1,1)
halo.get_col_density("Z",-1)
halo.save_file()
| mit | Python | |
5dc7b9e6d58ff0aee770cebd1c61f46827702ff9 | add setup.py | Bachmann1234/heart-rate-hud | setup.py | setup.py | from setuptools import setup, find_packages
# You need to install https://github.com/Bachmann1234/CMS50Dplus
setup(
name='heart-rate-hud',
version='1',
author='Matt Bachmann',
url='https://github.com/Bachmann1234/heart-rate-hud',
description='Tkinter window to display heartrate',
packages=find_packages()
)
| apache-2.0 | Python | |
d493f295c9af0eff76710599da6f05946ba50ed1 | Move test-only deps from REQUIRE_SETUP to REQUIRE_TEST. | frlen/simian,sillywilly42/simian,alexandregz/simian,googlearchive/simian,sillywilly42/simian,selfcommit/simian,frlen/simian,sillywilly42/simian,alexandregz/simian,frlen/simian,alexandregz/simian,selfcommit/simian,selfcommit/simian,alexandregz/simian,selfcommit/simian,googlearchive/simian,googlearchive/simian,sillywilly42/simian,googlearchive/simian,frlen/simian | setup.py | setup.py | #!/usr/bin/env python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# # Do NOT change the above sha-bang line unless if you know what you are doing.
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# #
try:
from setuptools import setup, find_packages
except ImportError:
print 'required Python setuptools is missing.'
print 'install from http://pypi.python.org/pypi/setuptools'
raise SystemExit(1)
REQUIRE_BASE = [
'setuptools>=0.6c9', # fix bugs with old version on Leopard
'pyasn1==0.1.2',
'tlslite==0.3.8',
'pyyaml>=3.10',
]
REQUIRE_SETUP = REQUIRE_BASE + [
'google_apputils>=0.2',
'python-dateutil>=1.4,<2', # because of google_apputils
]
REQUIRE_TEST = REQUIRE_SETUP + [
'django',
'icalendar==1.2',
'mox>=0.5.3',
'unittest2==0.5.1',
'webapp2',
'M2Crypto==0.21.1',
'WebOb==1.1.1',
]
REQUIRE_INSTALL = REQUIRE_BASE
SIMIAN_STUBS = [
('simianadmin', 'RunSimianAdmin'),
('simianauth', 'RunSimianAuth'),
]
SIMIAN_ENTRY_POINTS = ['%s = simian.stubs:%s' % s for s in SIMIAN_STUBS]
setup(
name = 'simian',
version = '2.2.1',
url = 'http://code.google.com/p/simian',
license = 'Apache 2.0',
description = 'An App Engine-based client & server component for Munki',
author = 'Google',
author_email = 'simian-eng@googlegroups.com',
packages = find_packages('src', exclude=['tests']),
package_dir = {'': 'src'},
package_data = {
'': ['*.zip'],
},
include_package_data = True,
entry_points = {
'console_scripts': SIMIAN_ENTRY_POINTS,
},
setup_requires = REQUIRE_SETUP,
install_requires = REQUIRE_INSTALL,
tests_require = REQUIRE_TEST,
google_test_dir = 'src/tests',
)
| #!/usr/bin/env python
#
# Copyright 2011 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# # Do NOT change the above sha-bang line unless if you know what you are doing.
#
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# #
try:
from setuptools import setup, find_packages
except ImportError:
print 'required Python setuptools is missing.'
print 'install from http://pypi.python.org/pypi/setuptools'
raise SystemExit(1)
REQUIRE_BASE = [
'setuptools>=0.6c9', # fix bugs with old version on Leopard
'pyasn1==0.1.2',
'tlslite==0.3.8',
'pyyaml>=3.10',
]
REQUIRE_SETUP = REQUIRE_BASE + [
'google_apputils>=0.2',
'icalendar==1.2',
'python-dateutil>=1.4,<2', # because of google_apputils
'unittest2==0.5.1',
'M2Crypto==0.21.1',
'WebOb==1.1.1',
]
REQUIRE_TEST = REQUIRE_BASE + REQUIRE_SETUP + [
'mox>=0.5.3',
'webapp2',
'django',
]
REQUIRE_INSTALL = REQUIRE_BASE
SIMIAN_STUBS = [
('simianadmin', 'RunSimianAdmin'),
('simianauth', 'RunSimianAuth'),
]
SIMIAN_ENTRY_POINTS = ['%s = simian.stubs:%s' % s for s in SIMIAN_STUBS]
setup(
name = 'simian',
version = '2.2.1',
url = 'http://code.google.com/p/simian',
license = 'Apache 2.0',
description = 'An App Engine-based client & server component for Munki',
author = 'Google',
author_email = 'simian-eng@googlegroups.com',
packages = find_packages('src', exclude=['tests']),
package_dir = {'': 'src'},
package_data = {
'': ['*.zip'],
},
include_package_data = True,
entry_points = {
'console_scripts': SIMIAN_ENTRY_POINTS,
},
setup_requires = REQUIRE_SETUP,
install_requires = REQUIRE_INSTALL,
tests_require = REQUIRE_TEST,
google_test_dir = 'src/tests',
) | apache-2.0 | Python |
5457fa3c39d5ebe016c9f171878aaf1580ee4730 | add setup | TRI-AMDD/piro,TRI-AMDD/piro,TRI-AMDD/piro,TRI-AMDD/piro,TRI-AMDD/piro | setup.py | setup.py | from setuptools import setup, find_packages
import warnings
DESCRIPTION = "rxn is software designed to assist in prediction of synthesis pathway"
LONG_DESCRIPTION = """
The rxn software package enables prediction of synthesis pathways
and determination of pareto-optimal frontiers for synthesis of
specific materials
"""
setup(
name="rxn",
version="2020.12.2",
packages=find_packages(),
description=DESCRIPTION,
long_description=LONG_DESCRIPTION,
long_description_content_type='text/markdown',
install_requires=["matminer==0.6.3",
"scikit-learn==0.23.1",
"plotly==4.8.2"
],
classifiers=[
"Programming Language :: Python :: 3",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
],
include_package_data=True,
author="AMDD - Toyota Research Institute",
author_email="murat.aykol@tri.global",
maintainer="Murat Aykol",
maintainer_email="murat.aykol@tri.global",
# license="Apache",
keywords=[
"materials", "battery", "chemistry", "science",
"density functional theory", "energy", "AI", "artificial intelligence",
"sequential learning", "active learning"
],
)
| apache-2.0 | Python | |
f52cba89474bf7ef4045a8dd12eef228b60a1555 | Make it installable | abakar/django-whatever,abakar/django-whatever,kmmbvnr/django-any | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='django-fsm',
version='0.0.1',
description='Unobtrusive test models creation for django.',
author='Mikhail Podgurskiy',
author_email='kmmbvnr@gmail.com',
url='http://github.com/kmmbvnr/django-any',
keywords = "django",
packages=['django_any', 'django_any.contrib', 'django_any.test'],
include_package_data=True,
zip_safe=False,
license='MIT License',
platforms = ['any'],
classifiers=[
'Development Status :: 2 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
]
)
| mit | Python | |
a64f29d7c492a772474ff1c5a4855a368ed10d2d | Create setup.py file. | Artanis/pygcui,Artanis/pygcui | setup.py | setup.py | try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name="pygcui", version="0.1-dev",
author="Erik Youngren", author_email="artanis.00@gmail.com",
url="https://github.com/Artanis/pygcui",
license="Simplified BSD License",
keywords=" pygame pygcurse widget user interface curses text",
description="A user interface library for pygcurse.",
packages=['pygcui'],
) | bsd-2-clause | Python | |
cf68f6488f7f1afff4f7e6532ecc4a7f89186688 | Add setup.py | lmcinnes/hypergraph | setup.py | setup.py | from setuptools import setup
def readme():
with open('README.rst') as readme_file:
return readme_file.read()
configuration = {
'name' : 'hypergraph',
'version' : '0.1',
'description' : 'Hypergraph tools and algorithms',
'long_description' : readme(),
'classifiers' : [
'Development Status :: 3 - Alpha',
'Intended Audience :: Science/Research',
'Intended Audience :: Developers',
'License :: OSI Approved',
'Programming Language :: Python',
'Topic :: Software Development',
'Topic :: Scientific/Engineering',
'Operating System :: Microsoft :: Windows',
'Operating System :: POSIX',
'Operating System :: Unix',
'Operating System :: MacOS',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.4',
],
'keywords' : 'hypergraph graph network community pomset',
'url' : 'http://github.com/lmcinnes/hdbscan',
'maintainer' : 'Leland McInnes',
'maintainer_email' : 'leland.mcinnes@gmail.com',
'license' : 'BSD',
'packages' : ['hdbscan'],
'install_requires' : ['numpy>=1.5],
'ext_modules' : [],
'cmdclass' : {'build_ext' : build_ext},
'test_suite' : 'nose.collector',
'tests_require' : ['nose'],
}
setup(**configuration)
| lgpl-2.1 | Python | |
48c5f707640fe0e216f1a454d6c52265d02de1e7 | Add setup.py script. | kxepal/python-couchdb-auditor | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2011 Alexander Shorin
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(
name = 'couchdb-auditor',
version = '0.1',
description = \
'Audit configuration and security issues for an Apache CouchDB server.',
long_description = \
'Python port of Jason Smith https://github.com/iriscouch/audit_couchdb tool.',
author = 'Alexander Shorin',
author_email = 'kxepal@gmail.com',
license = 'BSD',
url = 'http://code.google.com/p/couchdb-auditor/',
install_requires = ['couchdb'],
entry_points = {
'console_scripts': [
'couchdb-auditor = couchdb_auditor:main',
],
},
packages = ['couchdb_auditor'],
)
| bsd-3-clause | Python | |
0a301924b9050580979f65af96e9b91a7ae2f746 | Add setup.py so it is possible to pip install it from github | dangra/txtulip | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='txtulip',
version='0.0.1',
license='MIT',
description='Run Twisted on the Tulip/asyncio event loop',
url='https://github.com/itamarst/txtulip',
packages=find_packages(),
include_package_data=True,
zip_zafe=False,
platforms=['Any'],
)
| mit | Python | |
ed55dbe5a3967d8a73bbb76f19df470b1ab90b2a | Create SpecialArray.py | JLJTECH/TutorialTesting | Edabit/SpecialArray.py | Edabit/SpecialArray.py | #!/usr/bin/env python3
'''
Return True if every even index contains an even number and every odd index contains an odd number. Else return False
'''
def is_special_array(lst):
a = [i for i in lst[::2] if i % 2 == 1]
b = [i for i in lst[1::2] if i % 2 == 0]
return len(a) == len(b)
#Alternative Solutions
def is_special_array(lst):
return all(lst[i]%2==i%2 for i in range(len(lst)))
| mit | Python | |
d38a838f58f17e514a554e4533313bf3f1f80178 | Add factorial example | waltermoreira/tartpy | factorial.py | factorial.py | import rt
class Factorial(rt.Actor):
def __init__(self):
super().__init__()
self.behavior = self.factorial_beh
def factorial_beh(self, message):
customer, n = message
if n == 0:
customer(1)
else:
multiply_by_n = Multiplier.create(customer, n)
self((multiply_by_n, n-1))
class Multiplier(rt.Actor):
def __init__(self, customer, n):
super().__init__()
self.customer = customer
self.n = n
self.behavior = self.multiplier_beh
def multiplier_beh(self, m):
self.customer(m * self.n)
| mit | Python | |
656dc608bea00c9cdaaef9354f8ddac956b2afc9 | add setup.py | mozilla/agithub,jpaugh/agithub | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='agithub',
version='1.3',
author='Jonathan Paugh',
py_modules=['agithub'])
| mit | Python | |
791cbbe340c2777310fad55889ab991086d9f31d | support py2.7.5 | simon-weber/gmusicapi,peetahzee/Unofficial-Google-Music-API,nvbn/Unofficial-Google-Music-API,dvirtz/gmusicapi,simon-weber/Unofficial-Google-Music-API,dvirtz/gmusicapi,TheOpenDevProject/gmusicapi,thebigmunch/gmusicapi,tanhaiwang/gmusicapi | setup.py | setup.py | #!/usr/bin/env python
import re
from setuptools import setup, find_packages
import sys
#Only 2.6-2.7 are supported.
if not ((2, 6, 0) <= sys.version_info[:3] <= (2, 7, 5)):
sys.stderr.write('gmusicapi does not officially support this Python version.\n')
#try to continue anyway
dynamic_requires = []
if sys.version_info[:2] == (2, 6):
dynamic_requires += ['unittest2 == 0.5.1', 'simplejson == 3.0.7']
#This hack is from http://stackoverflow.com/a/7071358/1231454;
# the version is kept in a seperate file and gets parsed - this
# way, setup.py doesn't have to import the package.
VERSIONFILE = 'gmusicapi/_version.py'
version_line = open(VERSIONFILE).read()
version_re = r"^__version__ = ['\"]([^'\"]*)['\"]"
match = re.search(version_re, version_line, re.M)
if match:
version = match.group(1)
else:
raise RuntimeError("Could not find version in '%s'" % VERSIONFILE)
setup(
name='gmusicapi',
version=version,
author='Simon Weber',
author_email='simon@simonmweber.com',
url='http://pypi.python.org/pypi/gmusicapi/',
packages=find_packages(),
scripts=[],
license=open('LICENSE').read(),
description='An unofficial api for Google Play Music.',
long_description=(open('README.rst').read() + '\n\n' +
open('HISTORY.rst').read()),
install_requires=[
'validictory == 0.9.0', # validation
'decorator == 3.3.2', # keep
'mutagen == 1.21', # MM
'protobuf == 2.4.1', # MM
'requests == 1.2.0', # keep
'python-dateutil == 2.1', # MM
'proboscis==1.2.5.3', # testing
'oauth2client==1.1', # MM
'mock==1.0.1', # testing
'appdirs==1.2.0', # keep
] + dynamic_requires,
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Topic :: Multimedia :: Sound/Audio',
'Topic :: Software Development :: Libraries :: Python Modules'
],
include_package_data=True,
zip_safe=False,
)
| #!/usr/bin/env python
import re
from setuptools import setup, find_packages
import sys
#Only 2.6-2.7 are supported.
if not ((2, 6, 0) <= sys.version_info[:3] <= (2, 7, 4)):
sys.stderr.write('gmusicapi does not officially support this Python version.\n')
#try to continue anyway
dynamic_requires = []
if sys.version_info[:2] == (2, 6):
dynamic_requires += ['unittest2 == 0.5.1', 'simplejson == 3.0.7']
#This hack is from http://stackoverflow.com/a/7071358/1231454;
# the version is kept in a seperate file and gets parsed - this
# way, setup.py doesn't have to import the package.
VERSIONFILE = 'gmusicapi/_version.py'
version_line = open(VERSIONFILE).read()
version_re = r"^__version__ = ['\"]([^'\"]*)['\"]"
match = re.search(version_re, version_line, re.M)
if match:
version = match.group(1)
else:
raise RuntimeError("Could not find version in '%s'" % VERSIONFILE)
setup(
name='gmusicapi',
version=version,
author='Simon Weber',
author_email='simon@simonmweber.com',
url='http://pypi.python.org/pypi/gmusicapi/',
packages=find_packages(),
scripts=[],
license=open('LICENSE').read(),
description='An unofficial api for Google Play Music.',
long_description=(open('README.rst').read() + '\n\n' +
open('HISTORY.rst').read()),
install_requires=[
'validictory == 0.9.0',
'decorator == 3.3.2',
'mutagen == 1.21',
'protobuf == 2.4.1',
'requests == 1.2.0',
'python-dateutil == 2.1',
'proboscis==1.2.5.3',
'oauth2client==1.1',
'mock==1.0.1',
'appdirs==1.2.0',
] + dynamic_requires,
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Topic :: Multimedia :: Sound/Audio',
'Topic :: Software Development :: Libraries :: Python Modules'
],
include_package_data=True,
zip_safe=False,
)
| bsd-3-clause | Python |
4d3ad6b218726ec4a881a2a41740b44f1292ecfd | Add basic setup.py | worldcomputerxchange/inventory-control,codeforsanjose/inventory-control | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name = "WCX Inventory Control",
version = "0.0.1",
packages = find_packages(),
) | mit | Python | |
5a3b4773b0e416101716443a9526b47cd47e21a7 | Update version. v2.0.1 | appliedx/python-saml,appliedx/python-saml,tachang/python-saml,mobify/python-saml,ninadpdr/python-saml,onelogin/python3-saml,vivekgarhewal/med,pitbulk/python3-saml,ninadpdr/python-saml,onelogin/python-saml,mpaulweeks/python-saml,tachang/python-saml,pitbulk/python3-saml,mpaulweeks/python-saml,novafloss/python-saml,jkgneu12/python3-saml,mobify/python-saml,sandeep048/python-saml,onelogin/python-saml,elbaschid/python-saml,jkgneu12/python3-saml,onelogin/python3-saml,novafloss/python-saml,elbaschid/python-saml,vivekgarhewal/med,sandeep048/python-saml | setup.py | setup.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014, OneLogin, Inc.
# All rights reserved.
from setuptools import setup
setup(
name='python-saml',
version='2.0.1',
description='Onelogin Python Toolkit. Add SAML support to your Python software using this library',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
],
author='OneLogin',
author_email='support@onelogin.com',
license='MIT',
url='https://github.com/onelogin/python-saml',
packages=['onelogin','onelogin/saml2'],
include_package_data=True,
package_data = {
'onelogin/saml2/schemas': ['*.xsd'],
},
package_dir={
'': 'src',
},
test_suite='tests',
install_requires=[
'M2Crypto==0.22.3',
'dm.xmlsec.binding==1.3.1',
'isodate==0.5.0',
'defusedxml==0.4.1',
],
extras_require={
'test': (
'coverage==3.7.1',
'pylint==1.3.1',
'pep8==1.5.7',
'pyflakes==0.8.1',
'coveralls==0.4.4',
),
},
keywords='saml saml2 xmlsec django flask',
)
| #! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2014, OneLogin, Inc.
# All rights reserved.
from setuptools import setup
setup(
name='python-saml',
version='2.0.0',
description='Onelogin Python Toolkit. Add SAML support to your Python software using this library',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.7',
],
author='OneLogin',
author_email='support@onelogin.com',
license='MIT',
url='https://github.com/onelogin/python-saml',
packages=['onelogin','onelogin/saml2'],
include_package_data=True,
package_data = {
'onelogin/saml2/schemas': ['*.xsd'],
},
package_dir={
'': 'src',
},
test_suite='tests',
install_requires=[
'M2Crypto==0.22.3',
'dm.xmlsec.binding==1.3.1',
'isodate==0.5.0',
'defusedxml==0.4.1',
],
extras_require={
'test': (
'coverage==3.7.1',
'pylint==1.3.1',
'pep8==1.5.7',
'pyflakes==0.8.1',
'coveralls==0.4.4',
),
},
keywords='saml saml2 xmlsec django flask',
)
| bsd-3-clause | Python |
bcc2e85be21321e4f27ccc673513ce90e20ab1b3 | Fix setup.py | giumas/python-acoustics,felipeacsi/python-acoustics,antiface/python-acoustics,python-acoustics/python-acoustics,FRidh/python-acoustics | setup.py | setup.py | import os
from setuptools import setup, find_packages
from Cython.Build import cythonize
import numpy as np
if os.path.exists('README.md'):
long_description = open('README.md').read()
else:
long_description = "A Python library aimed at acousticians."
setup(
name='acoustics',
version='0.0',
description="Acoustics module for Python.",
long_description=long_description,
author='Python Acoustics',
author_email='fridh@fridh.nl',
license='LICENSE',
packages=find_packages(exclude=["tests"]),
#py_modules=['turbulence'],
scripts=[],
zip_safe=False,
install_requires=[
'numpy >=1.8',
'scipy >= 0.14',
'matplotlib',
'six >= 1.4.1',
'cython',
'numexpr',
'setuptools',
],
extras_require={
'jit': 'numba',
'fast_fft': 'pyFFTW',
'io': 'pandas',
},
ext_modules = cythonize('acoustics/*.pyx'),
include_dirs=[np.get_include()]
)
| import os
from setuptools import setup, find_packages
from Cython.Build import cythonize
import numpy as np
if os.path.exists('README.md'):
long_description = open('README.md').read()
else:
long_description = "A Python library aimed at acousticians."
setup(
name='acoustics',
version='0.0',
description="Acoustics module for Python.",
long_description=long_description,
author='Python Acoustics',
author_email='fridh@fridh.nl',
license='LICENSE',
#packages=find_packages(exclude=["tests"]),
py_modules=['turbulence'],
scripts=[],
zip_safe=False,
install_requires=[
'numpy >=1.8',
'scipy >= 0.13',
'matplotlib',
'six >= 1.4.1',
'cython',
'numexpr',
],
extras_require={
'jit': 'numba',
'fast_fft': 'pyFFTW',
'io': 'pandas',
},
ext_modules = cythonize('acoustics/*.pyx'),
include_dirs=[np.get_include()]
)
| bsd-3-clause | Python |
0c0ca6d4473669842a1caba9e3ec450e7969eebc | add setup.py | swstack/simpcli,swstack/simpcli | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name="simpcli",
description="Simple command line interfaces",
url="https://github.com/swstack/simpcli",
author="Stack, Stephen",
author_email="ss@stephenstack.com",
packages=find_packages(),
version='dev'
)
| mit | Python | |
c6c2f49014e650a07d450d9b5dd2b532f38ac5a4 | Create setup.py | Embed-Engineering/python-github-backup,josegonzalez/python-github-backup,josegonzalez/python-github-backup | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from github_backup import __version__
try:
from setuptools import setup
setup # workaround for pyflakes issue #13
except ImportError:
from distutils.core import setup
# Hack to prevent stupid TypeError: 'NoneType' object is not callable error on
# exit of python setup.py test # in multiprocessing/util.py _exit_function when
# running python setup.py test (see
# http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html)
try:
import multiprocessing
multiprocessing
except ImportError:
pass
def open_file(fname):
return open(os.path.join(os.path.dirname(__file__), fname))
setup(
name='github-backup',
version=__version__,
author='Jose Diaz-Gonzalez',
author_email='github-backup@josediazgonzalez.com',
packages=['github_backup'],
scripts=['bin/github-backup'],
url='http://github.com/josegonzalez/python-github-backup',
license=open('LICENSE.txt').read(),
classifiers=[
'Development Status :: 5 - Production/Stable',
'Topic :: System :: Archiving :: Backup',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
description='backup a github user or organization',
long_description=open_file('README.rst').read(),
install_requires=open_file('requirements.txt').readlines(),
zip_safe=True,
)
| mit | Python | |
64192b2d13d2503b144f02d8fbc9bfdf02aca1d5 | Create setup.py | ggreco77/GWsky | setup.py | setup.py | #!/usr/bin/env python
from distutils.core import setup
setup(name='GWsky' )
| bsd-2-clause | Python | |
f09817a210d1f621c8ac714233bccbf14786c551 | Add preprocessor | kiyomaro927/stdbt | source/utils/preprocessor.py | source/utils/preprocessor.py | # -*- coding: utf-8 -*-
import re
class Preprocessor:
def __init__(self):
pass
def __call__(self, string):
# add space
string += ' '
# eliminate '@' pattern
at_pattern = re.compile(u'@.*?\s|@.*?(?m)', re.S)
string = at_pattern.sub('', string)
# eliminate '#' pattern
tag_pattern = re.compile(u'\#.*?\s|\#.*?(?m)', re.S)
string = tag_pattern.sub('', string)
# eliminate 'http' pattern
string = re.sub(r'https?://[\w/:%#\$&\?\(\)~\.=\+\-…]+', '', string)
# eliminate 'RT' pattern
string = re.sub('RT', '', string)
# eliminate symbol pattern
symbol_pattern = re.compile(u'(?:\!|\?|\"|\'|\#|\$|\%|\&|\*|\(|\)|\`|\{|\}|\[|\]|\:|\;|\+|\/|\-|\=|\^|\~|\_|\\|\_|\>|\<|\,|\.|\|)')
string = symbol_pattern.sub('', string)
# eliminate \n \r
string = re.sub(r'\n', '', string)
string = re.sub(r'\r', '', string)
alphabet_pattern = re.compile(u'[^a-zA-Z_\'\s]', re.I)
string = alphabet_pattern.sub('', string)
return string.lower()
if __name__ == "__main__":
preprocessor = Preprocessor()
string = "@xxx hi! I'm Hirokazu Kiyomaru! http://example.com #example1 #example2 #example3"
print 'original:', string
string = preprocessor(string)
print 'output :', string
| mit | Python | |
267e539e927d97db0cfb22805569effdea964e37 | Add setup.py | 9seconds/pep3134 | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
from setuptools.command.test import test
REQUIREMENTS = []
# with open("README.rst", "r") as resource:
# LONG_DESCRIPTION = resource.read()
# copypasted from http://pytest.org/latest/goodpractises.html
class PyTest(test):
user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
def initialize_options(self):
test.initialize_options(self)
self.pytest_args = None # pylint: disable=W0201
def finalize_options(self):
test.finalize_options(self)
self.test_args = [] # pylint: disable=W0201
self.test_suite = True # pylint: disable=W0201
def run_tests(self):
# import here, cause outside the eggs aren't loaded
import pytest
import sys
errno = pytest.main(self.pytest_args)
sys.exit(errno)
setup(
name="pep3134",
description="Backport of PEP 3134 (with PEP 415 and PEP 409) "
"to Python 2 as close as possible",
long_description="",
version="0.1.0",
author="Sergey Arkhipov",
license="MIT",
author_email="serge@aerialsounds.org",
maintainer="Sergey Arkhipov",
maintainer_email="serge@aerialsounds.org",
url="https://github.com/9seconds/pep3134/",
install_requires=REQUIREMENTS,
tests_require=["pytest==2.6.1"],
packages=find_packages(),
cmdclass={'test': PyTest},
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 2.6",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.3",
"Programming Language :: Python :: 3.4",
"Topic :: Software Development :: Libraries",
"Topic :: Software Development :: Libraries :: Python Modules"
],
zip_safe=True
)
| mit | Python | |
e78e93d5f2a3c35e92b03ba85f0cdad9a5f893d2 | Add script for uploading bdists | bmorris3/conda-builder-affiliated,Cadair/conda-builder-affiliated,astropy/conda-build-tools,astropy/conda-builder-affiliated,cdeil/conda-builder-affiliated,astropy/conda-build-tools,cdeil/conda-builder-affiliated,kbarbary/conda-builder-affiliated,mwcraig/conda-builder-affiliated,astropy/conda-builder-affiliated,kbarbary/conda-builder-affiliated,zblz/conda-builder-affiliated,Cadair/conda-builder-affiliated,bmorris3/conda-builder-affiliated,zblz/conda-builder-affiliated,mwcraig/conda-builder-affiliated | affiliate-builder/upload_bdists.py | affiliate-builder/upload_bdists.py | from __future__ import (division, print_function, absolute_import,
unicode_literals)
import os
import glob
from conda import config
#from conda_build.metadata import MetaData
from binstar_client.inspect_package.conda import inspect_conda_package
from obvci.conda_tools.build import upload
from obvci.conda_tools.build_directory import Builder
from prepare_packages import RECIPE_FOLDER, BINSTAR_CHANNEL, BDIST_CONDA_FOLDER
def main():
# Get our binstar client from the Builder to get BINSTAR_TOKEN obfuscation
# in windows builds.
builder = Builder(RECIPE_FOLDER, BINSTAR_CHANNEL, 'main')
bdists = os.listdir(BDIST_CONDA_FOLDER)
conda_builds_dir = os.path.join(config.default_prefix,
'conda-bld', config.subdir)
built_packages = glob.glob(os.path.join(conda_builds_dir, '*.tar.bz2'))
for package in built_packages:
_, package_file = os.path.split(package)
name = package_file.split('-')[0]
if name in bdists:
# Need to upload this one...
# First grab the metadata from the package, which requires
# opening the file.
# SKIP THIS VESTIGAL CRAP
# with open(package) as f:
# package_data, release, file_data = inspect_conda_package(package, f)
# print(package_data, release, file_data)
# #package_data.update({'version': release['version']})
# package_data.update(release)
# package_data.update({'build': {'string': file_data['attrs']['build']}})
# package_data.update(file_data)
# meta = MetaData.fromdict({'package': package_data})
# meta.check_fields()
# print(meta)
# print('DIST:', meta.dist())
# RESUME READING HERE
# Not going to lie: after fighting with conda for 90 minutes to
# construct a proper MetaData object from a built package, I give
# up.
# Instead, create an object with one method, dist, which returns
# the build string and be done with it.
class MetaData(object):
def __init__(self, dist_info):
self._dist_info = dist_info
def dist(self):
return self._dist_info
meta = MetaData(package_file.split('.tar.bz2')[0])
# Upload it
upload(builder.binstar_cli, meta, BINSTAR_CHANNEL)
if __name__ == '__main__':
main()
| bsd-3-clause | Python | |
cedc0ccda68b3b1bc84b2c19cb7dc010b16da5f6 | Add setup.py | jbowes/markymark | setup.py | setup.py | #!/usr/bin/python
#
# Copyright (c) 2009 James Bowes <jbowes@dangerouslyinc.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
from distutils.core import setup
setup(name="markymark",
version="0.1",
description="Make your console text funky!",
author="James Bowes",
author_email="jbowes@dangerouslyinc.com",
url="http://github.com/jbowes/markymark",
py_modules=["markymark"],
)
| mit | Python | |
8171812c67d9189779aa39ba718f1d7cd8e7a045 | Add a setup.py file for scattering. | dopplershift/Scattering | setup.py | setup.py | from numpy.distutils.core import setup
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info
from os.path import join
flags = ['-W', '-Wall', '-march=opteron', '-O3']
def configuration(parent_package='', top_path=None):
config = Configuration('scattering', parent_package, top_path,
author = 'Ryan May',
author_email = 'rmay31@gmail.com',
platforms = ['Linux'],
description = 'Software for simulating weather radar data.',
url = 'http://weather.ou.edu/~rmay/research.html')
lapack = get_info('lapack_opt')
sources = ['ampld.lp.pyf', 'ampld.lp.f', 'modified_double_precision_drop.f']
config.add_extension('_tmatrix', [join('src', f) for f in sources],
extra_compile_args=flags, **lapack)
return config
setup(**configuration(top_path='').todict())
| bsd-2-clause | Python | |
952476575244cea3d0a4f8da4066b455a6b0ee4b | Add simple setup.py script | moble/h5py_cache,moble/h5py_cache | setup.py | setup.py | #!/usr/bin/env python
# Copyright (c) 2016, Michael Boyle
# See LICENSE file for details: <https://github.com/moble/h5py_cache/blob/master/LICENSE>
from distutils.core import setup
setup(name='h5py_cache',
description='Create h5py File object with specified cache',
author='Michael Boyle',
# author_email='',
url='https://github.com/moble/h5py_cache',
packages=['h5py_cache', ],
package_dir={'h5py_cache': '.'},
)
| mit | Python | |
7e3ad724cf2390e1cf7a7031834c880eaf6aecef | Add basic setup.py | mitchgu/TAMProxy-pyHost | setup.py | setup.py | from setuptools import setup
setup(
name='tamproxy',
version='0.0.1',
description='TAMProxy Python Host',
url='https://github.com/mitchgu/TAMProxy-pyHost',
classifiers=[
'Development Status :: 3 - Alpha',
'Programming Language :: Python :: 2.7',
],
keywords='maslab tamproxy',
packages=['tamproxy'],
install_requires=['numpy', 'pyserial>=3.0', 'PyYAML'],
)
| mit | Python | |
bdb46f1e4181648202f37670e630b6584a760996 | Create lists.py | davidone/misc,davidone/misc | lists.py | lists.py | #!/usr/bin/env python2
'''
Generates automatically two arrays, a and b.
Return an arrays containing common elements in arrays
a and b.
'''
import random
SIZE_LIST_A = 10
SIZE_LIST_B = 20
a = []
b = []
def populate_arrays():
for i in range(0, SIZE_LIST_A):
a.append(random.randint(1, 100))
for i in range(0, SIZE_LIST_B):
b.append(random.randint(1, 100))
def return_list(a, b):
c = []
for i in a:
if i in b and i not in c:
c.append(i)
return c
if __name__ == "__main__":
populate_arrays()
print "a: {:s}".format(str(a))
print "b: {:s}".format(str(b))
c = return_list(a, b)
if len(c) > 0:
print "c: {:s}".format(str(c))
else:
print "nothing in comon"
exit(0)
| mit | Python | |
73bbce4a13f2dae5d0a3c59ff2369e7140b59a79 | fix #1, add setup.py | relekang/rob | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name="rob",
version='0.1.0',
description='Make python objects persistent with Redis.',
url='http://github.com/relekang/rob',
author='Rolf Erik Lekang',
packages=find_packages(),
install_requires=[
'redis',
]
)
| mit | Python | |
d2fd48e19316ecce3f529155a5d07160ba1318e5 | add setup.py | Islast/BrainNetworksInPython,Islast/BrainNetworksInPython | setup.py | setup.py | from distutils.core import setup
if __name__ == '__main__':
setup(
name='BrainNetworksInPython',
version='0.1dev',
packages=['SCRIPTS','WRAPPERS'],
license='MIT license',
)
| mit | Python | |
1fd28ba1488e8f7c49f20f7846f6e1b3bf1baaf3 | add FocusPyJS.py | jaredly/pyjamas,jaredly/pyjamas,jaredly/pyjamas,jaredly/pyjamas | library/pyjamas/ui/platform/FocusPyJS.py | library/pyjamas/ui/platform/FocusPyJS.py |
def blur(elem):
JS("""
elem.blur();
""")
def createFocusable():
JS("""
var e = $doc.createElement("DIV");
e.tabIndex = 0;
return e;
""")
def focus(elem):
JS("""
elem.focus();
""")
def getTabIndex(elem):
JS("""
return elem.tabIndex;
""")
def setAccessKey(elem, key):
JS("""
elem.accessKey = key;
""")
def setTabIndex(elem, index):
JS("""
elem.tabIndex = index;
""")
| apache-2.0 | Python | |
504e2321a001144d5466cb492c77f01e045c89d5 | Add "dbm" to "python-imports" test | emilevauge/official-images,chorrell/official-images,docker-solr/official-images,davidl-zend/official-images,jperrin/official-images,docker-solr/official-images,davidl-zend/official-images,31z4/official-images,nodejs-docker-bot/official-images,emilevauge/official-images,davidl-zend/official-images,chorrell/official-images,thresheek/official-images,robfrank/official-images,thresheek/official-images,dinogun/official-images,pesho/docker-official-images,infosiftr/stackbrew,nodejs-docker-bot/official-images,infosiftr/stackbrew,docker-solr/official-images,neo-technology/docker-official-images,robfrank/official-images,emilevauge/official-images,dinogun/official-images,infosiftr/stackbrew,docker-solr/official-images,mattrobenolt/official-images,docker-solr/official-images,emilevauge/official-images,docker-flink/official-images,docker-solr/official-images,nodejs-docker-bot/official-images,infosiftr/stackbrew,infosiftr/stackbrew,nodejs-docker-bot/official-images,31z4/official-images,neo-technology/docker-official-images,mattrobenolt/official-images,docker-flink/official-images,docker-solr/official-images,docker-library/official-images,chorrell/official-images,dinogun/official-images,nodejs-docker-bot/official-images,robfrank/official-images,davidl-zend/official-images,31z4/official-images,31z4/official-images,jperrin/official-images,chorrell/official-images,docker-library/official-images,jperrin/official-images,jperrin/official-images,mattrobenolt/official-images,davidl-zend/official-images,neo-technology/docker-official-images,docker-flink/official-images,pesho/docker-official-images,emilevauge/official-images,31z4/official-images,pesho/docker-official-images,neo-technology/docker-official-images,thresheek/official-images,docker-library/official-images,docker-solr/official-images,docker-solr/official-images,31z4/official-images,mattrobenolt/official-images,jperrin/official-images,thresheek/official-images,docker-library/official-images,davidl-zend/official-images,docker-solr/official-images,emilevauge/official-images,nodejs-docker-bot/official-images,mattrobenolt/official-images,infosiftr/stackbrew,dinogun/official-images,jperrin/official-images,docker-flink/official-images,mattrobenolt/official-images,dinogun/official-images,emilevauge/official-images,docker-flink/official-images,davidl-zend/official-images,robfrank/official-images,chorrell/official-images,robfrank/official-images,robfrank/official-images,chorrell/official-images,thresheek/official-images,davidl-zend/official-images,neo-technology/docker-official-images,jperrin/official-images,infosiftr/stackbrew,docker-library/official-images,dinogun/official-images,dinogun/official-images,dinogun/official-images,docker-solr/official-images,emilevauge/official-images,pesho/docker-official-images,robfrank/official-images,docker-library/official-images,nodejs-docker-bot/official-images,neo-technology/docker-official-images,jperrin/official-images,thresheek/official-images,docker-flink/official-images,neo-technology/docker-official-images,mattrobenolt/official-images,31z4/official-images,31z4/official-images,davidl-zend/official-images,docker-library/official-images,davidl-zend/official-images,docker-flink/official-images,docker-flink/official-images,mattrobenolt/official-images,thresheek/official-images,pesho/docker-official-images,pesho/docker-official-images,jperrin/official-images,pesho/docker-official-images,docker-library/official-images,docker-flink/official-images,robfrank/official-images,robfrank/official-images,davidl-zend/official-images,docker-flink/official-images,thresheek/official-images,infosiftr/stackbrew,docker-solr/official-images,infosiftr/stackbrew,pesho/docker-official-images,nodejs-docker-bot/official-images,robfrank/official-images,docker-flink/official-images,pesho/docker-official-images,neo-technology/docker-official-images,davidl-zend/official-images,31z4/official-images,nodejs-docker-bot/official-images,chorrell/official-images,infosiftr/stackbrew,neo-technology/docker-official-images,nodejs-docker-bot/official-images,dinogun/official-images,mattrobenolt/official-images,jperrin/official-images,docker-solr/official-images,dinogun/official-images,docker-library/official-images,robfrank/official-images,pesho/docker-official-images,mattrobenolt/official-images,mattrobenolt/official-images,thresheek/official-images,docker-library/official-images,thresheek/official-images,thresheek/official-images,dinogun/official-images,dinogun/official-images,31z4/official-images,thresheek/official-images,docker-library/official-images,docker-library/official-images,neo-technology/docker-official-images,neo-technology/docker-official-images,docker-library/official-images,infosiftr/stackbrew,docker-flink/official-images,robfrank/official-images,31z4/official-images,davidl-zend/official-images,neo-technology/docker-official-images,docker-library/official-images,chorrell/official-images,infosiftr/stackbrew,jperrin/official-images,chorrell/official-images,chorrell/official-images,docker-solr/official-images,emilevauge/official-images,dinogun/official-images,chorrell/official-images,mattrobenolt/official-images,31z4/official-images,jperrin/official-images,robfrank/official-images,nodejs-docker-bot/official-images,nodejs-docker-bot/official-images,thresheek/official-images,neo-technology/docker-official-images,pesho/docker-official-images,infosiftr/stackbrew,emilevauge/official-images,emilevauge/official-images,thresheek/official-images,31z4/official-images,neo-technology/docker-official-images,pesho/docker-official-images,mattrobenolt/official-images,chorrell/official-images,emilevauge/official-images,chorrell/official-images,31z4/official-images,docker-flink/official-images,jperrin/official-images,infosiftr/stackbrew | test/tests/python-imports/container.py | test/tests/python-imports/container.py | import curses
import dbm
import readline
import bz2
assert(bz2.decompress(bz2.compress(b'IT WORKS IT WORKS IT WORKS')) == b'IT WORKS IT WORKS IT WORKS')
import platform
if platform.python_implementation() != 'PyPy' and platform.python_version_tuple()[0] != '2':
# PyPy and Python 2 don't support lzma
import lzma
assert(lzma.decompress(lzma.compress(b'IT WORKS IT WORKS IT WORKS')) == b'IT WORKS IT WORKS IT WORKS')
import zlib
assert(zlib.decompress(zlib.compress(b'IT WORKS IT WORKS IT WORKS')) == b'IT WORKS IT WORKS IT WORKS')
| import curses
import readline
import bz2
assert(bz2.decompress(bz2.compress(b'IT WORKS IT WORKS IT WORKS')) == b'IT WORKS IT WORKS IT WORKS')
import platform
if platform.python_implementation() != 'PyPy' and platform.python_version_tuple()[0] != '2':
# PyPy and Python 2 don't support lzma
import lzma
assert(lzma.decompress(lzma.compress(b'IT WORKS IT WORKS IT WORKS')) == b'IT WORKS IT WORKS IT WORKS')
import zlib
assert(zlib.decompress(zlib.compress(b'IT WORKS IT WORKS IT WORKS')) == b'IT WORKS IT WORKS IT WORKS')
| apache-2.0 | Python |
f6ea09312fd3f261c2273ffca703e93f0ae33bda | Create analysis.py | alexiskulash/ia-caucus-sentiment | src/analysis.py | src/analysis.py | def normalize(token):
token = token.replace(".","")
token = token.replace(",","")
token = token.replace("'","")
token = token.replace(";","")
token = token.replace("\n","")
token = token.replace("\'","")
token = token.replace("\"","")
token = token.replace("#","")
token = token.lower()
return token
f = open("output.txt", 'r')
tokens = f.read().split(" ")
normalized_text = []
for i in tokens:
i = normalize(i)
normalized_text.append(i)
print(normalized_text)
#Democrats
hillary = []
omalley = []
bernie = []
#Republicans
trump = []
jeb = []
randpaul = []
santorum = []
christie = []
carson = []
carly = []
cruz = []
huckabee = []
graham = []
for word in normalized_text:
if word == "hillary" or word == "hillaryclinton" or word == "hillary2016" or word == "hillyes" or word == "hillary clinton":
hillary.append(word)
elif word == "trump" or word == "donaldtrump" or word == "trump2016" or word == "realDonaldTrump":
trump.append(word)
elif word == "bernie" or word == "berniesanders" or word == "feelthebern" or word == "berniesanders2016" or word == "sanders":
bernie.append(word)
elif word == "o'malley" or word == "omalley" or word == "omalley2016" or word == "martinomalley":
omalley.append(word)
elif word == "jeb" or word == "jebbush" or word == "jeb2016":
jeb.append(word)
elif word == "carson" or word == "bc2dc16" or word == "realbencarson" or word == "carson2016":
carson.append(word)
elif word == "cruz" or word == "cruzcrew" or word == "tedcruz" or word == "cruz2016":
cruz.append(word)
elif word == "kasich" or word == "kasich4us" or word == "johnkasich" or word == "kasich2016":
kasich.append(word)
elif word == "randpaul" or word == "randpaul2016" or word == "rand paul":
randpaul.append(word)
elif word == "fiorina" or word == "carly2016" or word == "carlyfiorina" or word == "carly fiorina":
carly.append(word)
elif word == "chris christie" or word == "christie2016" or word == "chrischristie":
christie.append(word)
elif word == "jim gilmore" or word == "jimgilmore" or word == "gov_gilmore" or word == "gilmore2016":
gilmore.append(word)
elif word == "graham" or word == "lindseygraham" or word == "lindsey graham" or word == "lindseygrahamsc":
graham.append(word)
elif word == "huckabee" or word == "imwithhuck" or word == "govmikehuckabee" or word == "huckabee2016":
huckabee.append(word)
elif word == "pataki" or word == "georgepataki" or word == "governorpataki" or word == "pataki2016":
pataki.append(word)
elif word == "rubio" or word == "marco rubio" or word == "rubio2016":
rubio.append(word)
elif word == "santorum" or word == "ricksantorum" or word == "rick santorum" or word == "santorum2016":
santorum.append(word)
#print(hillary)
#print(trump)
#print(bernie)
total = len(bernie) + len(hillary) + len(trump)
percentb = len(bernie)*100 / total
percenth = len(hillary)*100 / total
percentt = len(trump)*100 / total
print("Hillary: ")
print(percenth)
print("Bernie: ")
print(percentb)
print("Trump: ")
print(percentt)
| mit | Python | |
8e9a0f54e6bd0448264537a1b61c0810ae8fc4d4 | Add files via upload | QuirinoC/Python | palindrome.py | palindrome.py | not_aceptable_characters = [".",",","?","!","@","#","\"", "\'", \
"(", ")","'", " ","-",";","\n",'',"-"]
'''
Copyright Quirino...
jk use it as yours if you want.
#Documenting after writing is boring
'''
#Realized classes are not that dificult, this class is realy useful
#This class makes it easier for me to do useful things with a string
'''
I used a class because it was a pain for me naming variables
This way i instantiate once then use the class
'''
class palindrome(object):
#This __init__ thing creates the object itself
'''
Now with this class we could do something like
Pstring = palindrome("Ana")
And the class will make:
-A filtered string (self.string)
-A reversed string (self.reversed)
-A splited string in case is not just a word (self.listed)
-A method that checks for palindrome string (ispalindrome())
-And has a method to create an filtered list (flist())
#NOTE:
The methods of the class would be used as self.ispalindrome()
'''
def __init__(self, string):
self.string = (filter(string, not_aceptable_characters))
self.reversed = (self.string)[::-1]
self.listed = string.split()
def ispalindrome(self):
if self.string == self.reversed:
return True
else:
return False
def flist(self):
newList = []
for i in self.listed:
newList.append(filter(i,not_aceptable_characters))
return newList
def filter(string,filter_list):
#This function takes a string argument, and uses a filter that is a list
#(See line 1) so the non desired character gets eliminated from the string
new_word = ""
for i in string:
if i not in filter_list:
new_word += i
return new_word.lower()
def palindrome_(string):
'''
Oh boy this one was tricky.
---------------------------
First we create a Pstring object using the palindrome class
Now we can use all its variables and methods for check which kind
Of palindrome the string is, i included 3 basic cases
'''
Pstring = palindrome(string)
#First Case:
#The Whole sentence is palindrome
if Pstring.ispalindrome():
print("\nThe whole string is character palindrome\n")
''' Thanks to the class i used above i saved myself 3 lines,
And confusion when it comes to variable usage
More readable code
#IGNORE#
Pstring = string
FPstring = filter(Pstring,not_aceptable_characters)
RFPstring = FPstring[::-1]
if FPstring == RFPstring:
print("\nThe whole thing is character palindrome\n")
#IGNORE#
'''
##########################################################
#Second Case:
#Show palindrome words in the string
palindromeWords = []
for i in Pstring.flist():
Pword = palindrome(i)
if i not in palindromeWords and Pword.ispalindrome():
palindromeWords.append(i)
##########################################################
if len(palindromeWords) > 0:
print("\nThis words are palindrome:")
for i in palindromeWords:
print (i)
print ()
#Third case:
#The string is palindrome in a words way like
#Hola ana como te va te como ana Hola
if Pstring.flist() == Pstring.flist()[::-1]:
print ("This string is word palindrome\n")
##########################################################
def start():
#This function takes user prompt to decide wheter the input will be a file
#Or a user given string
user_input = input(\
"Please input F to check a File or S to analize auser String: ")
if user_input.upper() == "F":
print("\n\
File must be in the same folder, \n\
Please write with extension, if the file is \n\
a .docx please write file.docx\n")
#Since its very easy for the user to get the name of the file wrong
#try will save the day
try:
file_ = open(input("Name of file: \n"),"r+")
file_string = file_.read()
file_.close()
palindrome_(file_string)
except:
print ("There is no such file")
start()
elif user_input.upper() == "S":
palindrome_(input("Please input the string to test: \n"))
else:
print ("Invalid Input")
start()
start()
| apache-2.0 | Python | |
df10bd85bcf94aba9661e397960a1cd3b4dd090d | Test for ISO NC creator | danheeks/heekscnc,danheeks/heekscnc,danheeks/heekscnc,danheeks/heekscnc | POST_TEST.py | POST_TEST.py | from posts.nc import *
import posts.iso
output('POST_TEST.txt')
program_begin(123, 'Test program')
absolute()
metric()
set_plane(0)
feedrate(420)
rapid(100,120)
rapid(z=50)
feed(z=0)
rapid(z=50)
rapid_home()
program_end()
| bsd-3-clause | Python | |
373b026c6ae0e1cae8236a0ba6d0bd8ce3ccab7c | Add missing module | vmalloc/backslash-python,slash-testing/backslash-python | backslash/compatibility.py | backslash/compatibility.py | class Compatibility(object):
def __init__(self, client):
super(Compatibility, self).__init__()
self.client = client
| bsd-3-clause | Python | |
eeff8a4e33a72b4efe5fb3a43bef2b60cd9b6752 | add image processing | vsimonis/worm1 | imgProc.py | imgProc.py | """
Created on Wed Dec 04 21:53:29 201
@author: Valerie
"""
from skimage import io, morphology, exposure,util
from skimage.measure import regionprops
#import matplotlib.pyplot as plt
import numpy as np
class imgProc:
def __init__():
def applyThresh( self, imgIn, t ):
imgIn1 = imgIn.ravel()
imgOut = np.zeros( ( np.shape(imgIn) ) ).ravel()
inds = np.arange( len(imgIn1) )[imgIn1 > t]
for ind in inds:
imgOut[ind] = 1
imgOut = np.reshape( imgOut, np.shape(imgIn) )
return imgOut
def threshAUHist( self, imgIn, avg, sd ):
pxCnt, gL = exposure.histogram( imgIn )
auh = 0
gli = 0 #index into pxCnt and gL
while( auh < avg + sd ):
auh += pxCnt[gli]
gli += 1
t = gL[gli-1]
imgOut = applyThresh( imgIn, t )
return imgOut
def morphOps( self, imgIn, sizeSE ):
imgOut = util.img_as_bool( imgIn ) #boolean image
imgOut = ~imgOut #img negative
imgOut = morphology.remove_small_objects( imgOut, 2000 ) #largest cc
SE = morphology.selem.disk( sizeSE ) #structuring element
imgOut = morphology.closing(imgOut, SE)
return imgOut
def getCentroid( self, imgIn ):
imgInL = morphology.label( imgIn )
regions = regionprops( imgInL )
y,x = regions[0]['Centroid']
return x, y
## Sample run
#J = threshAUHist(I, 4223, 19)
#J = morphOps(J,3)
#x, y = getCentroid(J)
#print x, y
#io.imshow(J)
| mit | Python | |
7d9410b90f03355ad22e562b568ec50efdcc96f4 | Create settings.py and add default path settings | hedderich/aqbanking-cli-wrapper | settings.py | settings.py | import os
AQBANKING_PATH = os.path.expanduser('~/.aqbanking/')
CACHE_PATH = os.path.join(AQBANKING_PATH, 'tmp')
BALANCE_PATH = os.path.join(CACHE_PATH, 'balance.ctx') | apache-2.0 | Python | |
53af7a4c8750a6660e34fad476f64198ab97443e | add - settings | anastasia/WARC-diff-tools | settings.py | settings.py | DECOMPRESS = True
| mit | Python | |
834a570a8073028fff86c91bd808ffc5ce6a835f | add settings to set constant ntulearn login url | manzaigit/ntulearndownloader,manzaigit/ntulearndownloader | settings.py | settings.py | NTULEARN_URL = "https://ntulearn.ntu.edu.sg/webapps/login/"
| mit | Python | |
53cb211fda4b46d38a10808893b8713cfb17d080 | Create ShinyAppsApp | mfcovington/djangocms-shiny-app,mfcovington/djangocms-shiny-app,mfcovington/djangocms-shiny-app | cms_shiny/cms_app.py | cms_shiny/cms_app.py | # -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from cms.app_base import CMSApp
from cms.apphook_pool import apphook_pool
from cms_shiny.menu import ShinyAppsMenu
class ShinyAppsApp(CMSApp):
name = _("Shiny Apps App")
urls = ["cms_shiny.urls"]
app_name = "cms_shiny"
menus = [ShinyAppsMenu]
apphook_pool.register(ShinyAppsApp)
| bsd-3-clause | Python | |
48984b9ab60c14c5d47ee329ef906d47b35b8ade | Add common tests for query endpoint | biothings/biothings.api,biothings/biothings.api | biothings/tests/test_query.py | biothings/tests/test_query.py | '''
Biothings Query Component Common Tests
'''
import os
from nose.core import main
from biothings.tests import BiothingsTestCase
class QueryTests(BiothingsTestCase):
''' Test against server specified in environment variable BT_HOST
and BT_API or MyGene.info production server V3 by default '''
__test__ = True
host = os.getenv("BT_HOST", "http://mygene.info")
api = os.getenv("BT_API", "/v3")
def test_01(self):
''' KWARGS CTRL Format Json '''
self.query(q='*', size='1')
def test_02(self):
''' KWARGS CTRL Format Yaml '''
res = self.request('query?q=*&size=1&out_format=yaml').text
assert res.startswith('max_score:')
def test_03(self):
''' KWARGS CTRL Format Html '''
res = self.request('query?q=*&size=1&out_format=html').text
assert '<html>' in res
def test_04(self):
''' KWARGS CTRL Format Msgpack '''
res = self.request('query?q=*&size=1&out_format=msgpack').content
self.msgpack_ok(res)
if __name__ == '__main__':
main(defaultTest='__main__.QueryTests', argv=['', '-v'])
| apache-2.0 | Python | |
fb41b16f95490b15190075403aa3d87fcfa34853 | Create smash.py | GaryBrittain/Smashrun | smash.py | smash.py | import urllib, urllib2, json
from stravalib.client import Client
from stravalib import unithelper
import dateutil.parser as parser
from pytz import timezone
activityId = 321998419
client = Client(access_token="")
activity = client.get_activity(activityId)
localtz = timezone(str(activity.timezone))
types = ['distance', 'latlng', 'time', 'altitude', 'moving']
streams = client.get_activity_streams(activityId, types=types, resolution='high')
latList = []
lngList = []
for lat,lng in streams['latlng'].data:
latList.append(lat)
lngList.append(lng)
waypointCount = len(streams['time'].data)
duration = []
cumulPause = 0
for idx in range(0,waypointCount):
if idx == 0:
duration.append(streams['time'].data[idx])
current = streams['time'].data[idx]
elif streams['moving'].data[idx] == True:
duration.append(int(streams['time'].data[idx]) - cumulPause)
current = (streams['time'].data[idx])
elif streams['moving'].data[idx] == False:
duration.append(int(current - cumulPause))
cumulPause = cumulPause + (streams['time'].data[idx] - current)
print streams['time'].data
print streams['moving'].data
print duration
distance = []
for idx in range(0,waypointCount):
distance.append(float(streams['distance'].data[idx] / 1000))
parameters = {
'activityType': "running",
'distance': float(unithelper.kilometers(activity.distance)),
'duration': activity.moving_time.seconds,
'startDateTimeLocal': localtz.localize(activity.start_date_local).isoformat(),
'note': activity.name,
'externalId': activity.id,
'recordingKeys':["latitude","longitude","duration","clock","distance","elevation"],
'recordingValues': (latList,lngList,duration,streams['time'].data,distance,streams['altitude'].data)
}
headers = {
'Content-Type': "application/json",
'Authorization': "Bearer "
}
data = json.dumps(parameters)
url = "https://api.smashrun.com/v1/my/activities"
req = urllib2.Request(url,data,headers)
response = urllib2.urlopen(req)
print response.read()
| mit | Python | |
8a39e7993bdf67c85d7f2e25ccf7fe3f82502479 | Create Problem14.py | xiaoyougang/ProjectEulerSolution | Problem14.py | Problem14.py | import time
def f(n):
if n%2==1 and n>1:
return f(3*n+1)+1
elif n%2==0:
return f(n/2)+1
return 1
m,value=0,0
begin=time.time()
for i in range(1,1000000):
tmp=f(i)
if tmp>m:
value=i
m=tmp
print time.time()-begin
print m,value
| apache-2.0 | Python | |
1b36957858c5ceba018d23be19b04e730c231ff6 | Implement timer to support Timer.Interval.* events | JokerQyou/Modder2 | modder/timer.py | modder/timer.py | # coding: utf-8
import threading
import time
class TimerThread(threading.Thread):
def __init__(self, queue, stop_event):
super(TimerThread, self).__init__()
self.__queue = queue
self.__stopped = stop_event
self.__wait = .5
now = time.time()
self.__last_trigger_minute = now
self.__last_trigger_hour = now
self.__last_trigger_day = now
def run(self):
while not self.__stopped.wait(self.__wait):
now = time.time()
passed_minute = now - self.__last_trigger_minute
passed_hour = now - self.__last_trigger_hour
passed_day = now - self.__last_trigger_day
if passed_minute >= 60:
self.__last_trigger_minute = now
self.__queue.put('Timer.Interval.Minute')
if passed_hour >= 3600:
self.__last_trigger_hour = now
self.__queue.put('Timer.Interval.Hour')
if passed_day >= 86400:
self.__last_trigger_day = now
self.__queue.put('Timer.Interval.Day')
| mit | Python | |
638e2d7a33f522007d80d39e0a8e5bface654286 | Add unit tests for utility methods. | alexisrolland/data-quality,alexisrolland/data-quality,alexisrolland/data-quality,alexisrolland/data-quality | test/test_scripts/test_utils.py | test/test_scripts/test_utils.py | from scripts.init import utils
import unittest
class TestUtils(unittest.TestCase):
@classmethod
def setUpClass(self):
pass
def test_get_parameter(self):
api = utils.get_parameter('api')
url = utils.get_parameter('api', 'url')
# Assert parameters are not empty
self.assertGreater(len(api), 0)
self.assertGreater(len(url), 0)
def test_execute_graphql_request(self):
payload = 'query{allDataSourceTypes{nodes{id}}}'
data = utils.execute_graphql_request(payload)
nb_records = len(data['data']['allDataSourceTypes']['nodes'])
# Assert graphql query returned records
self.assertGreater(nb_records, 0)
@classmethod
def tearDownClass(self):
pass
if __name__ == '__main__':
unittest.main()
| apache-2.0 | Python | |
9e42b39ffcab22b1a2f684353ce1242ce4a238d4 | Add support for export of graphs in DOT format | MD-Studio/MDStudio,MD-Studio/MDStudio,MD-Studio/MDStudio,MD-Studio/MDStudio,MD-Studio/MDStudio | components/lie_graph/lie_graph/graph_io/io_dot_format.py | components/lie_graph/lie_graph/graph_io/io_dot_format.py | # -*- coding: utf-8 -*-
"""
file: io_dict_format.py
Functions for exporting and importing graphs to and from graph description
language (DOT) format
"""
import sys
import json
if sys.version_info[0] < 3:
import StringIO
else:
from io import StringIO
from lie_graph import __module__, __version__
def write_dot(graph, node_key_tag=None, edge_key_tag=None, graph_name='graph', dot_directives={}):
"""
DOT graphs are either directional (digraph) or undirectional, mixed mode
is not supported.
Basic types for node and edge attributes are supported.
:param graph: Graph object to export
:type graph: :lie_graph:Graph
:param node_key_tag: node data key
:type node_key_tag: :py:str
:param edge_key_tag: edge data key
:type edge_key_tag: :py:str
:param graph_name: graph name to include
:type graph_name: :py:str
:param dot_directives: special DOT format rendering directives
:type dot_directives: :py:dict
:return: DOT graph representation
:rtype: :py:str
"""
# Define node and edge data tags to export
node_key_tag = node_key_tag or graph.node_key_tag
edge_key_tag = edge_key_tag or graph.edge_key_tag
indent = ' ' * 4
link = '->' if graph.is_directed else '--'
allowed_attr_types = (int, float, bool, str, unicode)
# Create empty file buffer
string_buffer = StringIO.StringIO()
# Write header comment and graph container
string_buffer.write('//Created by {0} version {1}\n'.format(__module__, __version__))
string_buffer.write('{0} "{1}" {2}\n'.format('digraph' if graph.is_directed else 'graph', graph_name, '{'))
# Write special DOT directives
for directive, value in dot_directives.items():
string_buffer.write('{0}{1}={2}\n'.format(indent, directive, value))
# Export nodes
string_buffer.write('{0}//nodes\n'.format(indent))
for node in graph.iternodes():
attr = ['{0}={1}'.format(k, json.dumps(v)) for k,v in node.nodes[node.nid].items() if
isinstance(v, allowed_attr_types) and not k.startswith('$')]
if attr:
string_buffer.write('{0}{1} [{2}];\n'.format(indent, node.nid, ','.join(attr)))
# Export adjacency
string_buffer.write('{0}//edges\n'.format(indent))
done = []
for node, adj in graph.adjacency.items():
for a in adj:
edges = [(node, a), (a, node)]
if all([e not in done for e in edges]):
attr = {}
for edge in edges:
attr.update(graph.edges.get(edge, {}))
attr = ['{0}={1}'.format(k, json.dumps(v)) for k, v in attr.items() if
isinstance(v, allowed_attr_types) and not k.startswith('$')]
if attr:
string_buffer.write('{0}{1} {2} {3} [{4}];\n'.format(indent, node, link, a, ','.join(attr)))
else:
string_buffer.write('{0}{1} {2} {3};\n'.format(indent, node, link, a))
done.extend(edges)
# Closing curly brace
string_buffer.write('}\n')
# Reset buffer cursor
string_buffer.seek(0)
return string_buffer.read() | apache-2.0 | Python | |
c227eb585817cd7385486a4292814c1c6bbca3da | Add test_webcast_india_gov.py | back-to/streamlink,bastimeyer/streamlink,wlerin/streamlink,melmorabity/streamlink,melmorabity/streamlink,beardypig/streamlink,chhe/streamlink,javiercantero/streamlink,gravyboat/streamlink,wlerin/streamlink,bastimeyer/streamlink,back-to/streamlink,beardypig/streamlink,javiercantero/streamlink,streamlink/streamlink,chhe/streamlink,gravyboat/streamlink,streamlink/streamlink | tests/test_webcast_india_gov.py | tests/test_webcast_india_gov.py | import unittest
from streamlink.plugins.webcast_india_gov import WebcastIndiaGov
class TestPluginWebcastIndiaGov(unittest.TestCase):
def test_can_handle_url(self):
# should match
self.assertTrue(WebcastIndiaGov.can_handle_url("http://webcast.gov.in/ddpunjabi/"))
self.assertTrue(WebcastIndiaGov.can_handle_url("http://webcast.gov.in/#Channel1"))
self.assertTrue(WebcastIndiaGov.can_handle_url("http://webcast.gov.in/#Channel3"))
# shouldn't match
self.assertFalse(WebcastIndiaGov.can_handle_url("http://meity.gov.in/"))
self.assertFalse(WebcastIndiaGov.can_handle_url("http://www.nic.in/"))
self.assertFalse(WebcastIndiaGov.can_handle_url("http://digitalindiaawards.gov.in/")) | bsd-2-clause | Python | |
d1b0da728d408cdb6c3acdb17b1cf9a54667a09b | Add first fraft Outlier Detection class Fix #26 | ericfourrier/auto-clean | autoc/outliersdetection.py | autoc/outliersdetection.py | """
@author: efourrier
Purpose : This is a simple experimental class to detect outliers. This class
can be used to detect missing values encoded as outlier (-999, -1, ...)
"""
from autoc.explorer import DataExploration, pd
import numpy as np
#from autoc.utils.helpers import cserie
from exceptions import NotNumericColumn
def iqr(ndarray):
return np.percentile(ndarray, 75) - np.percentile(ndarray, 25)
def z_score(ndarray):
return (ndarray - np.mean(ndarray)) / (np.std(ndarray))
def iqr_score(ndarray):
return (ndarray - np.median(ndarray)) / (iqr(ndarray))
def mad_score(ndarray):
return (ndarray - np.median(ndarray)) / (np.median(np.absolute(ndarray - np.median(ndarray))) / 0.6745)
class OutliersDetection(DataExploration):
"""
this class focuses on identifying outliers
Parameters
----------
data : DataFrame
Examples
--------
* od = OutliersDetection(data = your_DataFrame)
* cleaner.structure() : global structure of your DataFrame
"""
def __init__(self, *args, **kwargs):
super(OutliersDetection, self).__init__(*args, **kwargs)
self.strong_cutoff = {'cutoff_zscore': 6,
'cutoff_iqrscore': 6, 'cutoff_mad': 6}
self.basic_cutoff = {'cutoff_zscore': 3,
'cutoff_iqrscore': 2, 'cutoff_mad': 2}
def check_negative_value(self, colname):
""" this function will detect if there is at leat one
negative value and calculate the ratio negative postive/
"""
if not self.is_numeric(colname):
NotNumericColumn("The serie should be numeric values")
return sum(serie < 0)
def outlier_detection_serie_1d(self, colname, cutoff_params, scores=[z_score, iqr_score, mad_score]):
if not self.is_numeric(colname):
raise("auto-clean doesn't support outliers detection for Non numeric variable")
keys = [str(func.__name__) for func in scores]
df = pd.DataFrame(dict((key, func(self.data.loc[:, colname]))
for key, func in zip(keys, scores)))
df['is_outlier'] = 0
if 'z_score' in keys:
df.loc[np.absolute(df['z_score']) >=
cutoff_params["cutoff_zscore"], 'is_outlier'] = 1
if 'iqr_score' in keys:
df.loc[np.absolute(df['iqr_score']) >=
cutoff_params["cutoff_iqrscore"], 'is_outlier'] = 1
if 'mad_score' in keys:
df.loc[np.absolute(df['mad_score']) >=
cutoff_params["cutoff_mad"], 'is_outlier'] = 1
return df
def check_negative_value(self):
""" this will return a the ratio negative/positve for each numeric
variable of the DataFrame
"""
return self.data[self._dfnum].apply(lambda x: self.check_negative_value_serie(x.name))
def outlier_detection_1d(self, cutoff_params, subset=None,
scores=[z_score, iqr_score, mad_score]):
""" Return a dictionnary with z_score,iqr_score,mad_score as keys and the
associate dataframe of distance as value of the dictionnnary"""
df = self.data.copy()
numeric_var = self._dfnum
if subset:
df = df.drop(subset, axis=1)
df = df.loc[:, numeric_var] # take only numeric variable
# if remove_constant_col:
# df = df.drop(self.constantcol(), axis = 1) # remove constant variable
df_outlier = pd.DataFrame()
for col in df:
df_temp = self.outlier_detection_serie_1d(col, scores, cutoff_params)
df_temp.columns = [col + '_' +
col_name for col_name in df_temp.columns]
#df_outlier = pd.concat([df_outlier, df_temp], axis=1)
return df_temp
| mit | Python | |
3c9067381158e773936b4dc47f488b43044e7bf8 | move file exceptions to resources folder | pagarme/pagarme-python | pagarme/resources/exceptions.py | pagarme/resources/exceptions.py | # encoding: utf-8
class PagarmeApiError(Exception): pass
class PagarmeTransactionError(Exception): pass
class NotPaidException(PagarmeTransactionError): pass
class NotBoundException(PagarmeTransactionError): pass
| mit | Python | |
f30c5daebc5e3b2f4cb5a636c5dbdbbbec682727 | add migration for related name of association rules | lucashanke/houseofdota,lucashanke/houseofdota,lucashanke/houseofdota | app/migrations/0013_auto_20170705_2007.py | app/migrations/0013_auto_20170705_2007.py | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-07-05 20:07
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('app', '0012_auto_20170703_2246'),
]
operations = [
migrations.AlterField(
model_name='bundleassociationrules',
name='patch_statistics',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='bundle_rules', to='app.PatchStatistics'),
),
migrations.AlterField(
model_name='counterassociationrules',
name='patch_statistics',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='counter_rules', to='app.PatchStatistics'),
),
]
| mit | Python | |
dde20ff437e2f9b9f0fb05de3f03c2c3b22bc563 | add an invoke builder for project development | scrapinghub/streamparse,Parsely/streamparse,hodgesds/streamparse,scrapinghub/streamparse,msmakhlouf/streamparse,Parsely/streamparse,eric7j/streamparse,codywilbourn/streamparse,petchat/streamparse,petchat/streamparse,petchat/streamparse,msmakhlouf/streamparse,scrapinghub/streamparse,petchat/streamparse,scrapinghub/streamparse,scrapinghub/streamparse,msmakhlouf/streamparse,crohling/streamparse,eric7j/streamparse,codywilbourn/streamparse,msmakhlouf/streamparse,petchat/streamparse,crohling/streamparse,phanib4u/streamparse,msmakhlouf/streamparse,hodgesds/streamparse,phanib4u/streamparse | tasks.py | tasks.py | from invoke import run, task
import os
@task
def lint():
for src in os.listdir("pystorm"):
if src.endswith(".py"):
run("pyflakes pystorm/{}".format(src))
#run("pep8 pystorm/{}".format(src))
@task
def build(docs=False):
run("python setup.py build")
if docs:
run("sphinx-build doc/source doc/_build")
@task
def develop():
run("python setup.py develop")
| apache-2.0 | Python | |
0cd883c22f82e33d05f6177fa9b99e2adf7cc644 | Add tasks file for use with Invoke | thebigmunch/gmusicapi-wrapper | tasks.py | tasks.py | # coding=utf-8
"""Useful task commands for development and maintenance."""
from invoke import run, task
@task
def build(clean):
"""Build sdist and bdist_wheel distributions."""
run('python setup.py sdist bdist_wheel')
@task(build)
def deploy():
"""Build and upload gmusicapi_wrapper distributions."""
upload()
@task
def upload():
"""Upload gmusicapi_wrapper distributions using twine."""
run('twine upload dist/*')
@task
def clean():
"""Clean the project directory of unwanted files and directories."""
run('rm -rf gmusicapi_wrapper.egg-info')
run('rm -rf .coverage')
run('rm -rf .tox')
run('rm -rf .cache')
run('rm -rf build/')
run('rm -rf dist/')
run('find . -name *.pyc -delete')
run('find . -name *.pyo -delete')
run('find . -name __pycache__ -delete -depth')
run('find . -name *~ -delete')
@task
def cover(verbose=False):
"""Shorter alias for coverage task."""
coverage(verbose)
@task
def coverage(verbose=False):
"""Run the gmusicapi_wrapper tests using pytest-cov for coverage."""
cov_cmd = 'py.test --cov ./gmusicapi_wrapper --cov ./tests ./gmusicapi_wrapper ./tests'
if verbose:
cov_cmd += ' -v'
run(cov_cmd)
@task
def test():
"""Run the gmusicapi_wrapper tests using pytest."""
run('py.test')
@task
def tox():
"""Run the gmusicapi_wrapper tests using tox."""
run('tox')
| mit | Python | |
bf9f053f4382fadba3901b3b5c247b3eaac22ea3 | Add test/unit/modules/sfp_apple_itunes.py | smicallef/spiderfoot,smicallef/spiderfoot,smicallef/spiderfoot | test/unit/modules/sfp_apple_itunes.py | test/unit/modules/sfp_apple_itunes.py | # test_sfp_apple_items.py
import unittest
from modules.sfp_apple_itunes import sfp_apple_itunes
from sflib import SpiderFoot
from spiderfoot import SpiderFootEvent, SpiderFootTarget
class TestModuleAppleItunes(unittest.TestCase):
"""
Test modules.sfp_apple_itunes
"""
default_options = {
'_debug': False, # Debug
'__logging': True, # Logging in general
'__outputfilter': None, # Event types to filter from modules' output
'_useragent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:62.0) Gecko/20100101 Firefox/62.0', # User-Agent to use for HTTP requests
'_dnsserver': '', # Override the default resolver
'_fetchtimeout': 5, # number of seconds before giving up on a fetch
'_internettlds': 'https://publicsuffix.org/list/effective_tld_names.dat',
'_internettlds_cache': 72,
'_genericusers': "abuse,admin,billing,compliance,devnull,dns,ftp,hostmaster,inoc,ispfeedback,ispsupport,list-request,list,maildaemon,marketing,noc,no-reply,noreply,null,peering,peering-notify,peering-request,phish,phishing,postmaster,privacy,registrar,registry,root,routing-registry,rr,sales,security,spam,support,sysadmin,tech,undisclosed-recipients,unsubscribe,usenet,uucp,webmaster,www",
'__version__': '3.3-DEV',
'__database': 'spiderfoot.test.db', # note: test database file
'__modules__': None, # List of modules. Will be set after start-up.
'_socks1type': '',
'_socks2addr': '',
'_socks3port': '',
'_socks4user': '',
'_socks5pwd': '',
'_torctlport': 9051,
'__logstdout': False
}
def test_opts(self):
module = sfp_apple_itunes()
self.assertEqual(len(module.opts), len(module.optdescs))
def test_setup(self):
"""
Test setup(self, sfc, userOpts=dict())
"""
sf = SpiderFoot(self.default_options)
module = sfp_apple_itunes()
module.setup(sf, dict())
def test_watchedEvents_should_return_list(self):
module = sfp_apple_itunes()
self.assertIsInstance(module.watchedEvents(), list)
def test_producedEvents_should_return_list(self):
module = sfp_apple_itunes()
self.assertIsInstance(module.producedEvents(), list)
@unittest.skip("todo")
def test_handleEvent(self):
"""
Test handleEvent(self, event)
"""
sf = SpiderFoot(self.default_options)
module = sfp_apple_itunes()
module.setup(sf, dict())
target_value = 'example target value'
target_type = 'IP_ADDRESS'
target = SpiderFootTarget(target_value, target_type)
module.setTarget(target)
event_type = 'ROOT'
event_data = 'example data'
event_module = ''
source_event = ''
evt = SpiderFootEvent(event_type, event_data, event_module, source_event)
result = module.handleEvent(evt)
self.assertIsNone(result)
| mit | Python | |
5bab29cbdb1d5db9949a9379656cf1a925fcf20a | Add test suite for SettingFunction | onitake/Uranium,onitake/Uranium | tests/Settings/TestSettingFunction.py | tests/Settings/TestSettingFunction.py | # Copyright (c) 2016 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
import pytest
import UM.Settings.SettingFunction
## Individual test cases for the good setting functions.
#
# Each test will be executed with each of these functions. These functions are
# all good and should work.
setting_function_good_data = [
"0", # Number.
"\"x\"", # String.
"foo", # Variable.
"math.sqrt(4)", # Function call.
"foo * zoo" # Two variables.
]
## Fixture to create a setting function.
#
# These setting functions are all built with good functions. Id est no errors
# should occur during the creation of the fixture.
@pytest.fixture(params = setting_function_good_data)
def setting_function_good(request):
return UM.Settings.SettingFunction.SettingFunction(request.param)
## Individual test cases for the bad setting functions.
#
# Each test will be executed with each of these functions. These functions are
# all bad and should not work.
setting_function_bad_data = [
"" # Empty string.
"lambda i: os.open(/etc/passwd).read()", # Function that reads your passwords from your system.
"exec(\"lambda i: o\" + \"s.open(/etc/passwd).read()\")", # Obfuscated function that reads your passwords from your system.
"(" # Syntax error.
]
## Fixture to create a setting function.
#
# These setting functions are all built with bad functions. Id est they should
# give an error when creating the fixture.
@pytest.fixture(params = setting_function_bad_data)
def setting_function_bad(request):
return UM.Settings.SettingFunction.SettingFunction(request.param)
## Tests the initialisation of setting functions with good functions.
#
# Each of these should create a good function.
def test_init_good(setting_function_good):
assert setting_function_good is not None
assert setting_function_good.isValid()
## Tests the initialisation of setting functions with bad functions.
#
# Each of these should create a bad function.
def test_init_bad(setting_function_bad):
assert setting_function_bad is not None
assert not setting_function_bad.isValid() | agpl-3.0 | Python | |
99d33908b6610385f9c9f83678533611a515f5aa | Create List_Slicing.py | UmassJin/Leetcode | Python/List_Slicing.py | Python/List_Slicing.py | Array Slicing
a[start:end] # items start through end-1
a[start:] # items start through the rest of the array
a[:end] # items from the beginning through end-1
a[:] # a copy of the whole array
There is also the step value, which can be used with any of the above:
a[start:end:step] # start through not past end, by step
The key point to remember is that the :end value represents the first value
that is not in the selected slice. So, the difference beween end and start is
the number of elements selected (if step is 1, the default).
The other feature is that start or end may be a negative number, which means
it counts from the end of the array instead of the beginning. So:
a[-1] # last item in the array
a[-2:] # last two items in the array
a[:-2] # everything except the last two items
The ASCII art diagram is helpful too for remembering how slices work:
+---+---+---+---+---+
| H | e | l | p | A |
+---+---+---+---+---+
0 1 2 3 4 5
-5 -4 -3 -2 -1
>>> seq[:] # [seq[0], seq[1], ..., seq[-1] ]
>>> seq[low:] # [seq[low], seq[low+1], ..., seq[-1] ]
>>> seq[:high] # [seq[0], seq[1], ..., seq[high-1]]
>>> seq[low:high] # [seq[low], seq[low+1], ..., seq[high-1]]
>>> seq[::stride] # [seq[0], seq[stride], ..., seq[-1] ]
>>> seq[low::stride] # [seq[low], seq[low+stride], ..., seq[-1] ]
>>> seq[:high:stride] # [seq[0], seq[stride], ..., seq[high-1]]
>>> seq[low:high:stride] # [seq[low], seq[low+stride], ..., seq[high-1]]
array = [1,2,3,4,5,6]
array[start:end:step]
>>> array[::1]
[1, 2, 3, 4, 5, 6]
>>> array[::2]
[1, 3, 5]
>>> array[::3]
[1, 4]
>>> array[0::3]
[1, 4]
>>> array[0::2]
[1, 3, 5]
>>> array[1::2]
[2, 4, 6]
>>> array[-1]
6
>>> array[-2:]
[5, 6]
>>> array[:-2]
[1, 2, 3, 4]
| mit | Python | |
2bf6f29195c2e2c6079c2f851b337341b1a74629 | Add fabfile | idan/telostats,idan/telostats,idan/telostats | fabfile.py | fabfile.py | from fabric.api import local
def deploy_staticfiles():
local('STATIC_S3=1 ./manage.py collectstatic --noinput')
def deploy_heroku():
local('git push heroku')
def deploy():
deploy_staticfiles()
deploy_heroku()
| bsd-3-clause | Python | |
e78a3ada15092873d2bd7f0cd6b6f987bb62a50a | Migrate User#verified | jgorset/fandjango,jgorset/fandjango | fandjango/migrations/0008_auto__del_field_user_verified.py | fandjango/migrations/0008_auto__del_field_user_verified.py | # encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'User.verified'
db.delete_column('fandjango_user', 'verified')
def backwards(self, orm):
# Adding field 'User.verified'
db.add_column('fandjango_user', 'verified', self.gf('django.db.models.fields.NullBooleanField')(null=True, blank=True), keep_default=False)
models = {
'fandjango.oauthtoken': {
'Meta': {'object_name': 'OAuthToken'},
'expires_at': ('django.db.models.fields.DateTimeField', [], {'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'issued_at': ('django.db.models.fields.DateTimeField', [], {}),
'token': ('django.db.models.fields.CharField', [], {'max_length': '255'})
},
'fandjango.user': {
'Meta': {'object_name': 'User'},
'authorized': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'birthday': ('django.db.models.fields.DateField', [], {'null': 'True', 'blank': 'True'}),
'created_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'facebook_id': ('django.db.models.fields.BigIntegerField', [], {'unique': 'True'}),
'facebook_username': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'last_seen_at': ('django.db.models.fields.DateTimeField', [], {'auto_now_add': 'True', 'blank': 'True'}),
'middle_name': ('django.db.models.fields.CharField', [], {'max_length': '255', 'null': 'True', 'blank': 'True'}),
'oauth_token': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['fandjango.OAuthToken']", 'unique': 'True'})
}
}
complete_apps = ['fandjango']
| mit | Python | |
4ef9940a6f04dc37489e9deef164fb7c7edaf7f4 | fix import | ploxiln/fabric,mathiasertl/fabric,rodrigc/fabric | tests/support/tree/system/__init__.py | tests/support/tree/system/__init__.py | from fabric.api import task
from support.tree.system import debian
@task
def install_package():
pass
| from fabric.api import task
import debian
@task
def install_package():
pass
| bsd-2-clause | Python |
bf6d5b13eb6b5830390968814ebf3b2256011242 | Create find_mutation.py | elecabfer/Diverse,elecabfer/Diverse,elecabfer/Diverse,elecabfer/Diverse | find_mutation.py | find_mutation.py | import re
dir="/scratch/cluster/monthly/ecabello/Wareed/"
inputfiles=["gDNA5_S1", "gDNA-T75_S2" , "gDNA-TQ5_S3","Telo5_S4","Telo-T75_S5","Telo-TQ5_S6", "Telo-EV40_S7", "Telo-T740_S8", "Telo-TQ40_S9"]
#output = open("/scratch/cluster/monthly/ecabello/Wareed/new_sequencing/output_mutatio
strand="f"#raw_input("Strand? f/rev: ") #or "rev"
readlist=[]
####################################################
if strand != "rev":
print "FORWARD"
motivo6=r'T\wA[GT]{3,}.'
motivos=[r'T\wAGGG',r'T\wATGG',r'T\wAGTG',r'T\wAGGT', r'T\wATTG', r'T\wAGTT', r'T\wATTT']
output = open(dir+"/new_sequencing/output_mutations6x.xls" , 'w')
else:
print "REVERSE"
motivo6=r'[CA]{3}T\wA'
motivos=[r'CCCT\wA',r'CCAT\wA',r'CACT\wA',r'ACCT\wA', r'CAAT\wA', r'AACT\wA', r'AAAT\wA']
output = open(dir+"/new_sequencing/output_mutations_rev6x.xls" , 'w') #REVERSE
def findmotif(motifinput, motif6, fichier, salida): #motiflist y fichier son listas con los motivos y los archivos
for f in fichier:
R1=open(dir+"/new_sequencing/"+f+"_R1_001.fastq", "r").read().split("@NB500883")
salida.write(f+"\nMotif:\tNumber of hits:\tProportion:\tReads matching the motif, x times:")
a=0
t=0
g=0
c=0
r6=[]
R1=R1[1:]
motif6count=0
for entry in R1:
read2=entry.split("\n")
read=read2[1]
match6=re.findall(motif6,read)
if len(match6)>6:
r6.append(read)
motif6count = len(r6)
for l in motifinput:
#print f,l
motiflist=[]
cuenta=[]
countmatch=0
countread=0
readlist=[]
usedmotif=[]
for r in r6:
match=re.findall(l,r) #motivo
cuenta.append(len(match))
a+=r.count("A")
t+=r.count("T")
c+=r.count("C")
g+=r.count("G")
cuenta.append(len(match))
if len(match)>0: #or len(match6)>0 :
countread+=len(match)
# print match, len(match)
for m in match:
motiflist.append(m)
if m not in usedmotif:
usedmotif.append(m)
permillion=int((100.0/(motif6count+1))*countread) #replace count6read by len(R1)
salida.write("\n"+l+"\t"+str(countread)+"\t"+str(permillion)+" per 100")
if max(cuenta)>4: #in a tab
for n in range(4,max(cuenta)):
salida.write("\t"+str(n)+"x: "+str(cuenta.count(n)+1))
sum_nt=float(a+t+c+g)
ratioa=(a/sum_nt)*10
ratiot=(t/sum_nt)*10
ratiog=(g/sum_nt)*10
ratioc=(c/sum_nt)*10
salida.write("\nTotal number of reads: "+str(len(R1)+1))
salida.write('\nTotal number of reads with 6x motif: '+str(motif6count+1))
salida.write("\nComposition A: "+(str(ratioa))[:4]+"; T: "+ (str(ratiot))[:4]+ "; G: "+ (str(ratiog))[:4]+ "; C: "+ (str(ratioc))[:4])
salida.write("\n\n")
#print "\nComposition (%) A: "+str(ratioa)+"; T: "+ str(ratiot)+ "; G: "+ str(ratiog)+ "; C: "+ str(ratioc)
findmotif(motivos, motivo6, inputfiles, output)
print "FINI!!!"
#######################################
| mit | Python | |
5c7e096cb3847059d2212e5518852993e7ae4724 | Add sample query count_all_persons.py | google/personfinder,AwesomeTurtle/personfinder,groschovskiy/personfinder,clobrano/personfinder,kspviswa/personfinder,gauribhoite/personfinder,namanjain236/personfinder,AwesomeTurtle/personfinder,gauribhoite/personfinder,gauribhoite/personfinder,gauribhoite/personfinder,namanjain236/personfinder,gimite/personfinder,gauribhoite/personfinder,AwesomeTurtle/personfinder,clobrano/personfinder,gauribhoite/personfinder,clobrano/personfinder,g19-hs/personfinder,google/personfinder,lucasmoura/personfinder,groschovskiy/personfinder,lucasmoura/personfinder,google/personfinder,g19-hs/personfinder,google/personfinder,ominux/personfinder,gimite/personfinder,gimite/personfinder,ominux/personfinder,kspviswa/personfinder,gimite/personfinder | tools/sample_queries/count_all_persons.py | tools/sample_queries/count_all_persons.py | # Sample query for counting all the Person entries between dates.
query = Person.all(filter_expired=False).filter(
'entry_date >=', datetime.datetime(2013, 1, 1, 0, 0, 0)).filter(
'entry_date <', datetime.datetime(2014, 1, 1, 0, 0, 0))
count = 0
while True:
current_count = query.count()
if current_count == 0:
break
count += current_count
query.with_cursor(query.cursor())
print '# of persons =', count
| apache-2.0 | Python | |
61ded6588895c163fb3a37880b4de80bd8c3c85c | add new package (#27112) | LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/r-dtplyr/package.py | var/spack/repos/builtin/packages/r-dtplyr/package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RDtplyr(RPackage):
"""Data Table Back-End for 'dplyr'.
Provides a data.table backend for 'dplyr'. The goal of 'dtplyr' is to
allow you to write 'dplyr' code that is automatically translated to the
equivalent, but usually much faster, data.table code."""
homepage = "https://github.com/tidyverse/dtplyr"
cran = "dtplyr"
version('1.1.0', sha256='99681b7285d7d5086e5595ca6bbeebf7f4e2ee358a32b694cd9d35916cdfc732')
depends_on('r@3.3:', type=('build', 'run'))
depends_on('r-crayon', type=('build', 'run'))
depends_on('r-data-table@1.12.4:', type=('build', 'run'))
depends_on('r-dplyr@1.0.3:', type=('build', 'run'))
depends_on('r-ellipsis', type=('build', 'run'))
depends_on('r-glue', type=('build', 'run'))
depends_on('r-lifecycle', type=('build', 'run'))
depends_on('r-rlang', type=('build', 'run'))
depends_on('r-tibble', type=('build', 'run'))
depends_on('r-tidyselect', type=('build', 'run'))
depends_on('r-vctrs', type=('build', 'run'))
| lgpl-2.1 | Python | |
2b1afecd6bcf6c06cdc941552aad2c0737fa89cb | Add githook.py, an analog to hghook.py. | Khan/khan-linter,Khan/khan-linter,Khan/khan-linter,Khan/khan-linter | githook.py | githook.py | #!/usr/bin/env python
"""Commit hook for git that does lint testing.
It runs the lint checker (runlint.py) on all the open files in
the current commit.
To install (for git >= 1.7.1), run the following:
% git config --global init.templatedir '~/.git_template'
and then create a symlink from
~/.git_template/hooks/commit-msg
to this file.
"""
import os
import re
import subprocess
import sys
import runlint
def main():
"""Run a Mercurial pre-commit lint-check."""
# Go through all modified or added files.
try:
subprocess.check_output(['git', 'rev-parse', '--verify', 'HEAD'],
stderr=subprocess.STDOUT)
parent = 'HEAD'
except subprocess.CalledProcessError:
parent = '4b825dc642cb6eb9a060e54bf8d69288fbee4904' # empty repo
# Look at Added, Modified, and Renamed files.
files = subprocess.check_output(['git', 'diff', '--cached', '--name-only',
'--diff-filter=AMR', '-z', parent])
files_to_lint = files.strip('\0').split('\0') # that's what -z is for
num_errors = runlint.main(files_to_lint, blacklist='yes')
# Lint the commit message itself! Every non-merge commit must
# list either a test plan or a review that it's part of (the first
# commit in a review must have a test plan, but subsequent ones
# don't need to restate it). TODO(csilvers): should we do anything
# special with substate-update commits?
commit_message = open(sys.argv[1]).read()
if not re.search('^(test plan|review):', commit_message, re.I | re.M):
print >> sys.stderr, ('Missing "Test plan:" or "Review:" section '
'in the commit message.')
num_errors += 1
# TODO(csilvers): have a commit template that makes these tests useful.
elif re.search('^ <see below>$', commit_message, re.M):
print >> sys.stderr, ('Must enter a "Test plan:" (or "Review:") '
'in the commit message.')
num_errors += 1
if re.search('^<one-line summary, followed by ', commit_message, re.M):
print >> sys.stderr, 'Must enter a summary in the commit message.'
num_errors += 1
# TODO(csilvers): verify the first-line summary is actually 1 line long?
if num_errors:
# save the commit message so we don't need to retype it
f = open(os.path.join('.git', 'commit.save'), 'w')
f.write(commit_message)
f.close()
print >> sys.stderr, ('\n--- %s lint errors ---\n'
'Commit message saved to .git/commit.save'
% num_errors)
return 1
return 0
if __name__ == '__main__':
suppress_lint = os.getenv('FORCE_COMMIT', '')
if suppress_lint.lower() not in ('1', 'true'):
sys.exit(main())
| apache-2.0 | Python | |
86f41d5d57bc2fdfd91b18ee72efa7902d7bdc16 | add a module for programmatically generating jinja2 templates | fretboardfreak/netify | src/template.py | src/template.py | # Copyright 2015 Curtis Sand
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Generate Jinja2 Templates and/or HTML pages programmatically."""
from flask import Markup
from flask import render_template_string
from yattag import Doc
def render_template(template):
"""Run a template through Jinja2 and make it safe for the web.
:param template: Either a string or yattag.Doc object.
"""
if isinstance(template, Doc):
template_string = template.getvalue()
else:
template_string = template
return Markup(render_template_string(template_string))
class Page(object):
"""Base object for pages."""
def __init__(self, content):
if content is not None:
self.content = content
def build(self):
raise NotImplemented('Must be implemented by subclass.')
def __call__(self, *args, **kwargs):
self.__class__.__init__(self, *args, **kwargs)
return self.build()
class HtmlPage(Page):
"""Build an HTML Page with the given head and body content.
:param head: Either a string or yattag.Doc object representing the page's
head section. If not otherwise provided the default header
will contain only the charset meta tag.
:param body: Either a string or yattag.Doc object representing the page's
body section.
"""
object_string_map = {'head': 'head_txt', 'body': 'body_txt'}
def __init__(self, head=None, body=None):
if head is not None:
self.head = head
if body is not None:
self.body = body
def _get_text(self):
"""Convert possible yattag.Doc objects to strings."""
for obj_name in self.object_string_map:
obj = getattr(self, obj_name, '')
obj = '' if obj is None else obj
if isinstance(obj, Doc):
setattr(self, self.object_string_map[obj_name],
obj.getvalue())
else:
setattr(self, self.object_string_map[obj_name], obj)
def build(self):
if getattr(self, 'head', '') in ['', None]:
self.head = Doc()
self.head.stag('meta', charset='utf-8')
self._get_text()
doc = Doc()
doc.asis('<!DOCTYPE html/>')
with doc.tag('html'):
doc.attr(lang='en')
with doc.tag('head'):
doc.asis(self.head_txt)
with doc.tag('body'):
doc.asis(self.body_txt)
return doc
| apache-2.0 | Python | |
43873584dbb28feced2fc28a0721521a1758e09d | Print hello world | pk-python/basics | print.py | print.py | print('Hello World!') | mit | Python | |
8e8e2b99a0fc0ce572b31451078628709a80e7d5 | add short tutorial for geometric transformations | emmanuelle/scikits.image,ofgulban/scikit-image,paalge/scikit-image,newville/scikit-image,SamHames/scikit-image,bsipocz/scikit-image,warmspringwinds/scikit-image,paalge/scikit-image,GaZ3ll3/scikit-image,paalge/scikit-image,dpshelio/scikit-image,keflavich/scikit-image,almarklein/scikit-image,juliusbierk/scikit-image,oew1v07/scikit-image,rjeli/scikit-image,pratapvardhan/scikit-image,warmspringwinds/scikit-image,Hiyorimi/scikit-image,ofgulban/scikit-image,juliusbierk/scikit-image,SamHames/scikit-image,SamHames/scikit-image,Midafi/scikit-image,Britefury/scikit-image,Hiyorimi/scikit-image,bsipocz/scikit-image,bennlich/scikit-image,vighneshbirodkar/scikit-image,vighneshbirodkar/scikit-image,bennlich/scikit-image,pratapvardhan/scikit-image,chriscrosscutler/scikit-image,ajaybhat/scikit-image,rjeli/scikit-image,robintw/scikit-image,ajaybhat/scikit-image,michaelaye/scikit-image,michaelpacer/scikit-image,youprofit/scikit-image,jwiggins/scikit-image,rjeli/scikit-image,keflavich/scikit-image,ClinicalGraphics/scikit-image,ClinicalGraphics/scikit-image,chintak/scikit-image,emmanuelle/scikits.image,Midafi/scikit-image,jwiggins/scikit-image,youprofit/scikit-image,vighneshbirodkar/scikit-image,ofgulban/scikit-image,SamHames/scikit-image,blink1073/scikit-image,almarklein/scikit-image,GaZ3ll3/scikit-image,newville/scikit-image,michaelaye/scikit-image,dpshelio/scikit-image,oew1v07/scikit-image,robintw/scikit-image,emon10005/scikit-image,chintak/scikit-image,almarklein/scikit-image,michaelpacer/scikit-image,almarklein/scikit-image,chintak/scikit-image,emmanuelle/scikits.image,blink1073/scikit-image,Britefury/scikit-image,emmanuelle/scikits.image,WarrenWeckesser/scikits-image,chriscrosscutler/scikit-image,WarrenWeckesser/scikits-image,emon10005/scikit-image,chintak/scikit-image | doc/examples/applications/plot_geometric.py | doc/examples/applications/plot_geometric.py | """
===============================
Using geometric transformations
===============================
In this example, we will see how to use geometric transformations in the context
of image processing.
"""
import math
import numpy as np
import matplotlib.pyplot as plt
from skimage import data
from skimage import transform as tf
margins = dict(hspace=0.01, wspace=0.01, top=1, bottom=0, left=0, right=1)
"""
Basics
======
Several different geometric transformation types are supported: similarity,
affine, projective and polynomial.
Geometric transformations can either be created using the explicit parameters
(e.g. scale, shear, rotation and translation) or the transformation matrix:
"""
#: create using explicit parameters
tform = tf.SimilarityTransformation()
scale = 1
rotation = math.pi/2
translation = (0, 1)
tform.from_params(scale, rotation, translation)
print tform.matrix
#: create using transformation matrix
matrix = tform.matrix.copy()
matrix[1, 2] = 2
tform2 = tf.SimilarityTransformation(matrix)
"""
These transformation objects can be used to forward and reverse transform
coordinates between the source and destination coordinate systems:
"""
coord = [1, 0]
print tform2.forward(coord)
print tform2.reverse(tform.forward(coord))
"""
Image warping
=============
Geometric transformations can also be used to warp images:
"""
text = data.text()
tform.from_params(1, math.pi/4, (text.shape[0] / 2, -100))
# uses tform.reverse, alternatively use tf.warp(text, tform.reverse)
rotated = tf.warp(text, tform)
back_rotated = tf.warp(rotated, tform.forward)
plt.figure(figsize=(8, 3))
plt.subplot(131)
plt.imshow(text)
plt.axis('off')
plt.gray()
plt.subplot(132)
plt.imshow(rotated)
plt.axis('off')
plt.gray()
plt.subplot(133)
plt.imshow(back_rotated)
plt.axis('off')
plt.gray()
plt.subplots_adjust(**margins)
"""
.. image:: PLOT2RST.current_figure
Parameter estimation
====================
In addition to the basic functionality mentioned above you can also estimate the
parameters of a geometric transformation using the least-squares method.
This can amongst other things be used for image registration or rectification,
where you have a set of control points or homologous points in two images.
Let's assume we want to recognize letters on a photograph which was not taken
from the front but at a certain angle. In the simplest case of a plane paper
surface the letters are projectively distorted. Simple matching algorithms would
not be able to match such symbols. One solution to this problem would be to warp
the image so that the distortion is removed and then apply a matching algorithm:
"""
text = data.text()
src = np.array((
(155, 15),
(65, 40),
(260, 130),
(360, 95)
))
dst = np.array((
(0, 0),
(0, 50),
(300, 50),
(300, 0)
))
tform3 = tf.estimate_transformation('projective', src, dst)
warped = tf.warp(text, tform3, output_shape=(50, 300))
plt.figure(figsize=(8, 3))
plt.subplot(211)
plt.imshow(text)
plt.plot(src[:, 0], src[:, 1], '.r')
plt.axis('off')
plt.gray()
plt.subplot(212)
plt.imshow(warped)
plt.axis('off')
plt.gray()
plt.subplots_adjust(**margins)
"""
.. image:: PLOT2RST.current_figure
"""
plt.show()
| bsd-3-clause | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.