function stringlengths 11 56k | repo_name stringlengths 5 60 | features list |
|---|---|---|
def setUp(self):
"""
Initialize account and pages.
"""
super(AccountSettingsPageTest, self).setUp()
self.username, self.user_id = self.log_in_as_unique_user()
self.visit_account_settings_page() | analyseuc3m/ANALYSE-v1 | [
10,
5,
10,
1,
1460987160
] |
def test_all_sections_and_fields_are_present(self):
"""
Scenario: Verify that all sections and fields are present on the page.
"""
expected_sections_structure = [
{
'title': 'Basic Account Information (required)',
'fields': [
'Username',
'Full Name',
'Email Address',
'Password',
'Language',
'Country or Region'
]
},
{
'title': 'Additional Information (optional)',
'fields': [
'Education Completed',
'Gender',
'Year of Birth',
'Preferred Language',
]
},
{
'title': 'Connected Accounts',
'fields': [
'Dummy',
'Facebook',
'Google',
]
}
]
self.assertEqual(self.account_settings_page.sections_structure(), expected_sections_structure) | analyseuc3m/ANALYSE-v1 | [
10,
5,
10,
1,
1460987160
] |
def _test_text_field(
self, field_id, title, initial_value, new_invalid_value, new_valid_values, success_message=SUCCESS_MESSAGE,
assert_after_reload=True | analyseuc3m/ANALYSE-v1 | [
10,
5,
10,
1,
1460987160
] |
def _test_dropdown_field(
self, field_id, title, initial_value, new_values, success_message=SUCCESS_MESSAGE, reloads_on_save=False | analyseuc3m/ANALYSE-v1 | [
10,
5,
10,
1,
1460987160
] |
def _test_link_field(self, field_id, title, link_title, success_message):
"""
Test behaviour a link field.
"""
self.assertEqual(self.account_settings_page.title_for_field(field_id), title)
self.assertEqual(self.account_settings_page.link_title_for_link_field(field_id), link_title)
self.account_settings_page.click_on_link_in_link_field(field_id)
self.account_settings_page.wait_for_message(field_id, success_message) | analyseuc3m/ANALYSE-v1 | [
10,
5,
10,
1,
1460987160
] |
def test_full_name_field(self):
"""
Test behaviour of "Full Name" field.
"""
self._test_text_field(
u'name',
u'Full Name',
self.username,
u'@',
[u'another name', self.username],
)
actual_events = self.wait_for_events(event_filter=self.settings_changed_event_filter, number_of_matches=2)
self.assert_events_match(
[
self.expected_settings_changed_event('name', self.username, 'another name'),
self.expected_settings_changed_event('name', 'another name', self.username),
],
actual_events
) | analyseuc3m/ANALYSE-v1 | [
10,
5,
10,
1,
1460987160
] |
def test_password_field(self):
"""
Test behaviour of "Password" field.
"""
self._test_link_field(
u'password',
u'Password',
u'Reset Password',
success_message='Click the link in the message to reset your password.',
)
event_filter = self.expected_settings_change_initiated_event('password', None, None)
self.wait_for_events(event_filter=event_filter, number_of_matches=1)
# Like email, since the user has not confirmed their password change,
# the field has not yet changed, so no events will have been emitted.
self.assert_no_setting_changed_event() | analyseuc3m/ANALYSE-v1 | [
10,
5,
10,
1,
1460987160
] |
def test_language_field(self):
"""
Test behaviour of "Language" field.
"""
self._test_dropdown_field(
u'pref-lang',
u'Language',
u'English',
[u'Dummy Language (Esperanto)', u'English'],
reloads_on_save=True,
) | analyseuc3m/ANALYSE-v1 | [
10,
5,
10,
1,
1460987160
] |
def test_gender_field(self):
"""
Test behaviour of "Gender" field.
"""
self._test_dropdown_field(
u'gender',
u'Gender',
u'',
[u'Female', u''],
)
actual_events = self.wait_for_events(event_filter=self.settings_changed_event_filter, number_of_matches=2)
self.assert_events_match(
[
self.expected_settings_changed_event('gender', None, 'f'),
self.expected_settings_changed_event('gender', 'f', None),
],
actual_events
) | analyseuc3m/ANALYSE-v1 | [
10,
5,
10,
1,
1460987160
] |
def test_country_field(self):
"""
Test behaviour of "Country or Region" field.
"""
self._test_dropdown_field(
u'country',
u'Country or Region',
u'',
[u'Pakistan', u'Palau'],
) | analyseuc3m/ANALYSE-v1 | [
10,
5,
10,
1,
1460987160
] |
def test_connected_accounts(self):
"""
Test that fields for third party auth providers exist.
Currently there is no way to test the whole authentication process
because that would require accounts with the providers.
"""
providers = (
['auth-oa2-facebook', 'Facebook', 'Link'],
['auth-oa2-google-oauth2', 'Google', 'Link'],
)
for field_id, title, link_title in providers:
self.assertEqual(self.account_settings_page.title_for_field(field_id), title)
self.assertEqual(self.account_settings_page.link_title_for_link_field(field_id), link_title) | analyseuc3m/ANALYSE-v1 | [
10,
5,
10,
1,
1460987160
] |
def sync():
try:
_keep_alive_for = int(NS.config.data.get("sync_interval", 10)) + 250
disks = get_node_disks()
disk_map = {}
for disk in disks:
# Creating dict with disk name as key and disk_id as value
# It will help populate block device disk_id attribute
_map = dict(disk_id=disks[disk]['disk_id'], ssd=False)
disk_map[disks[disk]['disk_name']] = _map
block_devices = get_node_block_devices(disk_map)
for disk in disks:
if disk_map[disks[disk]['disk_name']]:
disks[disk]['ssd'] = disk_map[disks[disk][
'disk_name']]['ssd']
if "virtio" in disks[disk]["driver"]:
# Virtual disk
NS.tendrl.objects.VirtualDisk(**disks[disk]).save(
ttl=_keep_alive_for
)
else:
# physical disk
NS.tendrl.objects.Disk(**disks[disk]).save(ttl=_keep_alive_for)
for device in block_devices['all']:
NS.tendrl.objects.BlockDevice(**device).save(ttl=_keep_alive_for)
for device_id in block_devices['used']:
etcd_utils.write(
"nodes/%s/LocalStorage/BlockDevices/used/%s" %
(NS.node_context.node_id,
device_id.replace("/", "_").replace("_", "", 1)),
device_id, ttl=_keep_alive_for
)
for device_id in block_devices['free']:
etcd_utils.write(
"nodes/%s/LocalStorage/BlockDevices/free/%s" %
(NS.node_context.node_id,
device_id.replace("/", "_").replace("_", "", 1)),
device_id, ttl=_keep_alive_for
)
raw_reference = get_raw_reference()
etcd_utils.write(
"nodes/%s/LocalStorage/DiskRawReference" %
NS.node_context.node_id,
raw_reference,
ttl=_keep_alive_for,
)
except(Exception, KeyError) as ex:
_msg = "node_sync disks sync failed: " + ex.message
Event(
ExceptionMessage(
priority="error",
publisher=NS.publisher_id,
payload={"message": _msg,
"exception": ex}
)
) | Tendrl/node_agent | [
4,
14,
4,
20,
1473351508
] |
def get_disk_details():
disks = {}
disks_map = {}
cmd = cmd_utils.Command('hwinfo --disk')
out, err, rc = cmd.run()
if not err:
out = unicodedata.normalize('NFKD', out).encode('utf8', 'ignore') \
if isinstance(out, unicode) \
else unicode(out, errors="ignore").encode('utf8')
for all_disks in out.split('\n\n'):
devlist = {"disk_id": "",
"hardware_id": "",
"parent_id": "",
"disk_name": "",
"sysfs_id": "",
"sysfs_busid": "",
"sysfs_device_link": "",
"hardware_class": "",
"model": "",
"vendor": "",
"device": "",
"rmversion": "",
"serial_no": "",
"driver_modules": "",
"driver": "",
"device_files": "",
"device_number": "",
"bios_id": "",
"geo_bios_edd": "",
"geo_logical": "",
"size": "",
"size_bios_edd": "",
"geo_bios_legacy": "",
"config_status": "",
"partitions": {}
}
for disk in all_disks.split('\n'):
key = disk.split(':')[0]
if key.strip() == "Unique ID":
devlist["hardware_id"] = \
disk.split(':')[1].lstrip()
elif key.strip() == "Parent ID":
devlist["parent_id"] = \
disk.split(':')[1].lstrip()
elif key.strip() == "SysFS ID":
devlist["sysfs_id"] = \
disk.split(':')[1].lstrip()
elif key.strip() == "SysFS BusID":
devlist["sysfs_busid"] = \
disk.split(':')[1].lstrip()
elif key.strip() == "SysFS Device Link":
devlist["sysfs_device_link"] = \
disk.split(':')[1].lstrip()
elif key.strip() == "Hardware Class":
devlist["hardware_class"] = \
disk.split(':')[1].lstrip()
elif key.strip() == "Model":
devlist["model"] = \
disk.split(':')[1].lstrip().replace('"', "")
elif key.strip() == "Vendor":
devlist["vendor"] = \
disk.split(':')[1].replace(" ", "").replace('"', "")
elif key.strip() == "Device":
devlist["device"] = \
disk.split(':')[1].replace(" ", "").replace('"', "")
elif key.strip() == "Revision":
devlist["rmversion"] = \
disk.split(':')[1].lstrip().replace('"', "")
elif key.strip() == "Serial ID":
devlist["serial_no"] = \
disk.split(':')[1].replace(" ", "").replace('"', "")
elif key.strip() == "Driver":
devlist["driver"] = \
disk.split(':')[1].lstrip().replace('"', "")
elif key.strip() == "Driver Modules":
devlist["driver_modules"] = \
disk.split(':')[1].lstrip().replace('"', "")
elif key.strip() == "Device File":
_name = disk.split(':')[1].lstrip()
devlist["disk_name"] = \
"".join(_name.split(" ")[0])
elif key.strip() == "Device Files":
devlist["device_files"] = \
disk.split(':')[1].lstrip()
elif key.strip() == "Device Number":
devlist["device_number"] = \
disk.split(':')[1].lstrip()
elif key.strip() == "BIOS id":
devlist["bios_id"] = \
disk.split(':')[1].lstrip()
elif key.strip() == "Geometry (Logical)":
devlist["geo_logical"] = \
disk.split(':')[1].lstrip()
elif key.strip() == "Capacity":
devlist["size"] = \
disk.split('(')[1].split()[0]
elif key.strip() == "Geometry (BIOS EDD)":
devlist["geo_bios_edd"] = \
disk.split(':')[1].lstrip()
elif key.strip() == "Size (BIOS EDD)":
devlist["size_bios_edd"] = \
disk.split(':')[1].lstrip()
elif key.strip() == "Geometry (BIOS Legacy)":
devlist["geo_bios_legacy"] = \
disk.split(':')[1].lstrip()
elif key.strip() == "Config Status":
devlist["config_status"] = \
disk.split(':')[1].lstrip()
if ("virtio" in devlist["driver"] and
"by-id/virtio" in devlist['device_files']):
# split from:
# /dev/vdc, /dev/disk/by-id/virtio-0200f64e-5892-40ee-8,
# /dev/disk/by-path/virtio-pci-0000:00:08.0
for entry in devlist['device_files'].split(','):
if "by-id/virtio" in entry:
devlist['disk_id'] = entry.split('/')[-1]
break
elif "VMware" in devlist["vendor"]:
devlist["disk_id"] = \
"{vendor}_{device}_{parent_id}_{hardware_id}".format(**devlist)
elif (devlist["vendor"] != "" and
devlist["device"] != "" and
devlist["serial_no"] != ""):
devlist["disk_id"] = (devlist["vendor"] + "_" +
devlist["device"] + "_" + devlist[
"serial_no"])
else:
devlist['disk_id'] = devlist['disk_name']
if devlist["disk_id"] in disks.keys():
# Multipath is like multiple I/O paths between
# server nodes and storage arrays into a single device
# If single device is connected with more than one path
# then hwinfo and lsblk will give same device details with
# different device names. To avoid this duplicate entry,
# If multiple devices exists with same disk_id then
# device_name which is lower in alphabetical order is stored.
# It will avoid redundacy of disks and next sync it will
# make sure same device detail is populated
if devlist["disk_name"] < disks[
devlist['disk_id']]['disk_name']:
disks[devlist["disk_id"]] = devlist
disks_map[devlist['hardware_id']] = devlist["disk_id"]
else:
disks[devlist["disk_id"]] = devlist
disks_map[devlist['hardware_id']] = devlist["disk_id"]
return disks, disks_map, err | Tendrl/node_agent | [
4,
14,
4,
20,
1473351508
] |
def get_raw_reference():
base_path = '/dev/disk/'
paths = os.listdir(base_path)
raw_reference = {}
for path in paths:
raw_reference[path] = []
full_path = base_path + path
cmd = cmd_utils.Command("ls -l %s" % full_path)
out, err, rc = cmd.run()
if not err:
out = unicodedata.normalize('NFKD', out).encode('utf8', 'ignore') \
if isinstance(out, unicode) \
else unicode(out, errors="ignore").encode('utf8')
count = 0
for line in out.split('\n'):
if count == 0:
# to skip first line
count = count + 1
continue
line = line.replace(" ", " ")
raw_reference[path].append(line.split(' ', 8)[-1])
else:
logger.log(
"debug",
NS.publisher_id,
{"message": err}
)
return raw_reference | Tendrl/node_agent | [
4,
14,
4,
20,
1473351508
] |
def authorized_to_manage_request(_, request, current_user, pushmaster=False):
if pushmaster or \
request['user'] == current_user or \
(request['watchers'] and current_user in request['watchers'].split(',')):
return True
return False | YelpArchive/pushmanager | [
37,
23,
37,
12,
1359009995
] |
def compare_requests(request1, request2):
tags1_list = request1['tags'].split(',')
tags2_list = request2['tags'].split(',')
for tag in tags_order:
tag_in_tags1 = tag in tags1_list
tag_in_tags2 = tag in tags2_list
if tag_in_tags1 == tag_in_tags2:
continue
elif tag_in_tags1:
return -1
else:
return 1
return cmp(request1['user'], request2['user']) | YelpArchive/pushmanager | [
37,
23,
37,
12,
1359009995
] |
def __init__(self):
self.instances_by_id = {}
self.ids_by_uuid = {}
self.max_id = 0 | josephsuh/extra-specs | [
1,
1,
1,
1,
1337971331
] |
def return_server_by_uuid(self, context, uuid):
if uuid not in self.ids_by_uuid:
self._add_server(uuid=uuid)
return dict(self.instances_by_id[self.ids_by_uuid[uuid]]) | josephsuh/extra-specs | [
1,
1,
1,
1,
1337971331
] |
def stub_instance(id, user_id='fake', project_id='fake', host=None,
vm_state=None, task_state=None,
reservation_id="", uuid=FAKE_UUID, image_ref="10",
flavor_id="1", name=None, key_name='',
access_ipv4=None, access_ipv6=None, progress=0):
if host is not None:
host = str(host)
if key_name:
key_data = 'FAKE'
else:
key_data = ''
# ReservationID isn't sent back, hack it in there.
server_name = name or "server%s" % id
if reservation_id != "":
server_name = "reservation_%s" % (reservation_id, )
instance = {
"id": int(id),
"created_at": datetime.datetime(2010, 10, 10, 12, 0, 0),
"updated_at": datetime.datetime(2010, 11, 11, 11, 0, 0),
"admin_pass": "",
"user_id": user_id,
"project_id": project_id,
"image_ref": image_ref,
"kernel_id": "",
"ramdisk_id": "",
"launch_index": 0,
"key_name": key_name,
"key_data": key_data,
"vm_state": vm_state or vm_states.BUILDING,
"task_state": task_state,
"memory_mb": 0,
"vcpus": 0,
"root_gb": 0,
"hostname": "",
"host": host,
"instance_type": {},
"user_data": "",
"reservation_id": reservation_id,
"mac_address": "",
"scheduled_at": utils.utcnow(),
"launched_at": utils.utcnow(),
"terminated_at": utils.utcnow(),
"availability_zone": "",
"display_name": server_name,
"display_description": "",
"locked": False,
"metadata": [],
"access_ip_v4": access_ipv4,
"access_ip_v6": access_ipv6,
"uuid": uuid,
"progress": progress}
return instance | josephsuh/extra-specs | [
1,
1,
1,
1,
1337971331
] |
def setUp(self):
super(ConsolesControllerTest, self).setUp()
self.flags(verbose=True)
self.instance_db = FakeInstanceDB()
self.stubs.Set(db, 'instance_get',
self.instance_db.return_server_by_id)
self.stubs.Set(db, 'instance_get_by_uuid',
self.instance_db.return_server_by_uuid)
self.uuid = str(utils.gen_uuid())
self.url = '/v2/fake/servers/%s/consoles' % self.uuid
self.controller = consoles.Controller() | josephsuh/extra-specs | [
1,
1,
1,
1,
1337971331
] |
def fake_create_console(cons_self, context, instance_id):
self.assertEqual(instance_id, self.uuid)
return {} | josephsuh/extra-specs | [
1,
1,
1,
1,
1337971331
] |
def test_show_console(self):
def fake_get_console(cons_self, context, instance_id, console_id):
self.assertEqual(instance_id, self.uuid)
self.assertEqual(console_id, 20)
pool = dict(console_type='fake_type',
public_hostname='fake_hostname')
return dict(id=console_id, password='fake_password',
port='fake_port', pool=pool, instance_name='inst-0001')
expected = {'console': {'id': 20,
'port': 'fake_port',
'host': 'fake_hostname',
'password': 'fake_password',
'instance_name': 'inst-0001',
'console_type': 'fake_type'}}
self.stubs.Set(console.api.API, 'get_console', fake_get_console)
req = fakes.HTTPRequest.blank(self.url + '/20')
res_dict = self.controller.show(req, self.uuid, '20')
self.assertDictMatch(res_dict, expected) | josephsuh/extra-specs | [
1,
1,
1,
1,
1337971331
] |
def fake_get_console(cons_self, context, instance_id, console_id):
raise exception.ConsoleNotFound(console_id=console_id) | josephsuh/extra-specs | [
1,
1,
1,
1,
1337971331
] |
def test_show_console_unknown_instance(self):
def fake_get_console(cons_self, context, instance_id, console_id):
raise exception.InstanceNotFound(instance_id=instance_id)
self.stubs.Set(console.api.API, 'get_console', fake_get_console)
req = fakes.HTTPRequest.blank(self.url + '/20')
self.assertRaises(webob.exc.HTTPNotFound, self.controller.show,
req, self.uuid, '20') | josephsuh/extra-specs | [
1,
1,
1,
1,
1337971331
] |
def fake_get_consoles(cons_self, context, instance_id):
self.assertEqual(instance_id, self.uuid)
pool1 = dict(console_type='fake_type',
public_hostname='fake_hostname')
cons1 = dict(id=10, password='fake_password',
port='fake_port', pool=pool1)
pool2 = dict(console_type='fake_type2',
public_hostname='fake_hostname2')
cons2 = dict(id=11, password='fake_password2',
port='fake_port2', pool=pool2)
return [cons1, cons2] | josephsuh/extra-specs | [
1,
1,
1,
1,
1337971331
] |
def test_delete_console(self):
def fake_get_console(cons_self, context, instance_id, console_id):
self.assertEqual(instance_id, self.uuid)
self.assertEqual(console_id, 20)
pool = dict(console_type='fake_type',
public_hostname='fake_hostname')
return dict(id=console_id, password='fake_password',
port='fake_port', pool=pool)
def fake_delete_console(cons_self, context, instance_id, console_id):
self.assertEqual(instance_id, self.uuid)
self.assertEqual(console_id, 20)
self.stubs.Set(console.api.API, 'get_console', fake_get_console)
self.stubs.Set(console.api.API, 'delete_console', fake_delete_console)
req = fakes.HTTPRequest.blank(self.url + '/20')
self.controller.delete(req, self.uuid, '20') | josephsuh/extra-specs | [
1,
1,
1,
1,
1337971331
] |
def fake_delete_console(cons_self, context, instance_id, console_id):
raise exception.ConsoleNotFound(console_id=console_id) | josephsuh/extra-specs | [
1,
1,
1,
1,
1337971331
] |
def test_delete_console_unknown_instance(self):
def fake_delete_console(cons_self, context, instance_id, console_id):
raise exception.InstanceNotFound(instance_id=instance_id)
self.stubs.Set(console.api.API, 'delete_console', fake_delete_console)
req = fakes.HTTPRequest.blank(self.url + '/20')
self.assertRaises(webob.exc.HTTPNotFound, self.controller.delete,
req, self.uuid, '20') | josephsuh/extra-specs | [
1,
1,
1,
1,
1337971331
] |
def test_show(self):
fixture = {'console': {'id': 20,
'password': 'fake_password',
'port': 'fake_port',
'host': 'fake_hostname',
'console_type': 'fake_type'}}
output = consoles.ConsoleTemplate().serialize(fixture)
res_tree = etree.XML(output)
self.assertEqual(res_tree.tag, 'console')
self.assertEqual(res_tree.xpath('id')[0].text, '20')
self.assertEqual(res_tree.xpath('port')[0].text, 'fake_port')
self.assertEqual(res_tree.xpath('host')[0].text, 'fake_hostname')
self.assertEqual(res_tree.xpath('password')[0].text, 'fake_password')
self.assertEqual(res_tree.xpath('console_type')[0].text, 'fake_type') | josephsuh/extra-specs | [
1,
1,
1,
1,
1337971331
] |
def __init__(self, context, core):
self._context = context
self._core = core
self._run_token = -1
self._reset_cache() | pyocd/pyOCD | [
883,
424,
883,
228,
1382710205
] |
def _dump_metrics(self):
if self._metrics.total > 0:
LOG.debug("%d reads [%d%% hits, %d regs]", self._metrics.total, self._metrics.percent_hit, self._metrics.hits)
else:
LOG.debug("no accesses") | pyocd/pyOCD | [
883,
424,
883,
228,
1382710205
] |
def _convert_and_check_registers(self, reg_list):
# convert to index only
reg_list = [index_for_reg(reg) for reg in reg_list]
self._core.check_reg_list(reg_list)
return reg_list | pyocd/pyOCD | [
883,
424,
883,
228,
1382710205
] |
def write_core_registers_raw(self, reg_list, data_list):
# Check and invalidate the cache. If the core is still running, just pass the writes
# to our context.
if self._check_cache():
self._context.write_core_registers_raw(reg_list, data_list)
return
reg_list = self._convert_and_check_registers(reg_list)
self._metrics.writes += len(reg_list)
writing_cfbp = any(r for r in reg_list if r in self.CFBP_REGS)
writing_xpsr = any(r for r in reg_list if r in self.XPSR_REGS)
# Update cached register values.
for i, r in enumerate(reg_list):
v = data_list[i]
self._cache[r] = v
# Just remove all cached CFBP and XPSR based register values.
if writing_cfbp:
for r in self.CFBP_REGS:
self._cache.pop(r, None)
if writing_xpsr:
for r in self.XPSR_REGS:
self._cache.pop(r, None)
# Write new register values to target.
try:
self._context.write_core_registers_raw(reg_list, data_list)
except exceptions.CoreRegisterAccessError:
# Invalidate cache on register write error just to be safe.
self._reset_cache()
raise | pyocd/pyOCD | [
883,
424,
883,
228,
1382710205
] |
def _get_model(shape, axis, keepdims, input_zp, input_sc, output_zp, output_sc, dtype):
a = relay.var("a", shape=shape, dtype=dtype)
casted = relay.op.cast(a, "int32")
mean = relay.mean(casted, axis, keepdims)
model = relay.qnn.op.requantize(
mean,
input_scale=relay.const(input_sc, "float32"),
input_zero_point=relay.const(input_zp, "int32"),
output_scale=relay.const(output_sc, "float32"),
output_zero_point=relay.const(output_zp, "int32"),
out_dtype=dtype,
)
return model | dmlc/tvm | [
9142,
2938,
9142,
595,
1476310828
] |
def difftree(ui, repo, node1=None, node2=None, *files, **opts):
"""diff trees from two commits"""
def __difftree(repo, node1, node2, files=[]):
assert node2 is not None
mmap = repo[node1].manifest()
mmap2 = repo[node2].manifest()
m = cmdutil.match(repo, files)
modified, added, removed = repo.status(node1, node2, m)[:3]
empty = short(nullid)
for f in modified:
# TODO get file permissions
ui.write(":100664 100664 %s %s M\t%s\t%s\n" %
(short(mmap[f]), short(mmap2[f]), f, f))
for f in added:
ui.write(":000000 100664 %s %s N\t%s\t%s\n" %
(empty, short(mmap2[f]), f, f))
for f in removed:
ui.write(":100664 000000 %s %s D\t%s\t%s\n" %
(short(mmap[f]), empty, f, f))
##
while True:
if opts['stdin']:
try:
line = raw_input().split(' ')
node1 = line[0]
if len(line) > 1:
node2 = line[1]
else:
node2 = None
except EOFError:
break
node1 = repo.lookup(node1)
if node2:
node2 = repo.lookup(node2)
else:
node2 = node1
node1 = repo.changelog.parents(node1)[0]
if opts['patch']:
if opts['pretty']:
catcommit(ui, repo, node2, "")
m = cmdutil.match(repo, files)
chunks = patch.diff(repo, node1, node2, match=m,
opts=patch.diffopts(ui, {'git': True}))
for chunk in chunks:
ui.write(chunk)
else:
__difftree(repo, node1, node2, files=files)
if not opts['stdin']:
break | joewalnes/idea-community | [
33,
38,
33,
5,
1296022956
] |
def base(ui, repo, node1, node2):
"""output common ancestor information"""
node1 = repo.lookup(node1)
node2 = repo.lookup(node2)
n = repo.changelog.ancestor(node1, node2)
ui.write(short(n) + "\n") | joewalnes/idea-community | [
33,
38,
33,
5,
1296022956
] |
def revtree(ui, args, repo, full="tree", maxnr=0, parents=False):
def chlogwalk():
count = len(repo)
i = count
l = [0] * 100
chunk = 100
while True:
if chunk > i:
chunk = i
i = 0
else:
i -= chunk
for x in xrange(chunk):
if i + x >= count:
l[chunk - x:] = [0] * (chunk - x)
break
if full != None:
l[x] = repo[i + x]
l[x].changeset() # force reading
else:
l[x] = 1
for x in xrange(chunk - 1, -1, -1):
if l[x] != 0:
yield (i + x, full != None and l[x] or None)
if i == 0:
break
# calculate and return the reachability bitmask for sha
def is_reachable(ar, reachable, sha):
if len(ar) == 0:
return 1
mask = 0
for i in xrange(len(ar)):
if sha in reachable[i]:
mask |= 1 << i
return mask
reachable = []
stop_sha1 = []
want_sha1 = []
count = 0
# figure out which commits they are asking for and which ones they
# want us to stop on
for i, arg in enumerate(args):
if arg.startswith('^'):
s = repo.lookup(arg[1:])
stop_sha1.append(s)
want_sha1.append(s)
elif arg != 'HEAD':
want_sha1.append(repo.lookup(arg))
# calculate the graph for the supplied commits
for i, n in enumerate(want_sha1):
reachable.append(set())
visit = [n]
reachable[i].add(n)
while visit:
n = visit.pop(0)
if n in stop_sha1:
continue
for p in repo.changelog.parents(n):
if p not in reachable[i]:
reachable[i].add(p)
visit.append(p)
if p in stop_sha1:
continue
# walk the repository looking for commits that are in our
# reachability graph
for i, ctx in chlogwalk():
n = repo.changelog.node(i)
mask = is_reachable(want_sha1, reachable, n)
if mask:
parentstr = ""
if parents:
pp = repo.changelog.parents(n)
if pp[0] != nullid:
parentstr += " " + short(pp[0])
if pp[1] != nullid:
parentstr += " " + short(pp[1])
if not full:
ui.write("%s%s\n" % (short(n), parentstr))
elif full == "commit":
ui.write("%s%s\n" % (short(n), parentstr))
catcommit(ui, repo, n, ' ', ctx)
else:
(p1, p2) = repo.changelog.parents(n)
(h, h1, h2) = map(short, (n, p1, p2))
(i1, i2) = map(repo.changelog.rev, (p1, p2))
date = ctx.date()[0]
ui.write("%s %s:%s" % (date, h, mask))
mask = is_reachable(want_sha1, reachable, p1)
if i1 != nullrev and mask > 0:
ui.write("%s:%s " % (h1, mask)),
mask = is_reachable(want_sha1, reachable, p2)
if i2 != nullrev and mask > 0:
ui.write("%s:%s " % (h2, mask))
ui.write("\n")
if maxnr and count >= maxnr:
break
count += 1 | joewalnes/idea-community | [
33,
38,
33,
5,
1296022956
] |
def revstr(rev):
if rev == 'HEAD':
rev = 'tip'
return revlog.hex(repo.lookup(rev)) | joewalnes/idea-community | [
33,
38,
33,
5,
1296022956
] |
def revlist(ui, repo, *revs, **opts):
"""print revisions"""
if opts['header']:
full = "commit"
else:
full = None
copy = [x for x in revs]
revtree(ui, copy, repo, full, opts['max_count'], opts['parents']) | joewalnes/idea-community | [
33,
38,
33,
5,
1296022956
] |
def writeopt(name, value):
ui.write('k=%s\nv=%s\n' % (name, value)) | joewalnes/idea-community | [
33,
38,
33,
5,
1296022956
] |
def view(ui, repo, *etc, **opts):
"start interactive history viewer"
os.chdir(repo.root)
optstr = ' '.join(['--%s %s' % (k, v) for k, v in opts.iteritems() if v])
cmd = ui.config("hgk", "path", "hgk") + " %s %s" % (optstr, " ".join(etc))
ui.debug("running %s\n" % cmd)
util.system(cmd) | joewalnes/idea-community | [
33,
38,
33,
5,
1296022956
] |
def _deweird(s):
"""
Sometimes numpy loadtxt returns strings like "b'stuff'"
This converts them to "stuff"
@ In, s, str, possibly weird string
@ Out, _deweird, str, possibly less weird string
"""
if type(s) == str and s.startswith("b'") and s.endswith("'"):
return s[2:-1]
else:
return s | idaholab/raven | [
168,
104,
168,
215,
1490297367
] |
def __init__(self, outFiles):
"""
Initialize the class
@ In, outFiles, list, list of output files of SAPHIRE
@ Out, None
"""
self.headerNames = [] # list of variable names in SAPHIRE output files
self.outData = [] # list of variable values in SAPHIRE output files
for outFile in outFiles:
outFileName, outFileType = outFile[0], outFile[1]
if outFileType == 'uncertainty':
headers, data = self.getUncertainty(outFileName)
self.headerNames.extend(headers)
self.outData.extend(data)
elif outFileType == 'importance':
headers, data = self.getImportance(outFileName)
self.headerNames.extend(headers)
self.outData.extend(data)
elif outFileType == 'quantiles':
print("File:",outFileName, "with type", outFileType, "is not implemented yet! Skipping" )
pass
else:
raise IOError('The output file', outFileName, 'with type', outFileType, 'is not supported yet!') | idaholab/raven | [
168,
104,
168,
215,
1490297367
] |
def getImportance(self, outName):
"""
Method to extract the importance information of Fault Tree from SAPHIRE output files
@ In, outName, string, the name of output file
@ Out, headerNames, list, list of output variable names
@ Out, outData, list, list of output variable values
"""
headerNames = []
outData = []
outFile = os.path.abspath(os.path.expanduser(outName))
data = np.loadtxt(outFile, dtype=object, delimiter=',', skiprows=2)
headers = data[0]
for i in range(1, len(data)):
for j in range(1, len(headers)):
name = _deweird(data[i,0]).strip().replace(" ", "~")
header = _deweird(headers[j]).strip().replace(" ", "~")
headerNames.append(name + '_' + header)
outData.append(float(_deweird(data[i,j])))
return headerNames, outData | idaholab/raven | [
168,
104,
168,
215,
1490297367
] |
def setUp(self):
self.assertTrue(th.SetupTestDB())
self.db_path = th.TEST_DB_PATH
self.dba = DBAccess(db_path=self.db_path)
self.conn = sqlite3.connect(self.db_path)
self.cursor = self.conn.cursor() | ScienceStacks/JViz | [
30,
5,
30,
7,
1435851901
] |
def testmaketable(self):
CLIENT_URL = '/heatmap/maketable/'
TABLE_LIST = ['data_rev', 'data']
response = self.client.get(CLIENT_URL)
self.assertEqual(response.status_code, 200)
form_data = {'numrows': 10, 'lastrow': 1}
form = TableForm(data=form_data)
post_dict = {'display_form': form,
'tablename': TABLE_LIST[0],
'table_list': TABLE_LIST}
response = self.client.post(CLIENT_URL, post_dict)
self.assertEqual(response.status_code, 200) | ScienceStacks/JViz | [
30,
5,
30,
7,
1435851901
] |
def testQuery(self):
CLIENT_URL = '/heatmap/query/'
TABLE_LIST = ['data_rev', 'data']
TABLE_NAME = "testQuery"
response = self.client.get(CLIENT_URL)
self.assertEqual(response.status_code, 200)
# Test the post
th.CreateTableWithData(TABLE_NAME, self.conn)
query_string = "SELECT * from %s" % TABLE_NAME
form = QueryForm(data={'query_string': query_string})
post_dict = {'form': form,
'table_list': TABLE_LIST}
response = self.client.post(CLIENT_URL, post_dict)
self.assertEqual(response.status_code, 200) | ScienceStacks/JViz | [
30,
5,
30,
7,
1435851901
] |
def __init__(self, auto_describe=False):
self._collector_to_names = {}
self._names_to_collectors = {}
self._auto_describe = auto_describe
self._lock = Lock() | cloudera/hue | [
804,
271,
804,
38,
1277149611
] |
def unregister(self, collector):
"""Remove a collector from the registry."""
with self._lock:
for name in self._collector_to_names[collector]:
del self._names_to_collectors[name]
del self._collector_to_names[collector] | cloudera/hue | [
804,
271,
804,
38,
1277149611
] |
def collect(self):
"""Yields metrics from the collectors in the registry."""
collectors = None
with self._lock:
collectors = copy.copy(self._collector_to_names)
for collector in collectors:
for metric in collector.collect():
yield metric | cloudera/hue | [
804,
271,
804,
38,
1277149611
] |
def collect(self):
return metrics | cloudera/hue | [
804,
271,
804,
38,
1277149611
] |
def get_sample_value(self, name, labels=None):
"""Returns the sample value, or None if not found.
This is inefficient, and intended only for use in unittests.
"""
if labels is None:
labels = {}
for metric in self.collect():
for s in metric.samples:
if s.name == name and s.labels == labels:
return s.value
return None | cloudera/hue | [
804,
271,
804,
38,
1277149611
] |
def testDerCodec(self):
layers = { }
layers.update(rfc5652.cmsContentTypesMap)
getNextLayer = {
rfc5652.id_ct_contentInfo: lambda x: x['contentType'],
rfc5652.id_signedData: lambda x: x['encapContentInfo']['eContentType'],
rfc6402.id_cct_PKIData: lambda x: None
}
getNextSubstrate = {
rfc5652.id_ct_contentInfo: lambda x: x['content'],
rfc5652.id_signedData: lambda x: x['encapContentInfo']['eContent'],
rfc6402.id_cct_PKIData: lambda x: None
}
substrate = pem.readBase64fromText(self.pem_text)
next_layer = rfc5652.id_ct_contentInfo
while next_layer:
asn1Object, rest = der_decoder(substrate, asn1Spec=layers[next_layer])
self.assertFalse(rest)
self.assertTrue(asn1Object.prettyPrint())
self.assertEqual(substrate, der_encoder(asn1Object))
substrate = getNextSubstrate[next_layer](asn1Object)
next_layer = getNextLayer[next_layer](asn1Object) | etingof/pyasn1-modules | [
38,
39,
38,
8,
1456353005
] |
def interface(name, file=None):
return Spec({name: []}) | serge-sans-paille/pythran | [
1865,
184,
1865,
122,
1338278534
] |
def extract_runas(name, filepath):
return ['#runas {}()'.format(name)] | serge-sans-paille/pythran | [
1865,
184,
1865,
122,
1338278534
] |
def interface(name, file=None):
return Spec({name: []}) | serge-sans-paille/pythran | [
1865,
184,
1865,
122,
1338278534
] |
def extract_runas(name, filepath):
return ['#runas {}()'.format(name)] | serge-sans-paille/pythran | [
1865,
184,
1865,
122,
1338278534
] |
def y2k():
return datetime(2000, 1, 1).replace(tzinfo=utc) | gregmuellegger/django-autofixture | [
458,
114,
458,
30,
1282675169
] |
def __init__(self, address=None, value=None, **kwargs):
""" Initializes a new instance
:param address: The variable address to write
:param value: The value to write at address
"""
ModbusRequest.__init__(self, **kwargs)
self.address = address
self.value = bool(value) | uzumaxy/pymodbus3 | [
34,
11,
34,
3,
1405577525
] |
def decode(self, data):
""" Decodes a write coil request
:param data: The packet data to decode
"""
self.address, value = struct.unpack('>HH', data)
self.value = (value == ModbusStatus.On) | uzumaxy/pymodbus3 | [
34,
11,
34,
3,
1405577525
] |
def __str__(self):
""" Returns a string representation of the instance
:return: A string representation of the instance
"""
return 'WriteCoilRequest({0}, {1}) => '.format(
self.address, self.value
) | uzumaxy/pymodbus3 | [
34,
11,
34,
3,
1405577525
] |
def __init__(self, address=None, value=None, **kwargs):
""" Initializes a new instance
:param address: The variable address written to
:param value: The value written at address
"""
ModbusResponse.__init__(self, **kwargs)
self.address = address
self.value = value | uzumaxy/pymodbus3 | [
34,
11,
34,
3,
1405577525
] |
def decode(self, data):
""" Decodes a write coil response
:param data: The packet data to decode
"""
self.address, value = struct.unpack('>HH', data)
self.value = (value == ModbusStatus.On) | uzumaxy/pymodbus3 | [
34,
11,
34,
3,
1405577525
] |
def __init__(self, address=None, values=None, **kwargs):
""" Initializes a new instance
:param address: The starting request address
:param values: The values to write
"""
ModbusRequest.__init__(self, **kwargs)
self.address = address
if not values:
values = []
elif not isinstance(values, Iterable):
values = [values]
self.values = values
self.byte_count = (len(self.values) + 7) // 8 | uzumaxy/pymodbus3 | [
34,
11,
34,
3,
1405577525
] |
def decode(self, data):
""" Decodes a write coils request
:param data: The packet data to decode
"""
self.address, count, self.byte_count = struct.unpack('>HHB', data[0:5])
values = unpack_bitstring(data[5:])
self.values = values[:count] | uzumaxy/pymodbus3 | [
34,
11,
34,
3,
1405577525
] |
def __str__(self):
""" Returns a string representation of the instance
:returns: A string representation of the instance
"""
return 'WriteMultipleCoilRequest ({0}) => {1} '.format(
self.address, len(self.values)
) | uzumaxy/pymodbus3 | [
34,
11,
34,
3,
1405577525
] |
def __init__(self, address=None, count=None, **kwargs):
""" Initializes a new instance
:param address: The starting variable address written to
:param count: The number of values written
"""
ModbusResponse.__init__(self, **kwargs)
self.address = address
self.count = count | uzumaxy/pymodbus3 | [
34,
11,
34,
3,
1405577525
] |
def decode(self, data):
""" Decodes a write coils response
:param data: The packet data to decode
"""
self.address, self.count = struct.unpack('>HH', data) | uzumaxy/pymodbus3 | [
34,
11,
34,
3,
1405577525
] |
def wrap_http_connection(http_connection=None):
if not http_connection:
http_connection = requests.Session() if requests else httplib2.Http()
if not is_requests_instance(http_connection):
http_connection = RequestWrapper(http_connection)
return http_connection | tow/sunburnt | [
278,
89,
278,
30,
1248440645
] |
def __init__(self, conn):
self.conn = conn | tow/sunburnt | [
278,
89,
278,
30,
1248440645
] |
def publish_github_release(slug, token, tag_name, body):
github = github3.login(token=token)
owner, repo = slug.split("/")
repo = github.repository(owner, repo)
return repo.create_release(tag_name=tag_name, body=body) | pytest-dev/pytest | [
9887,
2273,
9887,
850,
1434400107
] |
def convert_rst_to_md(text):
return pypandoc.convert_text(
text, "md", format="rst", extra_args=["--wrap=preserve"]
) | pytest-dev/pytest | [
9887,
2273,
9887,
850,
1434400107
] |
def theme_config_init():
"""Initialization of configuration file. Sections: ???."""
global theme_config_file, theme_config_option
theme_config_file = weechat.config_new(THEME_CONFIG_FILE_NAME,
'theme_config_reload_cb', '')
if not theme_config_file:
return | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def theme_config_reload_cb(data, config_file):
"""Reload configuration file."""
return weechat.config_read(config_file) | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def theme_config_write():
"""Write configuration file."""
global theme_config_file
return weechat.config_write(theme_config_file) | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def theme_config_get_dir():
"""Return themes directory, with expanded WeeChat home dir."""
global theme_config_option
return weechat.config_string(
theme_config_option['themes_dir']).replace('%h',
weechat.info_get('weechat_dir', '')) | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def theme_config_get_undo():
"""Return name of undo file (by default "~/.weechat/themes/_undo.theme")."""
return '%s/_undo.theme' % theme_config_get_dir() | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def theme_config_get_cache_filename():
"""Get local cache filename, based on URL."""
global theme_config_option
return '%s/%s' % (theme_config_get_dir(),
os.path.basename(weechat.config_string(theme_config_option['scripts_url']))) | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def __init__(self, filename=None):
self.filename = filename
self.props = {}
self.listprops = []
self.options = {}
self.theme_ok = True
if self.filename:
self.theme_ok = self.load(self.filename)
else:
self.init_weechat()
self.nick_prefixes = self._get_nick_prefixes() | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def _option_is_used(self, option):
global theme_options_include_re, theme_options_exclude_re
for regex in theme_options_exclude_re:
if re.search(regex, option):
return False
for regex in theme_options_include_re:
if re.search(regex, option):
return True
return False | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def _get_attr_color(self, color):
"""Return tuple with attributes and color."""
m = re.match('([*_!]*)(.*)', color)
if m:
return m.group(1), m.group(2)
return '', color | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def _replace_color_alias(self, match):
value = match.group()[2:-1]
if value in self.palette:
value = self.palette[value]
return '${%s}' % value | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def prnt(self, message):
try:
weechat.prnt('', message)
except:
print(message) | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def load(self, filename):
self.options = {}
try:
lines = open(filename, 'rb').readlines()
for line in lines:
line = str(line.strip().decode('utf-8'))
if line.startswith('#'):
m = re.match('^# \\$([A-Za-z]+): (.*)', line)
if m:
self.props[m.group(1)] = m.group(2)
self.listprops.append(m.group(1))
else:
items = line.split('=', 1)
if len(items) == 2:
value = items[1].strip()
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
self.options[items[0].strip()] = value
return True
except:
self.prnt('Error loading theme "%s"' % filename)
return False | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def show(self, header):
"""Display content of theme."""
names = self.options.keys()
names.sort()
self.prnt('')
self.prnt(header)
for name in names:
self.prnt(' %s %s= %s%s' % (name, weechat.color('chat_delimiters'),
weechat.color('chat_value'), self.options[name])) | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def install(self):
try:
numset = 0
numerrors = 0
for name in self.options:
option = weechat.config_get(name)
if option:
if weechat.config_option_set(option, self.options[name], 1) == weechat.WEECHAT_CONFIG_OPTION_SET_ERROR:
self.prnt_error('Error setting option "%s" to value "%s" (running an old WeeChat?)' % (name, self.options[name]))
numerrors += 1
else:
numset += 1
else:
self.prnt('Warning: option not found: "%s" (running an old WeeChat?)' % name)
numerrors += 1
errors = ''
if numerrors > 0:
errors = ', %d error(s)' % numerrors
if self.filename:
self.prnt('Theme "%s" installed (%d options set%s)' % (self.filename, numset, errors))
else:
self.prnt('Theme installed (%d options set%s)' % (numset, errors))
except:
if self.filename:
self.prnt_error('Failed to install theme "%s"' % self.filename)
else:
self.prnt_error('Failed to install theme') | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def __init__(self, filename=None, chat_width=85, chat_height=25, prefix_width=10, nicklist_width=10):
Theme.__init__(self, filename)
self.chat_width = chat_width
self.chat_height = chat_height
self.prefix_width = prefix_width
self.nicklist_width = nicklist_width | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def html_style(self, fg, bg):
"""Return HTML style with WeeChat fg and bg colors."""
weechat_basic_colors = {
'default': 7, 'black': 0, 'darkgray': 8, 'red': 1, 'lightred': 9,
'green': 2, 'lightgreen': 10, 'brown': 3, 'yellow': 11, 'blue': 4,
'lightblue': 12, 'magenta': 5, 'lightmagenta': 13, 'cyan': 6,
'lightcyan': 14, 'gray': 7, 'white': 15 }
delim = max(fg.find(','), fg.find(':'))
if delim > 0:
bg = fg[delim + 1:]
fg = fg[0:delim]
bold = ''
underline = ''
reverse = False
while fg[0] in COLOR_ATTRIBUTES:
if fg[0] == '*':
bold = '; font-weight: bold'
elif fg[0] == '_':
underline = '; text-decoration: underline'
elif fg[0] == '!':
reverse = True
fg = fg[1:]
while bg[0] in COLOR_ATTRIBUTES:
bg = bg[1:]
if fg == 'default':
fg = self.options['fg']
if bg == 'default':
bg = self.options['bg']
if bold and fg in ('black', '0'):
fg = 'darkgray'
reverse = ''
if reverse:
fg2 = bg
bg = fg
fg = fg2
if fg == 'white' and self.whitebg:
fg = 'black'
num_fg = 0
num_bg = 0
if fg in weechat_basic_colors:
num_fg = weechat_basic_colors[fg]
else:
try:
num_fg = int(fg)
except:
self.prnt('Warning: unknown fg color "%s", using "default" instead' % fg)
num_fg = weechat_basic_colors['default']
if bg in weechat_basic_colors:
num_bg = weechat_basic_colors[bg]
else:
try:
num_bg = int(bg)
except:
self.prnt('Warning: unknown bg color "%s", using "default" instead' % bg)
num_bg = weechat_basic_colors['default']
style = 'color: #%s; background-color: #%s%s%s' % (self.html_color(num_fg),
self.html_color(num_bg),
bold, underline)
return style | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def html_nick(self, nicks, index, prefix, usecolor, highlight, maxlen, optfg='fg', optbg='bg'):
"""Print a nick."""
nick = nicks[index]
nickfg = optfg
if usecolor and optfg != 'weechat.color.nicklist_away':
nick_colors = self.options['weechat.color.chat_nick_colors'].split(',')
nickfg = nick_colors[index % len(nick_colors)]
if usecolor and nick == self.html_nick_self:
nickfg = 'weechat.color.chat_nick_self'
if nick[0] in ('@', '%', '+'):
color = self.nick_prefix_color(nick[0]) or optfg
str_prefix = self.html_string(nick[0], 1, color, optbg)
nick = nick[1:]
else:
str_prefix = self.html_string(' ', 1, optfg, optbg)
length = 1 + len(nick)
if not prefix:
str_prefix = ''
maxlen += 1
length -= 1
padding = ''
if length < abs(maxlen):
padding = self.html_string('', abs(maxlen) - length, optfg, optbg)
if highlight:
nickfg = 'weechat.color.chat_highlight'
optbg = 'weechat.color.chat_highlight_bg'
string = str_prefix + self.html_string(nick, 0, nickfg, optbg)
if maxlen < 0:
return padding + string
return string + padding | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def _html_apply_colors(self, match):
string = match.group()
end = string.find('}')
if end < 0:
return string
color = string[2:end]
text = string[end + 1:]
return self.html_string(text, 0, color) | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def html_chat_time(self, msgtime):
"""Return formatted time with colors."""
option = 'weechat.look.buffer_time_format'
if self.options[option].find('${') >= 0:
str_without_colors = re.sub(r'\$\{[^\}]+\}', '', self.options[option])
length = len(time.strftime(str_without_colors, msgtime))
value = re.compile(r'\$\{[^\}]+\}[^\$]*').sub(self._html_apply_colors, self.options[option])
else:
value = time.strftime(self.options[option], msgtime)
length = len(value)
value = re.compile(r'[^0-9]+').sub(self._html_apply_color_chat_time_delimiters, value)
value = self.html_string(value, 0, 'weechat.color.chat_time')
return (time.strftime(value, msgtime), length) | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def to_html(self):
"""Print HTML version of theme."""
self.html_nick_self = 'mario'
channel = '#weechat'
oldtopic = 'Welcome'
newtopic = 'Welcome to %s - help channel for WeeChat' % channel
nicks = ('@carl', '@jessika', '@louise', '%Melody', '%Diego', '+Max',
'sheryl', 'Harold^', 'richard', 'celia', 'Eva', 'freddy', 'lee',
'madeleine', self.html_nick_self, 'mila', 'peter', 'tina', 'Vince', 'warren', 'warren2')
nicks_hosts = ('test@foo.com', 'something@host.com')
chat_msgs = ('Hello!',
'hi mario, I just tested your patch',
'I would like to ask something',
'just ask!',
'WeeChat is great?',
'yes',
'indeed',
'sure',
'of course!',
'affirmative',
'all right',
'obviously...',
'certainly!')
html = []
#html.append('<pre style="line-height: 1.2em">')
html.append('<pre>')
width = self.chat_width + 1 + self.nicklist_width
# title bar
html.append(self.html_string(newtopic, width,
'weechat.bar.title.color_fg', 'weechat.bar.title.color_bg'))
# chat
chat = []
str_prefix_join = self.html_string('-->', self.prefix_width * -1, 'weechat.color.chat_prefix_join', 'weechat.color.chat_bg')
str_prefix_quit = self.html_string('<--', self.prefix_width * -1, 'weechat.color.chat_prefix_quit', 'weechat.color.chat_bg')
str_prefix_network = self.html_string('--', self.prefix_width * -1, 'weechat.color.chat_prefix_network', 'weechat.color.chat_bg')
str_prefix_empty = self.html_string('', self.prefix_width * -1, 'weechat.color.chat', 'weechat.color.chat_bg')
chat.append(self.html_chat((9, 10, 00),
str_prefix_join,
(('', self.html_nick_self),
('weechat.color.chat_delimiters', ' ('),
('weechat.color.chat_host', nicks_hosts[0]),
('weechat.color.chat_delimiters', ')'),
('irc.color.message_join', ' has joined '),
('weechat.color.chat_channel', channel))))
chat.append(self.html_chat((9, 10, 25),
self.html_nick(nicks, 8, True, True, False, self.prefix_width * -1),
(('weechat.color.chat', chat_msgs[0]),)))
chat.append(self.html_chat((9, 11, 2),
str_prefix_network,
(('', nicks[0]),
('weechat.color.chat', ' has changed topic for '),
('weechat.color.chat_channel', channel),
('weechat.color.chat', ' from "'),
('irc.color.topic_old', oldtopic),
('weechat.color.chat', '"'))))
chat.append(self.html_chat((9, 11, 2),
str_prefix_empty,
(('weechat.color.chat', 'to "'),
('irc.color.topic_new', newtopic),
('weechat.color.chat', '"'))))
chat.append(self.html_chat((9, 11, 36),
self.html_nick(nicks, 16, True, True, True, self.prefix_width * -1),
(('weechat.color.chat', chat_msgs[1]),)))
chat.append(self.html_chat((9, 12, 4),
str_prefix_quit,
(('', 'joe'),
('weechat.color.chat_delimiters', ' ('),
('weechat.color.chat_host', nicks_hosts[1]),
('weechat.color.chat_delimiters', ')'),
('irc.color.message_quit', ' has left '),
('weechat.color.chat_channel', channel),
('weechat.color.chat_delimiters', ' ('),
('irc.color.reason_quit', 'bye!'),
('weechat.color.chat_delimiters', ')'))))
chat.append(self.html_chat((9, 15, 58),
self.html_nick(nicks, 12, True, True, False, self.prefix_width * -1),
(('weechat.color.chat', chat_msgs[2]),)))
chat.append(self.html_chat((9, 16, 12),
self.html_nick(nicks, 0, True, True, False, self.prefix_width * -1),
(('weechat.color.chat', chat_msgs[3]),)))
chat.append(self.html_chat((9, 16, 27),
self.html_nick(nicks, 12, True, True, False, self.prefix_width * -1),
(('weechat.color.chat', chat_msgs[4]),)))
for i in range(5, len(chat_msgs)):
chat.append(self.html_chat((9, 17, (i - 5) * 4),
self.html_nick(nicks, i - 2, True, True, False, self.prefix_width * -1),
(('weechat.color.chat', chat_msgs[i]),)))
chat_empty = self.html_string(' ', self.chat_width, 'weechat.color.chat', 'weechat.color.chat_bg')
# separator (between chat and nicklist)
str_separator = self.html_string('│', 0, 'weechat.color.separator', 'weechat.color.chat_bg')
# nicklist
nicklist = []
for index in range(0, len(nicks)):
fg = 'weechat.bar.nicklist.color_fg'
if nicks[index].endswith('a'):
fg = 'weechat.color.nicklist_away'
nicklist.append(self.html_nick(nicks, index, True, True, False, self.nicklist_width, fg, 'weechat.bar.nicklist.color_bg'))
nicklist_empty = self.html_string('', self.nicklist_width, 'weechat.bar.nicklist.color_fg', 'weechat.bar.nicklist.color_bg')
# print chat + nicklist
for i in range (0, self.chat_height):
if i < len(chat):
str1 = chat[i]
else:
str1 = chat_empty
if i < len(nicklist):
str2 = nicklist[i]
else:
str2 = nicklist_empty
html.append('%s%s%s' % (str1, str_separator, str2))
# status
html.append(self.html_concat((('weechat.bar.status.color_delim', '['),
('weechat.color.status_time', '12:34'),
('weechat.bar.status.color_delim', '] ['),
('weechat.bar.status.color_fg', '18'),
('weechat.bar.status.color_delim', '] ['),
('weechat.bar.status.color_fg', 'irc'),
('weechat.bar.status.color_delim', '/'),
('weechat.bar.status.color_fg', 'freenode'),
('weechat.bar.status.color_delim', '] '),
('weechat.color.status_number', '2'),
('weechat.bar.status.color_delim', ':'),
('weechat.color.status_name', '#weechat'),
('weechat.bar.status.color_delim', '('),
('irc.color.item_channel_modes', '+nt'),
('weechat.bar.status.color_delim', '){'),
('weechat.bar.status.color_fg', '%d' % len(nicks)),
('weechat.bar.status.color_delim', '} ['),
('weechat.bar.status.color_fg', 'Act: '),
('weechat.color.status_data_highlight', '3'),
('weechat.bar.status.color_delim', ':'),
('weechat.bar.status.color_fg', '#linux'),
('weechat.bar.status.color_delim', ','),
('weechat.color.status_data_private', '18'),
('weechat.bar.status.color_delim', ','),
('weechat.color.status_data_msg', '4'),
('weechat.bar.status.color_delim', ','),
('weechat.color.status_data_other', '5'),
('weechat.bar.status.color_delim', ','),
('weechat.color.status_data_other', '6'),
('weechat.bar.status.color_delim', ']')),
width, 'weechat.bar.status.color_fg', 'weechat.bar.status.color_bg'))
# input
html.append(self.html_concat((('weechat.bar.input.color_delim', '['),
(self.nick_prefix_color('+'), '+'),
('irc.color.input_nick', self.html_nick_self),
('weechat.bar.input.color_delim', '('),
('weechat.bar.input.color_fg', 'i'),
('weechat.bar.input.color_delim', ')] '),
('weechat.bar.input.color_fg', 'this is misspelled '),
('aspell.look.color', 'woord'),
('weechat.bar.input.color_fg', ' '),
('cursor', ' ')),
width, 'weechat.bar.input.color_fg', 'weechat.bar.input.color_bg'))
# end
html.append('</pre>')
del self.html_nick_self
return '\n'.join(html) | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def save_html(self, filename, whitebg=False):
html = self.get_html(whitebg)
try:
f = open(filename, 'w')
f.write(html)
f.close()
self.prnt('Theme exported as HTML to "%s"' % filename)
except:
self.prnt_error('Error writing HTML to "%s"' % filename)
raise | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def theme_cmd(data, buffer, args):
"""Callback for /theme command."""
if args == '':
weechat.command('', '/help %s' % SCRIPT_COMMAND)
return weechat.WEECHAT_RC_OK
argv = args.strip().split(' ', 1)
if len(argv) == 0:
return weechat.WEECHAT_RC_OK
if argv[0] in ('list', 'install'):
weechat.prnt('', '%s: action "%s" not developed' % (SCRIPT_NAME, argv[0]))
return weechat.WEECHAT_RC_OK
# check arguments
if len(argv) < 2:
if argv[0] in ('install', 'installfile', 'save', 'export'):
weechat.prnt('', '%s: too few arguments for action "%s"'
% (SCRIPT_NAME, argv[0]))
return weechat.WEECHAT_RC_OK
# execute asked action
if argv[0] == 'info':
filename = None
if len(argv) >= 2:
filename = argv[1]
theme = Theme(filename)
if filename:
theme.info('Info about theme "%s":' % filename)
else:
theme.info('Info about current theme:')
elif argv[0] == 'show':
filename = None
if len(argv) >= 2:
filename = argv[1]
theme = Theme(filename)
if filename:
theme.show('Content of theme "%s":' % filename)
else:
theme.show('Content of current theme:')
elif argv[0] == 'installfile':
theme = Theme()
theme.save(theme_config_get_undo())
theme = Theme(argv[1])
if theme.isok():
theme.install()
elif argv[0] == 'undo':
theme = Theme(theme_config_get_undo())
if theme.isok():
theme.install()
elif argv[0] == 'save':
theme = Theme()
theme.save(argv[1])
elif argv[0] == 'backup':
theme = Theme()
theme.save(theme_config_get_backup())
elif argv[0] == 'restore':
theme = Theme(theme_config_get_backup())
if theme.isok():
theme.install()
elif argv[0] == 'export':
htheme = HtmlTheme()
whitebg = False
htmlfile = argv[1]
argv2 = args.strip().split(' ', 2)
if len(argv2) >= 3 and argv2[1] == 'white':
whitebg = True
htmlfile = argv2[2]
htheme.save_html(htmlfile, whitebg)
return weechat.WEECHAT_RC_OK | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def theme_init():
"""Called when script is loaded."""
theme_config_create_dir()
filename = theme_config_get_backup()
if not os.path.isfile(filename):
theme = Theme()
theme.save(filename) | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def theme_cmdline():
if len(sys.argv) < 2 or sys.argv[1] in ('-h', '--help'):
theme_cmdline_usage()
elif len(sys.argv) > 1:
if sys.argv[1] in ('-e', '--export'):
if len(sys.argv) < 4:
theme_cmdline_usage()
whitebg = 'white' in sys.argv[4:]
htheme = HtmlTheme(sys.argv[2])
htheme.save_html(sys.argv[3], whitebg)
elif sys.argv[1] in ('-i', '--info'):
if len(sys.argv) < 3:
theme_cmdline_usage()
theme = Theme(sys.argv[2])
theme.info('Info about theme "%s":' % sys.argv[2])
else:
theme_cmdline_usage() | posquit0/dotfiles | [
170,
19,
170,
1,
1413121319
] |
def _split_what(what):
"""
Returns a tuple of `frozenset`s of classes and attributes.
"""
return (
frozenset(cls for cls in what if isclass(cls)),
frozenset(cls for cls in what if isinstance(cls, Attribute)),
) | python-attrs/attrs | [
4664,
337,
4664,
119,
1422370861
] |
def include_(attribute, value):
return value.__class__ in cls or attribute in attrs | python-attrs/attrs | [
4664,
337,
4664,
119,
1422370861
] |
def setup(self):
self.app = bountyfunding.app.test_client()
clean_database() | bountyfunding/bountyfunding | [
11,
4,
11,
1,
1372027522
] |
def test_email(self):
eq_(len(self.get_emails()), 0) | bountyfunding/bountyfunding | [
11,
4,
11,
1,
1372027522
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.