repo_name stringlengths 5 100 | path stringlengths 4 231 | language stringclasses 1
value | license stringclasses 15
values | size int64 6 947k | score float64 0 0.34 | prefix stringlengths 0 8.16k | middle stringlengths 3 512 | suffix stringlengths 0 8.17k |
|---|---|---|---|---|---|---|---|---|
rdio/sentry | src/sentry/migrations/0082_auto__add_activity__add_field_group_num_comments__add_field_event_num_.py | Python | bsd-3-clause | 25,258 | 0.008195 | # -*- coding: 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):
# Adding model 'Activity'
db.create_table('sentry_activity', (
('id', self.gf('django.db.models.... | "(('project', 'tuser', 'group'),)", 'object_name': 'AffectedUserByGroup'},
'first_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
'group': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['sentry.Group']"}),
| 'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ident': ('django.db.models.fields.CharField', [], {'max_length': '200', 'null': 'True'}),
'last_seen': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'db_index': 'True'}),
... |
antoinecarme/pyaf | tests/periodicities/Business_Hour/Cycle_Business_Hour_50_BH_24.py | Python | bsd-3-clause | 82 | 0.04878 | import tests.periodicities.period_test as p | er
per.buildModel((24 , 'BH' | , 50));
|
lawl/pmbootstrap | pmb/aportgen/__init__.py | Python | gpl-3.0 | 2,359 | 0.000424 | """
Copyright 2017 Oliver Smith
This file is part of pmbootstrap.
pmbootstrap is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
pmbootstrap ... |
import os
import logging
import pmb.aportgen.binutils
import pmb.aportgen.busybox_static
import pmb.aportgen.device
import pmb.aportgen.gcc
import pmb.aportgen.linux
import pmb.aportgen.musl
import pmb.config
import pmb.helpers.cli
def properties(pkgname):
"""
Get the `pmb.config.aportgen` properties for the... | pkgname prefix.
Example: "musl-armhf" => ("musl", "cross", {"confirm_overwrite": False})
:param pkgname: package name
:returns: (prefix, folder, options)
"""
for folder, options in pmb.config.aportgen.items():
for prefix in options["prefixes"]:
if pkgname.startswith(prefix):
... |
rabipanda/tensorflow | tensorflow/python/estimator/estimator.py | Python | apache-2.0 | 47,094 | 0.005585 | # Copyright 2016 The TensorFlow Authors. 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 applica... | emporary directory will be used.
config: Configuration object.
params: `dict` of hyper parameters that will be passed into `model_fn`.
Keys are names of parameters, values are basic python types.
warm_start_from: Optional s | tring filepath to a checkpoint to warm-start
from, or a `tf.estimator.WarmStartSettings` object to
fully configure warm-starting. If the string filepath is
provided instead of a `WarmStartSettings`, then all
variables are warm-... |
jfwood/barbican-1 | barbican/queue/simple/resources.py | Python | apache-2.0 | 1,675 | 0 | # Copyright (c) 2013 Rackspace, Inc.
#
# 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 wr... | on(verification_id, keystone_id):
"""Process Verification."""
LOG.debug('Verification id is {0}'.format(verification_id))
task = resources.PerformVerification()
try:
task.process(verification_id, keystone_id)
except Exception:
LOG.exception(">>>>> Task exception seen, but simulatin | g async "
"reporting via the Verification entity on the "
"worker side.")
|
Schamnad/cclib | test/data/testSPun.py | Python | bsd-3-clause | 6,501 | 0.002307 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016, the cclib development team
#
# This file is part of cclib (http://cclib.github.io) and is distributed under
# the terms of the BSD 3-Clause License.
"""Test unrestrictied single point logfiles in cclib"""
import os
import unittest
import numpy
from skip ... | single point unittest"""
def testnooccnos(self):
"""Are natural orbital occupation numbers the right size?"""
self.assertEqu | als(self.data.nooccnos.shape, (self.data.nmo, ))
class GaussianSPunTest(GenericSPunTest):
"""Customized unrestricted single point unittest"""
def testatomnos(self):
"""Does atomnos have the right dimension (20)?"""
size = len(self.data.atomnos)
self.assertEquals(size, 20)
... |
havrlant/fca-search | src/retrieval/spell_checker.py | Python | bsd-2-clause | 823 | 0.030377 | import math
from common.string import strip_accents
from difflib import get_close_matches
class SpellChecker():
def __init__(self, allWords):
self.allWords = {x for x in allWords if x}
def checkWords(self, words):
if words and words[0]:
suggestions = {x:self.check(x) for x in words}
suggestions = {k:v for... | d)
if word in self.allWords or not word:
return word
lword = len(word)
maxDiffs = max(1, math.floor(lword / 5))
candidates = [x for x in self.allWords if abs(len(x) - lword) <= max | Diffs and (x[0] == word[0] or x[len(x)-1] == word[lword-1])]
matches = get_close_matches(word, candidates, cutoff=0.7)
return matches[0] if matches else word |
graphql-python/graphql-core | tests/validation/test_lone_anonymous_operation.py | Python | mit | 2,602 | 0 | from functools import partial
from graphql.validation import LoneAnonymousOperationRule
from .harness import assert_validation_errors
assert_errors = partial(assert_validation_errors, LoneAnonymousOperationRule)
assert_valid = partial(assert_errors, errors=[])
def describe_validate_anonymous_operation_must_be_alo... | query Foo {
field
}
query Bar {
field
}
"""
)
def anon_operation_with_fragment():
assert_valid(
"""
{
...Foo
}
fragment Foo on Type {
field
... |
)
def multiple_anon_operations():
assert_errors(
"""
{
fieldA
}
{
fieldB
}
""",
[
{
"message": "This anonymous operation"
" must b... |
yardex/python-mingus | mingus_examples/improviser/improviser.py | Python | gpl-3.0 | 5,915 | 0.002367 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
*** Description ***
Converts a progression to chords, orchestrates them and plays
them using fluidsynth.
Make sure to set SF2 to a valid soundfont file.
Based on play_progression.py
"""
from mingus.core import progressions, intervals
from mingus.core im... | = ["I", "vi", "ii", "iii7", "I7", "viidom7", | "iii7",
# "V7"]
key = 'C'
# If True every second iteration will be played in double time, starting on the
# first
double_time = True
orchestrate_second = True
swing = True
play_solo = True
play_drums = True
play_bass = True
play_chords = True
bar_length = 1.75
song_end = 28
# Control beginning of solos and chords... |
mattclay/ansible | test/support/network-integration/collections/ansible_collections/vyos/vyos/plugins/cliconf/vyos.py | Python | gpl-3.0 | 10,676 | 0.00103 | #
# (c) 2017 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is d... | visited = set()
for line in candidate_commands:
| item = str(line).replace("'", "")
if not item.startswith("set") and not item.startswith("delete"):
raise ValueError(
"line must start with either `set` or `delete`"
)
elif item.startswith("set") and item not in running_commands:
... |
3ptscience/steno3dpy | steno3d/options.py | Python | mit | 1,305 | 0 | """options.py defines the base option classes for steno3d"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from json import dumps
import properties
from .props import HasSteno3DProps
class Options(HasSteno3DProps... | lue'] = self._props[change['name']].default
class ColorOptions(Options):
"""Options related to resource display color"""
color = properties.Color(
| doc='Solid color',
default='random',
required=False
)
opacity = properties.Float(
doc='Opacity',
default=1.,
min=0.,
max=1.,
required=False
)
class MeshOptions(Options):
"""Options related to mesh display"""
wireframe = properties.Boolean... |
cmunk/protwis | structure/assign_generic_numbers_gpcr.py | Python | apache-2.0 | 11,967 | 0.010445 | from django.conf import settings
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.PDB import *
from Bio.PDB.PDBIO import Select
from common.definitions import *
from protein.models import Protein, ProteinSegment
from residue.models import Residue
from structure.functions import BlastSearch... | eptide
import os,logging
from collections import Ord | eredDict
logger = logging.getLogger("protwis")
#==============================================================================
#Class for annotating the pdb structures with generic numbers
class GenericNumbering(object):
residue_list = ["ARG","ASP","GLU","HIS","ASN","GLN","LYS","SER","THR","HID... |
opengovcat/seismometer | scripts/reload.py | Python | mit | 1,800 | 0.008889 | #!/usr/bin/env python
from lxml import objectify
import argparse
import os
import codecs
import gzip
# init constants and vars
RAWDATADIR = 'opengov.cat/rawdata/xml/' # use 'wget -r -np http://opengov.cat/rawdata/xml/ to download files'
start = {}
end = {}
entity = {}
# load entities
def read():
files = [ f for f... | 'iddep': item.iddep
}
#print f[:10], item.id | , item.iddep
if not start.has_key(id):
start[id] = date
# check last entities data
for i in start.keys():
if not e.has_key(i) and not end.has_key(i):
end[i] = date
read()
f = codecs.open('entities.csv', encoding='utf-8', mode='a+')
f.write('id,... |
hakehuang/pycpld | ips/ip/qdec/__init__.py | Python | mit | 66 | 0.015152 | from qdec_partial import g | et_ip_nam | e
from qdec_partial import QDEC |
aburgasser/splat | splat/simulate.py | Python | mit | 110,951 | 0.031636 | from __future__ import print_function, division
# imports: internal
import copy
import glob
import os
import requests
import time
# imports: external
from astropy import units as u
from astropy.coordinates import SkyCoord
import astropy.constants as constants
from astropy.cosmology import Planck15, z_at_value
from as... | , 6.66649153e-0 | 4,
5.15618875e-04])
'''
# constants
r0 = (8000.*u.pc).to(unit).value # radial offset from galactic center to Sun
z0 = (25.*u.pc).to(unit).value # vertical offset from galactic plane to Sun
r1 = (2600.*u.pc).to(unit).value # radial length scale of exponential thin disk
z1 = (300.*u.pc).to(unit).value # ve... |
go-lab/appcomposer | alembic/versions/4148c3cb14ad_update_models_to_avoid_uniqueness_errors.py | Python | bsd-2-clause | 1,977 | 0.011634 | """Update models to avoid uniqueness errors
Revision ID: 4148c3cb14ad
Revises: 21e927fdf78c
Create Date: 2015-04-24 23:27:26.628208
"""
# revision identifiers, used by Alembic.
revision = '4148c3cb14ad'
down_revision = '21e927fdf78c'
import hashlib
from alembic import op
import sqlalchemy as sa
import sqlalchemy.sq... | g_suggestions = sql.select([ExternalSuggestions.c.id, ExternalSuggestions.c.human_key])
for row in op.get_bind().execute(existing_suggestions):
suggestion_id = row[ExternalSuggestions.c.id]
hum | an_key_hash = hashlib.md5(row[ExternalSuggestions.c.human_key]).hexdigest()
update_stmt = ExternalSuggestions.update().where(ExternalSuggestions.c.id == suggestion_id).values(human_key_hash = human_key_hash)
op.execute(update_stmt)
def downgrade():
### commands auto generated by Alembic - please ... |
ChinaMassClouds/copenstack-server | openstack/src/ceilometer-2014.2.2/ceilometer/tests/ipmi/notifications/test_ironic.py | Python | gpl-2.0 | 8,529 | 0 | #
# Copyright 2014 Red Hat, Inc
#
# Author: Chris Dent <chdent@redhat.com>
#
# 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 requi... | rce_id]
self.assertEqual(6900.0, test_counter.volume)
self.assertEqual('RPM', test_counter.unit)
| self.assertEqual(sample.TYPE_GAUGE, test_counter.type)
self.assertEqual('hardware.ipmi.fan', test_counter.name)
def test_ipmi_voltage_notification(self):
"""Test IPMI Voltage sensor data.
A single voltage reading is effectively the same as temperature,
modulo "voltage".
... |
nguyentran/openviber | tools/swtoolkit/test/environment_tools_test.py | Python | mit | 10,313 | 0.003394 | #!/usr/bin/python2.4
# Copyright 2009, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of... | ['1', '2', '3']), [])
self.assertEqual(env.Overlap(['1', '$OLVAR', '3'], '$OLVAR'), ['baz'])
# Variable substitition will replace and flatten lists
self.assertEqual(set(env.Overlap(['1', '2', '3'], | '$OLLIST')),
set(['2', '3']))
# Substitution flattens lists
self.assertEqual(set(env.Overlap([['1', '2'], '3'], ['2', ['3', '4']])),
set(['2', '3']))
def testSubstList2(self):
"""Test SubstList2()."""
env = self.env
# Empty args should return empty list... |
louisLouL/pair_trading | capstone_env/lib/python3.6/site-packages/quandl/util.py | Python | mit | 3,666 | 0.000546 | from inflection import parameterize
import dateutil.parser
import re
from six import string_types
class Util(object):
@staticmethod
def constructed_path(path, params={}):
for key in list(params.copy().keys()):
| modified_path = path.replace(":%s" % key, str(params[key]))
if modified_path != path:
params.pop(key, None)
path = modified_path
return path
# http://stackoverflow | .com/questions/38987/how-can-i-merge-two-python-dictionaries-in-a-single-expression
@staticmethod
def merge_to_dicts(x, y):
z = x.copy()
z.update(y)
return z
@staticmethod
def methodize(string):
return parameterize(string.replace(r'.', '')).replace(r'-', '_')
@stati... |
nke001/attention-lvcsr | libs/Theano/theano/sandbox/cuda/opt.py | Python | mit | 96,948 | 0.00163 | from __future__ import print_function
import logging
_logger = logging.getLogger('theano.sandbox.cuda.opt')
import copy
import sys
import time
import warnings
import pdb
import numpy
import theano
from theano import scalar as scal
from theano import config, tensor, gof
import theano.ifelse
from six.moves import red... | = 'output' or
input.clients[0][0].op == gpu_from_host)):
continue
try:
new_input | = host_from_gpu(gpu_from_host(input))
if new_input.type == input.type:
fgraph.replace_validate(input, new_input,
"InputToGpuOptimizer")
except TypeError:
# as we currently only support float32, this can fail.
... |
samsaga2/tv3alacarta | default.py | Python | gpl-3.0 | 937 | 0.004269 | # URL INFO http://www.tv3.cat/pvideo/FLV_bbd_dadesItem.jsp?idint=4705751
# URL RTMP http://www.tv3.cat/pvideo/FLV_bbd_media.jsp?PROFILE=EVP&ID=4705751&QUALITY=H&FORMAT=MP4
# el QUALITY y el FORMAT salen del URL INFO
'''
REMOTE_DBG = True
if REMOTE_DBG:
try:
import pysrc.pydevd as pydevd
... | hannel import TV3Channel
from a3mediachannel import A3MediaChannel
base_url = sys.argv[0]
addon_handle = int(sys.argv | [1])
args = urlparse.parse_qs(sys.argv[2][1:])
xbmcplugin.setContent(addon_handle, 'movies')
#channel = TV3Channel(base_url, addon_handle, args)
channel = A3MediaChannel(base_url, addon_handle, args)
channel.call()
|
HuaweiSNC/OPS2 | src/python/dao/driver_mgmt.py | Python | mit | 5,150 | 0.022789 | # -*- coding: utf-8 -*-
'''
Created on 2013-3-8
@author: m00147039
'''
import sqlite3
#===============================================================================
# DB Data struct
#===============================================================================
ID = 0
PROCDUCTTYPE = 1
VERSION = 2
MODULENAME = 3
... | True
self._conn.ex | ecute("create table if not exists drivers_table( id integer primary key autoincrement, \
productType varchar(128), \
version varchar(128), \
... |
naderm/cs188 | p5/classification/testParser.py | Python | bsd-3-clause | 3,041 | 0.008221 | # testParser.py
# -------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to
# http://inst.... | fixed_lines.append(l)
else:
fixed_lines.append(l[0:idx])
return '\n'.join(fixed_lines)
def parse(self):
# read in the test case and remove comments
test = {}
with open(self.path) as handle:
| raw_lines = handle.read().split('\n')
test_text = self.removeComments(raw_lines)
test['__raw_lines__'] = raw_lines
test['path'] = self.path
test['__emit__'] = []
lines = test_text.split('\n')
i = 0
# read a property in each loop cycle
while(i ... |
dav1x/openshift-ansible-contrib | reference-architecture/vmware-ansible/inventory/vsphere/vms/vmware_inventory.py | Python | apache-2.0 | 27,704 | 0.001372 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C): 2017, Ansible Project
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Requirements
# - pyvmomi >= 6.0.0.2016.4
# TODO:
# * more jq examples
# * optional folder heriarchy
"""
$ jq '._meta.hostvars[].c... | ,
'validate_certs': True,
'ini_path': os.path.join(os.path.dirname(__file__), '%s.ini' % scriptbasename),
'cache_name': 'ansible-vmware',
'cache_path': '~/.ansible/tmp',
'cache_max_age': 3600,
'max_object_level': 1,
'skip_keys | ': 'declaredalarmstate,'
'disabledmethod,'
'dynamicproperty,'
'dynamictype,'
'environmentbrowser,'
'managedby,'
'parent,'
'childtype,'
... |
jabesq/home-assistant | homeassistant/components/ring/camera.py | Python | apache-2.0 | 5,739 | 0 | """This component provides support to the Ring Door Bell camera."""
import asyncio
from datetime import timedelta
import logging
import voluptuous as vol
from homeassistant.components.camera import PLATFORM_SCHEMA, Camera
from homeassistant.components.ffmpeg import DATA_FFMPEG
from homeassistant.const import ATTR_ATT... | elta(minutes=45)
_LOGGER = logging.getLogger(__name__)
NOTIFICATION_TITLE = 'Ring Camera Setup'
SCAN_INTE | RVAL = timedelta(seconds=90)
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_FFMPEG_ARGUMENTS): cv.string,
vol.Optional(CONF_SCAN_INTERVAL, default=SCAN_INTERVAL): cv.time_period,
})
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up a Ring Door Bell and StickUp C... |
qedsoftware/commcare-hq | corehq/apps/reports/standard/monitoring.py | Python | bsd-3-clause | 67,020 | 0.002641 | from collections import defaultdict, namedtuple
import datetime
from urllib import urlencode
import math
import operator
from pygooglechart import ScatterChart
import pytz
from corehq.apps.es import filters
from corehq.apps.es import cases as case_es
from corehq.apps.es.aggregations import (
TermsAggregation,
... | closed in the last {} days.")),
# "recently active" means "touched in the last 120 days"
]
@property
def totals_columns(self):
return [
(_("# Active Cases"),
_("Number of open cases modified in the last {} days")),
(_("# Inactive Cases"),
... | "last {} days")),
]
@property
def special_notice(self):
if self.domain_object.case_sharing_included():
return _("This report currently does not support case sharing. "
"There might be inconsistencies in case totals if the "
"user is ... |
tzolov/elasticsearch-yarn-ambari-plugin | src/main/resources/services/ELASTICSEARCH_YARN/package/scripts/master.py | Python | apache-2.0 | 6,151 | 0.028288 | #!/usr/bin/env python
"""
Licensed to the Apache Software Foundation (ASF) 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");... | ser, logoutput=True, timeout=300)
Execute(format('hadoop jar {es_jar_path} -install-es hdfs.upload.dir={es_hdfs_upload_dir} download.local.dir={es_download_local_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=Tr | ue, timeout=300)
Execute(format('hadoop jar {es_jar_path} -install hdfs.upload.dir={es_hdfs_upload_dir} download.local.dir={es_download_local_dir} es.version={es_version} loadConfig=/home/{es_user}/elasticsearch.properties'), user=params.es_user, logoutput=True, timeout=300)
# Store the properties required by S... |
low-sky/degas | degas/examples/compare_cube.py | Python | gpl-3.0 | 6,219 | 0.005146 | from spectral_cube import SpectralCube
import glob
from astropy.convolution import Box1DKernel
import astropy.units as u
from corner import corner
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats as ss
empdir = '/mnt/space/erosolow/surveys/empire/'
degasdir = '/mnt/space/erosolow/surveys/DEGAS/'
m... | numpy as np
# corner(np.c_[empire_reproj.filled_data[:].ravel(), degas_con.filled_data[:].ravel()])
# corner(np.c_[empire_reproj.filled_data[:].ravel().value, degas_con.filled_data[:].ravel().value])
# emp = =empire_reproj.filled_data[:].value
# emp =empire_reproj.filled_data[:].value
# deg = degas_con.filled_data[:]... | * np.isfinite(deg)
# corner(np.c_[emp[idx], deg[idx]])
# plt.show()
# ?corner
# corner(np.c_[emp[idx], deg[idx]])
# plt.set_xrange([-0.006, 0.012])
# plt.set_xlim([-0.006, 0.012])
# f = corner(np.c_[emp[idx], deg[idx]])
# f.axes
# f.axes[2].set_xlim([-0.006, 0.02])
# f.axes[2].set_ylim([-0.006, 0.02])
# plt.show()
# f... |
AMOboxTV/AMOBox.LegoBuild | script.module.youtube.dl/lib/youtube_dl/extractor/jeuxvideo.py | Python | gpl-2.0 | 2,038 | 0.002459 | # coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class JeuxVideoIE(InfoExtractor):
_VALID_URL = r'http://.*?\.jeuxvideo\.com/.*/(.*?)\.htm'
_TESTS = [{
'url': 'http://www.jeuxvideo.com/reportages-videos-jeux/0004/00046170/tearaway-playstation-vita... | [{
'url': source['file'],
| 'format_id': source['label'],
'resolution': source['label'],
} for source in reversed(config['sources'])]
return {
'id': video_id,
'title': title,
'formats': formats,
'description': self._og_search_description(webpage),
... |
Delosari/dazer | working_examples/testing_constants.py | Python | mit | 19 | 0.052632 | myA | = 5.2
myB = 5.3 | |
motmot/fview | motmot/fview/utils.py | Python | bsd-3-clause | 1,929 | 0.020736 | import threading
import numpy as np
def ros_ensure_valid_name(name):
return name.replace('-','_')
def lineseg_box(xmin, ymin, xmax, ymax):
return [ [xmin,ymin,xmin,ymax],
[xmin,ymax,xmax,ymax],
[xmax,ymax,xmax,ymin],
[xmax,ymin,xmin,ymin],
]
def lineseg_circle(x,y,... | (self):
return self.evt.isSet()
def | get(self,*args,**kwargs):
# called from consumer thread
self.evt.wait(*args,**kwargs)
val = self._val
self.evt.clear()
return val
def get_nowait(self):
# XXX TODO this is not atomic and is thus dangerous.
# (The value could get read, then another thread could ... |
Jspsun/LEETCodePractice | Python/WordPattern.py | Python | mit | 407 | 0.002457 | class Solution(object):
def wordPattern(self, pattern, str):
s = pattern
t = str.split()
# gets the index of each char withi | n the string and ge | nerates a list
sDex = map(s.find, s)
# gets the index of each word within the array and generates a list
tDex = map(t.index, t)
return sDex == tDex
S = Solution()
print S.wordPattern("abba", "a b b a")
|
bungoume/debug-server | debug_server/manage.py | Python | mit | 255 | 0 | #!/usr/ | bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "debug_server.settings")
from django.core.management import execute_from_command_line
execute_fr | om_command_line(sys.argv)
|
usakhelo/FreeCAD | src/Mod/Arch/import3DS.py | Python | lgpl-2.1 | 4,196 | 0.01001 | #***************************************************************************
#* *
#* Copyright (c) 2016 Yorik van Havre <yorik@uncreated.net> *
#* *
#* This ... | nobj.obj.points.array:
verts.append([d_point[0],d_point[1],d_point[2]])
meshdata = []
for d_face in d_nobj.obj.faces.array:
meshdata.append([verts[int(d_face[i])] for i in xrange(3)])
m = [tuple(r) for r in d_nobj.obj.matrix.array]
| m = m[0] + m[1] + m[2] + m[3]
placement = FreeCAD.Placement(FreeCAD.Matrix(*m))
mesh = Mesh.Mesh(meshdata)
obj = FreeCAD.ActiveDocument.addObject("Mesh::Feature","Mesh")
obj.Mesh = mesh
obj.Placement = placement
else:
print("Skippi... |
KenKundert/messenger | tests/test_inform.py | Python | gpl-3.0 | 29,357 | 0.001942 | # Test Inform
# Imports {{{1
from inform import (
Inform, InformantFactory, Error, codicil, display, done, error,
errors_accrued, fatal, log, output, terminate, terminate_if_errors, warn,
set_culprit, add_culprit, get_culprit, join_culprit
)
from contextlib import contextmanager
from textwrap import dedent... | lla pariatur. Excepteur sint occaecat cupidatat
non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
''').strip()
# Utilities {{{1
invokeExecutableRegex = r"(?<=ack: invoked as: )[^\n]+(?=\n)"
invokeTimeRegex = r"(?<=ack: log opened on )[^\n]+(?=\n)"
def strip(stringio):
return stringio... | achieved = stringio.getvalue().strip()
achieved = re.sub(invokeExecutableRegex, '<exe>', achieved)
achieved = re.sub(invokeTimeRegex, '<date>', achieved)
return achieved
# Helper classes and functions {{{1
@contextmanager
def messenger(*args, **kwargs):
stdout = StringIO()
stderr = StringIO()
... |
reubano/hdxscraper-unhabitat | app/utils.py | Python | mit | 1,855 | 0.00054 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
utils
~~~~~
Provides miscellaneous utility methods
"""
from __future__ import (
absolute_import, division, print_function, with_statement,
unicode_literals)
import itertools as it
from termcolor import colored as color
underscor... | lds]
def prompt(ptype):
dictionary = {
'bullet': color(" →", "blue", attrs=['bold']),
| 'error': color(" ERROR:", "red", attrs=['bold']),
'success': color(" SUCCESS:", "green", attrs=['bold']),
'warn': color(" WARN:", "yellow", attrs=['bold'])
}
return dictionary[ptype].decode('utf-8')
def flatten_fields(record, key=None):
try:
for subkey, value in record.it... |
maurizi/otm-core | opentreemap/manage_treemap/views/fields.py | Python | agpl-3.0 | 8,599 | 0 | # -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from copy import deepcopy
from django.utils.translation import ugettext as _
from opentreemap.util import json_from_request
from treemap.models import Species
from treema... | p):
model_name = to_model_name(group['model'])
Model = safe_get_model_class(model_name)
mobj = Model(instance=instance)
model_fields = {field for field in mobj.tracked_fields
if _should_show_field(mobj, field)}
model_fields = {'%s.%s' % (group['mod... | :
if 'model' in group:
models = (to_model_name(group['model']), )
else:
models = ('Tree', 'Plot')
udfs = {udf.full_name for udf in udf_defs(instance)
if udf.iscollection and udf.model_type in models and
(group['header'] not in coll... |
frew/simpleproto | scons-local-1.1.0/SCons/Tool/pdflatex.py | Python | bsd-2-clause | 2,773 | 0.006491 | """SCons.Tool.pdflatex
Tool-specific initialization for pdflatex.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.Tool.Tool()
selection method.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008 The SCons Foundation
#
# Per... | on(PDFLaTeXAuxFunction,
strfunction=SCons.Tool.tex.TeXLaTeXStrFunction)
import pdf
pdf.generate(env)
bld = env['BUILDERS']['PDF']
bld.add_action('.ltx', PDFLaTeXAuxAction)
bld.add_action('.latex', PDFLaTeXAuxAction)
bld.add_emitter('.ltx', SCons.Tool.tex.tex_emitt... | ex.tex_emitter)
env['PDFLATEX'] = 'pdflatex'
env['PDFLATEXFLAGS'] = SCons.Util.CLVar('-interaction=nonstopmode')
env['PDFLATEXCOM'] = 'cd ${TARGET.dir} && $PDFLATEX $PDFLATEXFLAGS ${SOURCE.file}'
env['LATEXRETRIES'] = 3
def exists(env):
return env.Detect('pdflatex')
|
flingone/frameworks_base_cmds_remoted | libs/boost/tools/build/src/build/property.py | Python | apache-2.0 | 19,263 | 0.008566 | # Status: ported, except for tests and --abbreviate-paths.
# Base revision: 64070
#
# Copyright 2001, 2002, 2003 Dave Abrahams
# Copyright 2006 Rene Rivera
# Copyright 2002, 2003, 2004, 2005, 2006 Vladimir Prus
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.... |
xg = get_grist (x)
yg = get_grist (y)
if yg and not xg:
return -1
elif xg and not yg:
return 1
else:
if not xg:
x = feature.expan | d_subfeatures([x])
y = feature.expand_subfeatures([y])
if x < y:
return -1
elif x > y:
return 1
else:
return 0
def identify(string):
return string
# Uses Property
def refine (properties, requirements):
""" Refines... |
homeworkprod/byceps | byceps/services/global_setting/dbmodels.py | Python | bsd-3-clause | 720 | 0 | """
byceps.services.global_setting.dbmodels
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2021 Jochen Kupperschmidt
:License: Revised BSD (see `LICENSE` file for details)
"""
from ...database import db
from ...util.instances import ReprBuilder
class Setting(db.Model):
"""A global setting.""" |
__tablename__ = 'global_settings'
name = db.Column(db.UnicodeText, primary_key=True)
value = db.Column(db.UnicodeText)
def __init__(self, name: str, value: str) -> None:
self.name = name
self.value = value
| def __repr__(self) -> str:
return ReprBuilder(self) \
.add_with_lookup('name') \
.add_with_lookup('value') \
.build()
|
Adverpol/eco-basket | migrations/versions/1139f0b4c9e3_order_name_not_unique.py | Python | gpl-3.0 | 635 | 0.009449 | """order name | not unique
Revision ID: 1139f0b4c9e3
Revises: 220436d6dcdc
Create Date: 2016-05-31 08:59:21.225314
"""
# revision identifiers, used by Alembic.
revision = '1139f0b4c9e3'
down_revision = '220436d6dcdc | '
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_constraint('orders_name_key', 'orders', type_='unique')
### end Alembic commands ###
def downgrade():
### commands auto generated by Alembic - please adjust! ###
o... |
drj11/pdftables | pdftables/diagnostics.py | Python | bsd-2-clause | 11,691 | 0.000171 | #!/usr/bin/env python
import sys
from collections import namedtuple
import poppler
import cairo
from os.path import abspath
Point = namedtuple('Point', ['x', 'y'])
Line = namedtuple('Line', ['start', 'end'])
Polygon = namedtuple('Polygon', 'points')
Rectangle = namedtuple('Rectangle', ['top_left', 'bottom_right'])
A... | (
table_container._y_point_values,
table_container._center_lines,
direction="vertical")))
for table in table_container:
anno | tations.append(
AnnotationGroup(
name='row_edges',
color=Color(1, 0, 0),
shapes=convert_horizontal_lines(
table.row_edges, table.bounding_box)))
annotations.append(
AnnotationGroup(
name='column_edges',
... |
mtasic85/pytsort | tsort.py | Python | mit | 2,082 | 0.001921 | __all__ = ['tsort']
from functools import reduce
def tsort(data, smallest_first=False, fewest_edges_first=False, flatten=False):
# FIXME: support fewest_edges_first
# make copy of data
tmp = data.copy()
# remove self-references
for k, v in tmp.items():
v.discard(k)
# initially find v... | es)
else:
_empty_vertices = (v for v in empty_vertices)
# add current vertices that do not point to any other vertices
if flatten:
sorted_vertices.extend(_empty_vertices)
else:
sorted_vertices.append(_empty_vertices)
# traverse all vertices a... | hich are not in previously found vertices
# that do not point to any other vertices
# tmp = {
# k: (v - empty_vertices)
# for k, v in tmp.items()
# if k not in empty_vertices
# }
for k, v in list(tmp.items()):
if k in empty_vertic... |
jambonrose/djangocon2015-views | src/viewsproject/wsgi.py | Python | bsd-2-clause | 401 | 0 | """
WSGI config for viewsproject project.
It exposes the WSGI callable as a module-level va | riable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
| import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "viewsproject.settings")
application = get_wsgi_application()
|
geekosphere/wootpaste | alembic/versions/41804fbf1862_add_a_spam_field.py | Python | agpl-3.0 | 757 | 0.01321 | """add a spam field
Revision ID: 41804fbf1862
Revises: 4d7d5b95ddef
Create Date: 2014-12-17 19:04:09.190962 |
"""
# revision identifiers, used by Alembic.
revision = '41804fbf1862'
down_revision = '4d7d5b95ddef'
from alembic import op
import sql | alchemy as sa
from os.path import join, dirname, abspath, realpath
import sys
sys.path.append(realpath(join(dirname(abspath(__file__)), '..')))
import wootpaste.models
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.add_column('paste', sa.Column('spam', sa.Boolean(), nullable=Tr... |
toobaz/pandas | pandas/tests/series/conftest.py | Python | bsd-3-clause | 595 | 0 | import pytest
import pandas.util.testing as tm
@pytest.fixture
def datetime_series():
"""
Fixture for Series of floats with DatetimeIndex
"""
s = tm.makeTimeSeries()
s.name = "ts"
return s
@pytest.fixture
def string_series():
"""
Fixture for Series of floats with Index of unique str... | """
s = tm.makeStringSeries()
s.name = "series"
return s
@pytest.fixture
def object_series():
"""
Fixture for Series of dtype datetime64[ns] with Index of unique strings
"""
s = tm.makeObjectSeries()
s.name = "objects"
retu | rn s
|
SublimeLinter/SublimeLinter-coffeelint | linter.py | Python | mit | 752 | 0 | from SublimeLinter.lint import NodeLinter, util
class Coffeelint(NodeLinter):
regex = (
r'^<issue line="(?P<line>\d+)"\s*\r?\n'
r'\s*lineEnd="\d+"\s*\r?\n'
r'\s*reason="\[(?:(?P<error>error)|(?P<warning>warn))\]\s+'
r'(?:\[stdin\]:\d+:(?P<col>\d+):\s+error:\s+)?'
r'(?P<mess... | command = ['coffeelint', '--reporter', 'jslint', '--stdin']
if util.get_syntax(self.view) == 'coffeescript_literate':
command.append('--literate')
return command | |
gnowgi/gnowsys-studio | gstudio/admin/processtype.py | Python | agpl-3.0 | 16,358 | 0.002445 | """AttributetypeAdmin for Gstudio"""
from datetime import datetime
from django.forms import Media
from django.contrib import admin
from django.contrib.auth.models import User
from django.utils.html import strip_tags
from django.utils.text import truncate_words
from django.conf.urls.defaults import url
from django.conf... | cesstype.authors.all()]
return ', '.join(authors)
get_authors.allow_tags = True
get_authors.short_description = _('author(s)')
def get_metatypes(self, processtype):
"""Return the metatypes linked in HTML"""
try:
metatypes = ['<a href="%s" target="blank">%s</a>' %
... | tle)
for metatype in processtype.metatypes.all()]
except NoReverseMatch:
metatypes = [metatype.title for metatype in
processtype.metatypes.all()]
return ', '.join(metatypes)
get_metatypes.allow_tags = True
get_metatypes.short_descri... |
andreyrobota/AndreyKosinskiy | IdeaSite/apps.py | Python | mit | 91 | 0 | from django.apps | import AppConfig
class IdeasiteConfig(AppConfig):
| name = 'IdeaSite'
|
mokuki082/EggDrop | code/build/bdist.macosx-10.6-intel/python3.4-standalone/app/temp/pygame/display.py | Python | gpl-3.0 | 396 | 0.005051 |
def __load():
import imp, os, sys
ext = 'pygame/display.so'
for path in sys.path:
if not path.endswith('lib-dynload'):
continue
ext_path | = os.path.join(path, ext)
if os.path.exists | (ext_path):
mod = imp.load_dynamic(__name__, ext_path)
break
else:
raise ImportError(repr(ext) + " not found")
__load()
del __load
|
MDSLab/s4t-lighthing-rod | modules/plugins-manager/python/sync-wrapper.py | Python | apache-2.0 | 3,393 | 0.005305 | #############################################################################################
###
## Copyright (C) 2018 Nicola Peditto
###
## 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
###... | n = sys.argv[2]
plugin_params = sys.argv[3]
# Globals
socket_path = '/tmp/plugin-'+plugin_name
plugin_path = os.environ.get('IOTRONIC_HOME')+"/plugins/"+plugin_name+"/"+plugin_name+".py"
plugin = imp.load_source("plugin", plugin_path)
if sys.version_info[0] < 3:
import Queue
| q_result = Queue.Queue()
else:
import queue
q_result = queue.Queue()
# Thread to run user's plugin logic
class Plugin(threading.Thread):
def __init__(self, params, q_result, api):
threading.Thread.__init__(self)
self.setName(plugin_name)
self.name = plugin_name
self.para... |
GIR-at-AAMU/gir_app_labs_at_aamu | pages/authors/__init__.py | Python | apache-2.0 | 1,066 | 0.000938 | # Copyright 2017 The GiR @ AAMU Authors. 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 applica... | awells13
import cbradfo6
import dfoste18
import dwilso57
import egardner2
import ijoda
import jander37
import jbeatty
import jlindber
import jmedina
import jnoland
import kfikes3
import | klule
import lsteele3
import mcarrjr
import mhughe
import mmaneice
import nmai
import nwilli40
import pparrick
import smartine
import tlarsen
import tmcdani
import tthomp37
import ualexan1
|
OpenNews/opennews-source | source/people/migrations/0001_initial.py | Python | mit | 5,559 | 0.004317 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-28 01:00
from __future__ import unicode_literals
import caching.base
from django.db import migrations, models
import django.db.models.deletion
import sorl.thumbnail.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
... | ('github_repos_num', models.PositiveIntegerField(blank=True, null=True)),
('github_gists_num', models.PositiveIntegerField(blank=True, null=True)),
('homepage', models. | URLField(blank=True)),
('description', models.TextField(blank=True)),
('address', models.CharField(blank=True, max_length=255)),
('city', models.CharField(blank=True, max_length=64)),
('state', models.CharField(blank=True, max_length=32)),
... |
sonic182/portfolio3 | courses/migrations/0008_auto_20161019_1042.py | Python | mit | 430 | 0 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-10-19 10:42
from __future__ i | mport unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('courses', | '0007_auto_20161019_1014'),
]
operations = [
migrations.RenameField(
model_name='student',
old_name='courses',
new_name='course',
),
]
|
wisechengyi/pants | src/python/pants/backend/jvm/register.py | Python | apache-2.0 | 11,163 | 0.001971 | # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.jvm.artifact import Artifact
from pants.backend.jvm.ossrh_publication_metadata import (
Developer,
License,
OSSRHPublicationMetadata,
Scm,
)
from pants.b... | JvmPrepCommand,
"managed_jar_dependencies": ManagedJarDependencies,
"netrc_credentials": NetrcCredentials,
"scala_libr | ary": ScalaLibrary,
"scalac_plugin": ScalacPlugin,
"unpacked_jars": UnpackedJars,
},
objects={
"artifact": Artifact,
"scala_artifact": ScalaArtifact,
"ossrh": OSSRHPublicationMetadata,
"license": License,
"scm": Scm,
... |
flavoi/diventi | diventi/ebooks/migrations/0037_auto_20190524_0738.py | Python | apache-2.0 | 4,683 | 0.003417 | # Generated by Django 2.2.1 on 2019-05-24 05:38
from django.db import migrations, models |
class Migration(migrations.Migration):
dependencies = [
('ebooks', '0036_section_super_title'),
]
operations = [
migrations.AlterField(
model_name='book',
name='color',
field=models.CharField(blank=True, choices=[('info', 'Blue'), ('primary', 'Rose'),... | n'), ('default', 'Gray')], default='default', max_length=30, verbose_name='color'),
),
migrations.AlterField(
model_name='book',
name='description',
field=models.TextField(blank=True, verbose_name='description'),
),
migrations.AlterField(
m... |
fernandojvdasilva/algorithm-studies | chapter1/test_chapter1_solutions.py | Python | gpl-3.0 | 852 | 0.021127 | '''
Created on 30 de set de 2017
@author: fernando
'''
import unittest
from chapter1.solution_1_1 import has_all_unique_characters
from chapter1.solution_1_4 import are_anagrams
class Test(unittest.TestCase):
def testSolution1_1(self):
result = | has_all_unique_characters("cafdgbc")
assert(result == False)
result = has_all_unique_characters("adfegbc")
assert(result)
def testSolution1_4(self):
result = are_anagrams('ovo', 'voo')
assert(result)
resul... | sult == False)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testSolution1_1']
unittest.main() |
wangscript/libjingle-1 | trunk/build/android/gyp/gcc_preprocess.py | Python | bsd-3-clause | 1,415 | 0.010601 | #!/usr | /bin/env python
#
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style l | icense that can be
# found in the LICENSE file.
import optparse
import os
import subprocess
import sys
from util import build_utils
def DoGcc(options):
build_utils.MakeDirectory(os.path.dirname(options.output))
gcc_cmd = [
'gcc', # invoke host gcc.
'-E', # stop after... |
songgc/tensormate | tensormate/graph/image_graph.py | Python | apache-2.0 | 1,742 | 0.001722 | import tensorflow as tf
from tensorflow.contrib import layers
from tensorflow.contrib.framework import arg_scope
from tensormate.graph import TfGgraphBuilder
class ImageGraphBuilder(TfGgraphBuilder):
def __init__(self, scope=None, device=None, plain=False, data_format="NHWC",
data_format_ops=(l... | layers.separable_conv2d,
layers.separable_convolution2d,
layers.avg_pool2d,
layers.max_pool2d,
layers.batch_norm)):
| super(ImageGraphBuilder, self).__init__(scope=scope, device=device, plain=plain)
self.data_format = data_format
self.data_format_ops = data_format_ops if data_format_ops is not None else []
def _call_body(self, *args, **kwargs):
# is_training = kwargs.get("is_training", True)
... |
fenderglass/SpectroGene | scripts/proteome_run.py | Python | bsd-2-clause | 4,617 | 0.003032 | #!/usr/bin/env python
#(c) 2015 by Authors
#This file is a part of SpectroGene program.
#Released under the BSD license (see LICENSE file)
"""
This script performs SpectroGene run in known proteome mode (proteome run)
"""
from __future__ import print_function
import shutil
import sys
import os
import argparse
import... |
thread.start()
threads.append(thread)
out_file = os.path.join(inst_workdir, "spectra.OUTPUT_TABLE")
output_files.append(o | ut_file)
for t in threads:
t.join()
if thread_error[0] != 0:
print("There were errors running TopPIC, exiting")
return None
return output_files
def main():
parser = argparse.ArgumentParser(description="Runs SpectroGene in proteome"
" mode... |
guorendong/iridium-browser-ubuntu | components/proximity_auth/e2e_test/cryptauth.py | Python | bsd-3-clause | 4,829 | 0.005384 | # Copyright 2015 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 httplib
import json
import logging
import pprint
import time
logger = logging.getLogger('proximity_auth.%s' % __name__)
_GOOGLE_APIS_URL = 'www.goog... | _path, request_data):
| """ Sends an HTTP request to CryptAuth and returns the deserialized
response.
"""
conn = httplib.HTTPSConnection(self._google_apis_url)
path = _REQUEST_PATH % function_path
headers = {
'authorization': 'Bearer ' + self._access_token,
'Content-Type': 'application/json'
}
b... |
geowurster/str2type | str2type/__init__.py | Python | bsd-3-clause | 3,276 | 0.000916 | """
Convert a Python string to its native type.
The reason this module exists because there is a need to handle arguments with
the syntax `--opt KEY=VAL` where `KEY` will be used as a keyword argument
somewhere and `VAL` is expected to be a native Python type.
This module was built with click in mind, which is an exc... | l__ = "wursterk@gmail.com"
__source__ = "https://github.com/geowurster/str2type"
__license__ = """
New BSD License
Copyright (c) 2014-2015, Kevin D. Wurster
All rights reserved.
Redistribution and use in source and binary forms, with or without
modific | ation, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following ... |
ogirardot/django-registration | registration/forms.py | Python | bsd-3-clause | 4,861 | 0.005143 | """
Forms and validation code for user registration.
"""
from django.contrib.auth.models import User
from django import forms
from django.utils.translation import ugettext_lazy as _
# I put this on all required fields, because it's easier to pick up
# on them with CSS or JavaScript if they have a class of "require... | field.
"""
if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
if self.cleaned_data['password1'] != self.cleaned_data['password2']:
raise forms.ValidationError(_("The two password fields didn't match."))
return self.cleaned_data
... | s of ``RegistrationForm`` which adds a required checkbox
for agreeing to a site's Terms of Service.
"""
tos = forms.BooleanField(widget=forms.CheckboxInput(attrs=attrs_dict),
label=_(u'I have read and agree to the Terms of Service'),
error_messa... |
aurora-pro/apex-sigma | sigma/plugins/fun/vn_char.py | Python | gpl-3.0 | 2,210 | 0.001357 | import lxml.html as l
import requests
def key_char_parse(char_id):
url = 'https://vndb.org/c' + str(char_id)
page = requests.get(url)
root = l.fromstring(page.text)
name = root.cssselect('.mainbox h1')[0].text
kanji_name = root.cssselect('.mainbox h2.alttitle')[0].text
img = 'https:' + root.c... | value = []
for sp | an in row[1]:
if 'charspoil_1' in span.classes:
tag = 'minor spoiler'
elif 'charspoil_2' in span.classes:
tag = 'spoiler'
elif 'sexual' in span.classes:
... |
dmateusp/PokemonGo-Bot | pokemongo_bot/cell_workers/recycle_items.py | Python | mit | 5,073 | 0.002563 | import json
import os
from pokemongo_bot import inventory
from pokemongo_bot.base_dir import _base_dir
from pokemongo_bot.base_task import BaseTask
from pokemongo_bot.human_behaviour import action_delay
from pokemongo_bot.services.item_recycle_worker import ItemRecycler
from pokemongo_bot.tree_config_builder import Co... | config_item_name not in item_list.viewvalues():
| if config_item_name not in item_list:
raise ConfigException(
"item {} does not exist, spelling mistake? (check for valid item names in data/items.json)".format(
config_item_name))
def should_run(self):
"""
Returns ... |
WaveBlocks/WaveBlocks | src/tests/TestComplexMath.py | Python | bsd-3-clause | 2,776 | 0.010447 | """The WaveBlocks Project
Test the complex math functions.
@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011 R. Bourquin
@license: Modified BSD License
"""
from numpy import *
from matplotlib.pyplot import *
from WaveBlocks.ComplexMath import *
from WaveBlocks.Plot import plotcf
# Continuous complex angle... | o it "right"
z = cont_sqrt(y)
figure()
subplot(2,1,1)
plotcf(x, angle(y), abs(y))
plot(x, real(y), "-b")
plot(x, imag(y), "-g")
grid(True)
ylim([-2.1,2.1])
#xl | abel(r"$\phi$")
ylabel(r"$2 \cdot \exp(i \cdot \phi)$")
title(r"$z = r \cdot \exp(i \cdot \phi)$")
subplot(2,1,2)
plotcf(x, angle(z), abs(z))
plot(x, real(z), "-b")
plot(x, imag(z), "-g")
grid(True)
ylim([-2.1,2.1])
xlabel(r"$\phi$")
ylabel(r"$\sqrt{2 \cdot \exp(i \cdot \phi)}$")
title(r"$\sqrt{z} = \sqrt{r} \cdot \ex... |
jhesketh/zookeepr | alembic/versions/3b1b405d632e_.py | Python | gpl-2.0 | 705 | 0.009929 | """
* Add parent_id to ceiling
Revision ID: 3b1b405d632e
Revises: 1e6ca7fcff4a
Create Date: 2012-09-24 01:37:29.895286
"""
# revision identifiers, used by Alembic.
revision = '3b1b405d632e'
down_revision = '1e6ca7fcff4a'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generate... | ', sa.Integer(), nullable=True))
op.create_foreign_key(None, 'ceiling', 'ceiling', ['parent_id'], ['id'])
### end Alembic commands ###
de | f downgrade():
### commands auto generated by Alembic - please adjust! ###
op.drop_column('ceiling', 'parent_id')
### end Alembic commands ###
|
cgranade/qutip | qutip/qobj.py | Python | bsd-3-clause | 79,002 | 0.000114 | """The Quantum Object (Qobj) class, for representing quantum states and
operators, and related functions.
"""
__all__ = ['Qobj', 'qobj_list_evaluate', 'ptrace', 'dag', 'isequal',
'issuper', 'isoper', 'isoperket', 'isoperbra', 'isket', 'isbra',
'isherm', 'shape', 'dims']
import warnings
import ty... | f quantum object.
cosm()
Cosine of quantum object.
dag()
Adjoint (dagger) of quantum object.
dnorm()
Diamond norm of quantum operator.
dual_chan()
Dual channel of quantum object representing a CP map.
eigenenergies(sparse=False, sort='low', eigvals=0, tol=0, maxiter=1... | ergies (eigenvalues) of a quantum object.
eigenstates(sparse=False, sort='low', eigvals=0, tol=0, maxiter=100000)
Returns eigenenergies and eigenstates of quantum object.
expm()
Matrix exponential of quantum object.
full(order='C')
Returns dense array of quantum object `data` attribu... |
nlamirault/hyperion-lite | hyperiontests/test_grafana.py | Python | gpl-3.0 | 1,189 | 0 | # Copyright (C) 2014 Nicolas Lamirault <nicolas.lamirault@gmail.com>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... | ense
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from hyperiontests import hyperion
from hyperiontests import settings
class TestGrafana(hyperion.HyperionTestCase):
def setUp(self):
super(TestGrafana, self).setUp()
self._host = "http://%s:%s" % (settings.HYPERION_HOS... | ana/#/dashboard/file/default.json")
self.assertEqual(200, response.status_code)
|
sam-m888/gramps | gramps/cli/argparser.py | Python | gpl-2.0 | 23,180 | 0.001984 | # -*- coding: utf-8 -*-
#
# Gramps - a GTK+/GNOME based genealogy program
#
# Copyright (C) 2000-2006 Donald N. Allingham, A. Roitman
# Copyright (C) 2007-2009 B. Malengier
# Copyright (C) 2008 Lukasz Rymarczyk
# Copyright (C) 2008 Raphael Ackermann
# Copyright (C) 2008 Brian G. Matherly
# Copyright... | ions
-O, --open=FAMILY_TREE Open Family Tree
-U, --username=USERNAME Database username
-P, --password=PASSWORD Database password
-C, --create=FAMILY_TREE Create on open if new Famil | y Tree
-i, --import=FILENAME Import file
-e, --export=FILENAME Export file
-r, --remove=FAMILY_TREE_PATTERN Remove matching Family Tree(s) (use regular expressions)
-f, --format=FORMAT Specify Family Tree format
-a, --action=ACTION ... |
rudhir-upretee/SUMO_Src | tools/district/districtMapper.py | Python | gpl-3.0 | 5,678 | 0.002818 | #!/usr/bin/env python
"""
@file districtMapper.py
@author Daniel Krajzewicz
@date 2007-07-26
@version $Id: districtMapper.py 12567 2012-08-20 10:01:44Z dkrajzew $
<documentation missing>
SUMO, Simulation of Urban MObility; see http://sumo.sourceforge.net/
Copyright (C) 2007-2012 DLR (http://www.dlr.de/) and co... | es(self, junctions1):
ret = []
for junction in junctions1:
ret.append(self._xPos[junction])
return ret
def getJunctionYPoses(self, junctions1):
ret = []
for junction in junc | tions1:
ret.append(self._yPos[junction])
return ret
# All members are "private".
class DistrictMapper(handler.ContentHandler):
def __init__(self):
self._haveDistrict = False
self._parsingDistrictShape = False
self._districtShapes = {}
self._currentID = ""
... |
romanchyla/pylucene-trunk | samples/LuceneInAction/lia/advsearching/BooksLikeThis.py | Python | apache-2.0 | 3,039 | 0 | # ====================================================================
# 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 re... | reader = reader
self.searcher = IndexSearcher(reader)
def docsLike(self, id, doc, max):
authors = doc.getValues("author")
authorQuery = BooleanQuery()
for author in authors:
authorQuery.add(TermQuery(Term("author", author)),
BooleanClause.Occ... | authorQuery.setBoost(2.0)
vector = self.reader.getTermFreqVector(id, "subject")
subjectQuery = BooleanQuery()
for term in vector.getTerms():
tq = TermQuery(Term("subject", term))
subjectQuery.add(tq, BooleanClause.Occur.SHOULD)
likeThisQuery = BooleanQuery(... |
ecell/ecell3 | ecell/frontend/model-editor/plugins/ProcessSD.py | Python | lgpl-3.0 | 3,470 | 0.057637 | #::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
#
# This file is part of the E-Cell System
#
# Copyright (C) 1996-2016 Keio University
# Copyright (C) 2008-2016 RIKEN
# Copyright (C) 2005-2009 The Molecular Sciences Institute
#
#:::::::::::::::::::::::::::::::::::::::... | t under the terms of the GNU General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# E-Cell System is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTA... | th E-Cell System -- see the file COPYING.
# If not, write to the Free Software Foundation, Inc.,
# 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
#
#END_HEADER
import numpy as nu
from ecell.ui.model_editor.Constants import *
from ecell.ui.model_editor.ShapeDescriptor import *
SHAPE_PLUGIN_TYPE='Process' #... |
bzhou26/leetcode_sol | p210_Course_Schedule_II.py | Python | mit | 2,295 | 0.003922 | '''
- Leetcode problem: 210
- Difficulty: Medium
- Brief problem description:
There are a total of n courses you have to take, labeled from 0 to n-1.
Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1]
Given the total number of cour... | in_degree = {}
for p in prerequisites:
in_degree[p[0]] = in_degree.get(p[0], 0) + 1
dag[p[1]].append(p[0])
zero_dq = deque()
for i in range(numCourses):
if not in_degree.get(i):
zero_dq.append(i)
ordered_course = []
whil... | for c in nb:
in_degree[c] = in_degree.get(c) - 1
if in_degree[c] == 0:
zero_dq.append(c)
if len(ordered_course) == numCourses:
return ordered_course
else:
return []
|
fiam/blangoblog | settings.py | Python | bsd-3-clause | 3,700 | 0.002163 | #coding=utf-8
# Django settings for blog project.
from os.path import abspath, dirname, join
PROJECT_DIR = dirname(abspath(__file__))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@domain.com'),
)
MANAGERS = ADMINS
DATABASE_ENGINE = 'postgresql_psycopg2' # 'postgresql_psy... | set to the same as your
# system time zone.
TIME_ZONE = 'America/Chicago'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/langua | ge-identifiers.html
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# Absolute path to the directory that holds media.
# Example: "/home/media/media.lawrence.com/"
MEDIA_ROOT = ''
# URL that h... |
syncrase/pythonScriptTest | AgentSpecial.py | Python | gpl-2.0 | 617 | 0.024712 | from Personne import *
class AgentSpecial(Personne):
"""
Exemple d'héritage simple
--->>>> l'héritage multiple est possible
-> | hérite des exceptions
Classe définissant un agent spécial.
Elle hérite de la classe Personne"""
def __init__(self, nom, matricule):
"""Un agent se définit par son nom et son matricule"""
self.nom = nom
self.matricule = matricule
#Personne.__init__(self, nom)
def __str__(self... | lors d'une conversion de l'objet en chaîne"""
return "Agent {0}, matricule {1}".format(self.nom, self.matricule) |
eayunstack/python-neutronclient | neutronclient/tests/unit/qos/test_cli20_rule.py | Python | apache-2.0 | 1,542 | 0 | # Copyright 2015 Huawei Technologies India Pvt Ltd.
# 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
#
# ... | ype': 'bandwidth_limit',
'type': 'dscp_marking'}]
cmd = qos_rule.ListQoSRuleTypes(test_cli20.MyApp(sys.stdout),
None)
self._test_list_resources(resources, cmd, True,
response_contents=respon | se_contents,
cmd_resources=cmd_resources)
|
diyan/falcon_seed | run_app.py | Python | mit | 475 | 0.004211 | #!/usr/bin/env python
from __future__ import unicode_literals, absolute_import, division
# TODO werkzeug reloader may crash, search for more reliable solution
from werkzeug.serving import run_simple
from app import create_app
app = cr | eate_app()
if __ | name__ == '__main__':
#run_simple('127.0.0.1', 5000, api, use_debugger=True, use_reloader=True)
# Werkzeug reloader is not resilient to Python syntax error
run_simple('127.0.0.1', 5000, app, use_reloader=True) |
skiliks/internet-connection-breaker | icb.py | Python | apache-2.0 | 4,180 | 0.008579 | #! /usr/bin/python3
# -*- coding: utf-8 -*-
import getopt
impo | rt sys
import time
import datetime
import subprocess
connection_name = "Подключение по локальной сети"
#netsh interface set interface "Подключение по локальной сети" admin=DISABLED
#команда включения интернета
CONNECTION_ON = 'netsh interface set interface "' + connection_name + '" admin=ENABLED'
#команда выключения и... | разрыва увеличивается от нуля до ДР к концу волны
WAVE_TYPE_UP = "up"
#длительность разрыва уменьшается от ДР до нуля к концу волны
WAVE_TYPE_DOWN = "down"
#длительность разрыва нарастает от нуля к ДР (в середине волны) и спадает до нуля к концу
WAVE_TYPE_HEEL = "heel"
def main():
#константы по умолчанию
#кол... |
interlegis/saap | saap/core/migrations/0011_municipio_estado.py | Python | gpl-3.0 | 577 | 0.001733 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.13 on 2018-09-18 16:38
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0010_auto_20180918_1317'),
]
| operations = [
migrations.AddField(
model_name='municipio',
| name='estado',
field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='core.Estado', verbose_name='Estado'),
),
]
|
dahool/vertaal | djangoapp/templatetags/bbcodetag.py | Python | gpl-3.0 | 2,634 | 0.008352 | # -*- coding: utf-8 -*-
"""Copyright (c) 2009 Sergio Gabriel Teves
All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any... | late.Library()
@register.inclusion_tag('tags/smileysrender.html')
def smileyrender():
list = []
for item in settings.SMILEYS_PACK:
list.append({'code': item[0],'img': settings.SMILEYS_ROOT + item[1]})
return {'list': list}
@register.filter
def smiley(value):
img = '<img src="%s"/>'
... | % (settings.SMILEYS_ROOT + item[1]),value)
return mark_safe(value)
@register.filter
def bbcode(value):
"""
Generates (X)HTML from string with BBCode "markup".
By using the postmark lib from:
@see: http://code.google.com/p/postmarkup/
"""
try:
from postmarkup im... |
kyleaoman/simfiles | simfiles/_hdf5_io.py | Python | gpl-3.0 | 6,437 | 0.000311 | import h5py as h5py
import numpy as np
import multiprocessing
import os.path
class _hdf5_io():
def __init__(self, path, fbase, ncpu=0, interval=None):
self._path = path
self._fbase = fbase
self._parts = self._find_parts(self._path, self._fbase)
self._nb_cpu = multiprocessing.cpu_c... | "basename '{:s}' doesn't exist)".format(path, fbase))
def get_parts(self):
return self._parts
def hdf5_get(path, fbase, hpath, attr=None, ncpu=0, interval=None):
"""
Retrieve and assemble data from an hdf5 fileset.
Parameters
----------
path: str
Direc... | o gather, e.g. '/PartType1/ParticleIDs'
attr: str
Name of attribute to fetch (optional).
ncpu: int
Read in parallel with the given cpu count (default: 0 -> all cpus).
interval: tuple
Read a subset of a dataset in the given interval (2-tuple) of indices.
Returns
-------
... |
rossp/django-helpdesk | helpdesk/tasks.py | Python | bsd-3-clause | 129 | 0 | from celery.decorators import task
from | .email import process_email
@task()
def helpdesk_process_email | ():
process_email()
|
nickto/telegram-bot-aurora | settings.py | Python | mit | 4,919 | 0.003253 | #!/usr/bin/env python3
import datetime
import json
import os.path
SETTINGS_PATH = "./data/settings/settings.json"
DEFAULT_SETTINGS_PATH = "./default-settings.json"
def chat_settings_exist(chat_id, path=SETTINGS_PATH):
if os.path.isfile(path):
with open(path, "r") as settings_file:
settings = ... | ]["last"]["year"],
month=chat_settings["alert"][type]["last"]["month"],
| day=chat_settings["alert"][type]["last"]["day"],
hour=chat_settings["alert"][type]["last"]["hour"],
minute=chat_settings["alert"][type]["last"]["minute"],
second=chat_settings["alert"][type]["last"]["second"],
)
return last_alert_datetime
def update_last_sent(chat_settings, type, n... |
rhdedgar/openshift-tools | scripts/monitoring/cron-send-create-app.py | Python | apache-2.0 | 12,893 | 0.004266 | #!/usr/bin/env python
""" Create application check for v3 """
# We just want to see any exception that happens
# don't want the script to die under any cicumstances
# script must try | to clean itself up
# pylint: disable=broad-except
# main() function has a lot of setup and error handling
| # pylint: disable=too-many-statements
# main() function raises a captured exception if there is one
# pylint: disable=raising-bad-type
# Adding the ignore because it does not like the naming of the script
# to be different than the class name
# pylint: disable=invalid-name
import argparse
import datetime
import rand... |
sodhancha/Godown | godown/wsgi.py | Python | gpl-3.0 | 390 | 0 | """
WSGI config for godown project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on t | his file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "godown. | settings")
application = get_wsgi_application()
|
Haynie-Research-and-Development/jarvis | deps/lib/python3.4/site-packages/colorlog/tests/test_colorlog.py | Python | gpl-2.0 | 3,146 | 0.000954 | """Test the colorlog.colorlog module."""
import sys
import pytest
import colorlog
def test_colored_formatter(create_and_test_logger):
create_and_test_logger()
def test_custom_colors(create_and_test_logger):
"""Disable all colors and check no escape codes are output."""
create_a | nd_test_logger(
log_colors={}, reset=False,
validator=lambda line: '\x1b[' not in line)
def test_reset(create_and_test_logger):
create_and_test_logger(
reset=True, validator=lambda l: l.endswith('\x1b[0m'))
def test_no_reset(create_and_test_logger):
create_and_test_logger(
fm... | d with an escape code
validator=lambda line: not line.endswith('\x1b[0m'))
def test_secondary_colors(create_and_test_logger):
expected = ':\x1b[31mtest_secondary_colors:\x1b[34m'
create_and_test_logger(
fmt=(
"%(log_color)s%(levelname)s:"
"%(name_log_color)s%(name)s:"
... |
marmarek/anaconda | pyanaconda/ui/gui/spokes/welcome.py | Python | gpl-2.0 | 15,586 | 0.001989 | # Welcome spoke classes
#
# Copyright (C) 2011-2012 Red Hat, Inc.
#
# This copyrighted material is made available to anyone wishing to use,
# modify, copy, or redistribute it subject to the terms and conditions of
# the GNU General Public License v.2, or (at your option) any later version.
# This program is distribute... | n here
# to preselect the translation, when it's available.
territory = geoloc.get_territory_code(wait=True)
# bootopts and kickstart have priority over geoip
if self.data.lang.lang and self.data.lang.seen:
| locales = [self.data.lang.lang]
else:
locales = localization.get_territory_locales(territory) or [DEFAULT_LANG]
# get the data models
filter_store = self._languageStoreFilter
store = filter_store.get_model()
# get language codes for the locales
langs = [loca... |
esemin83/python_training | generator/contact.py | Python | apache-2.0 | 2,227 | 0.005388 | from model.group_address import Address_data
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f = "data/contacts.json... | andom_string("address", 20),
home_phone=random_numbers(10), mobile_phone=random_numbers(10), work_phone=random_numbers(10),
fax_phone=random_numbers(10), email_1=random_mail("@mail.ru", 10), email_2=random_mail("@mail.ru", 10),
home_page=random_string("page", 15))
... |
Address_data(firstname="firstname", middlename="middlename", lastname="lastname", nickname="nickname",
company="company", address="address", home_phone="7874177", mobile_phone="784541212",
work_phone="8776464321", fax_phone="874845421", email_1="321@mail.ru", email_2="123@mail.ru"... |
endlessm/chromium-browser | third_party/harfbuzz-ng/src/src/gen-use-table.py | Python | bsd-3-clause | 15,523 | 0.036655 | #!/usr/bin/env python3
# flake8: noqa
import io
import sys
if len (sys.argv) != 5:
print ("""usage: ./gen-use-table.py IndicSyllabicCategory.txt IndicPositionalCategory.txt UnicodeData.txt Blocks.txt
Input file, as of Unicode 12:
* https://unicode.org/Public/UCD/latest/ucd/IndicSyllabicCategory.txt
* https://unicod... | WEL_MODIFIER(U, UIS | C, UGC):
# https://github.com/harfbuzz/harfbuzz/issues/1102
# https://github.com/harfbuzz/harfbuzz/issues/1379
return U in [0x11046, 0x1134D]
def is_HALANT_NUM(U, UISC, UGC):
return UISC == Number_Joiner
def is_ZWNJ(U, UISC, UGC):
return UISC == Non_Joiner
def is_ZWJ(U, UISC, UGC):
return UISC == Joiner
def is_Wo... |
zstackorg/zstack-woodpecker | integrationtest/vm/simulator/iam2/test_iam2_project_basic_ops_image.py | Python | apache-2.0 | 7,449 | 0.00886 | '''
test iam2 image operations by platform admin/operator/member
# 1 create project
# 2 create virtual id (project admin/operator/member)
# 3 Add image with virtual id
# 4 delete
@author: quarkonics
'''
import os
import time
import zstackwoodpecker.test_util as test_util
import apibinding.inventory as inventory
impor... | 2_virtual_id(plain_user_name, plain_user_password,
project_uuid=project_uuid).uuid
# 3 add virtual id to project
iam2_ops.add_iam2_virtual_ids_to_project([plain_user_uuid],project_uuid)
# 4 login in project by plain user |
plain_user_session_uuid = iam2_ops.login_iam2_virtual_id(plain_user_name, plain_user_password)
# 4 login in project
#project_inv=iam2_ops.get_iam2_projects_of_virtual_id(plain_user_session_uuid)
project_login_uuid = iam2_ops.login_iam2_project(project_name, plain_user_session_uuid).uuid
# Image related ops:... |
rogerthat-platform/rogerthat-backend | src-test/rogerthat_tests/mobicage/models/test_compressed_int_list.py | Python | apache-2.0 | 2,303 | 0.002171 | # -*- coding: utf-8 -*-
# Copyright 2017 GIG Technology NV
#
# 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... | e.l + 5 * [0])[-10:] # [1, 0, 0, 0, 1, 0, 0, 0, 0, 0]
print 'Expected: %r' % expected
m.put()
m = M | yModel.get_by_key_name('test')
self.assertListEqual(expected, m.test)
|
lanyuwen/openthread | tools/harness-automation/cases_R140/leader_5_1_5.py | Python | bsd-3-clause | 1,876 | 0 | #!/usr/bin/env python
#
# Copyright (c) 2016, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# notic... | R
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT | NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADV... |
house4hack/openSHAC | web2py_shac/applications/enter/languages/it.py | Python | mit | 4,775 | 0.02308 | # coding: utf8
{
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" è un\'espressione opzionale come "campo1=\'nuovo valore\'". Non si può fare "update" o "delete" dei risultati di un JOIN ',
'%Y-%m-%d': '%d/%m/%Y',
'%Y-%m-%d %H:%M:%S': '%d/%m/%... | ,
' | cache': 'cache',
'change password': 'Cambia password',
'Online examples': 'Vedere gli esempi',
'Administrative interface': "Interfaccia amministrativa",
'customize me!': 'Personalizzami!',
'data uploaded': 'dati caricati',
'database': 'database',
'database %s select': 'database %s select',
'db': 'db',
'design': 'proget... |
etingof/pyasn1 | pyasn1/codec/ber/encoder.py | Python | bsd-2-clause | 28,322 | 0.00113 | #
# This file is part of pyasn1 software.
#
# Copyright (c) 2005-2020, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/pyasn1/license.html
#
import sys
from pyasn1 import debug
from pyasn1 import error
from pyasn1.codec.ber import eoo
from pyasn1.compat.integer import to_bytes
from pyasn1.compat.octets... | cit tags for inner chunks
if asn1Spec is None:
baseTag = | value.tagSet.baseTag
# strip off explicit tags
if baseTag:
tagSet = tag.TagSet(baseTag, baseTag)
else:
tagSet = tag.TagSet()
asn1Spec = value.clone(tagSet=tagSet)
elif not isOctetsType(value):
baseTag = asn1Spec.tag... |
krassowski/basic-particle-simulator | simulator/__init__.py | Python | bsd-3-clause | 25 | 0 | from simu | lation import * | |
GeHongpeng/PythonProject | DetectTables/DetectTablesFromImages.py | Python | gpl-3.0 | 9,252 | 0.004549 | # _*_ coding= utf-8 _*_
import sys
sys.path.append("/usr/local/Cellar/numpy/1.11.0/lib/python2.7/site-packages")
sys.path.append("/usr/local/Cellar/opencv/2.4.12_2/lib/python2.7/site-packages")
import numpy as np
import cv2
import json
import os
import re
#
targetFilePath = '/Users/gehongpeng/PycharmProjects/TableDe... | #
mergedContoursList.pop(j)
#
mergedContoursList.append((xNew, yNew, wNew, hNew))
break
#
if flag == False:
mergedContoursList.append(contoursList[i])
# draw rectangles on img
contourImage = img.c... | x1, y1, w, h = contour
cv2.rectangle(contourImage, (x1, y1), (x1 + w, y1 + h), (0, 255, 0), 1)
# save contour image
contourResultPath = resultFilePath + "contour/"
if not os.path.exists(contourResultPath):
os.makedirs(contourResultPath)
cv2.imwrite(contourResultP... |
vjh8mh/cs3240-labdemo | hello.py | Python | mit | 141 | 0.007092 | __author__ = 'Student'
from stuff import doub | le_message
from helper import greeting
greeting("hello")
greeting("hello | ")
greeting("hello")
|
Tithen-Firion/youtube-dl | youtube_dl/extractor/hark.py | Python | unlicense | 1,341 | 0.002237 | # coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
class HarkIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?hark\.com/clips/(?P<id>.+?)-.+'
_TEST = {
'url': 'http://www.hark.com/clips/mmbzyhkgny-obama-beyond-the-afghan-theater-we-only-target-al-qaeda-on-ma... | 'duration': 11,
}
}
def _real_extract(self, url):
video_id = self._match_id(url)
data = self._download_json(
'http://www.hark.com/clips/%s.json' % video_id, video_id)
return {
| 'id': video_id,
'url': data['url'],
'title': data['name'],
'description': data.get('description'),
'thumbnail': data.get('image_original'),
'duration': data.get('duration'),
}
|
cdhekne/My_Thesis | Thesis_WebCrawler/edx/edx/pipelines.py | Python | apache-2.0 | 257 | 0 | # Define your item pipeline | s here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class EdxPipeline(object):
def process_item(self, item, | spider):
return item
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.