code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
'''
shell_CMDs = {}
shell_CMDs[1] = 'netstat -n'
shell_CMDs[2] = "awk {'print $6'}"
'''
len = shell_CMDs.__len__()
p = {}
p[1] = subprocess.Popen(shlex.split(shell_CMDs[1]), stdout=subprocess.PIPE,stderr=subprocess.PIPE)
for i in range(2,len):
p[i] = subprocess.Po... | def pipe_shell_cmds(shell_CMDs) | shell_CMDs = {}
shell_CMDs[1] = 'netstat -n'
shell_CMDs[2] = "awk {'print $6'}" | 2.106136 | 1.781253 | 1.18239 |
all_terms = set([t for toks in tdocs for t in toks])
terms = set()
phrases = set()
for t in all_terms:
if gram_size(t) > 1:
phrases.add(t)
else:
terms.add(t)
# Identify candidates for redundant terms (1-gram terms found in a phrase)
redundant = set()... | def prune(tdocs) | Prune terms which are totally subsumed by a phrase
This could be better if it just removes the individual keywords
that occur in a phrase for each time that phrase occurs. | 3.67175 | 3.551227 | 1.033938 |
# latest class version and download link
args = (package_basedir, package_basedir, CLASS_VERSION, os.path.abspath(prefix))
command = 'sh %s/depends/install_class.sh %s %s %s' %args
ret = os.system(command)
if ret != 0:
raise ValueError("could not build CLASS v%s" %CLASS_VERSION) | def build_CLASS(prefix) | Function to dowwnload CLASS from github and and build the library | 7.355134 | 7.444802 | 0.987956 |
char_list = list(str(number))
length = len(char_list)
if length <= 3:
return number
result = ''
if length % 3 != 0:
while len(char_list) % 3 != 0:
c = char_list[0]
result += c
char_list.remove(c)
result += ','
i = 0
while len... | def format_number(number) | >>> format_number(1)
1
>>> format_number(22)
22
>>> format_number(333)
333
>>> format_number(4444)
'4,444'
>>> format_number(55555)
'55,555'
>>> format_number(666666)
'666,666'
>>> format_number(7777777)
'7,777,777' | 2.055445 | 2.136022 | 0.962277 |
index = url.rfind('page')
if index != -1:
result = url[0:index]
result += 'page=%s' % page_number
else:
result = url
result += '&page=%s' % page_number
return result | def generate_key(url, page_number) | >>> url_a = 'http://localhost:5009/search?keywords=a'
>>> generate_key(url_a, 10)
'http://localhost:5009/search?keywords=a&page=10'
>>> url_b = 'http://localhost:5009/search?keywords=b&page=1'
>>> generate_key(url_b, 10)
'http://localhost:5009/search?keywords=b&page=10' | 2.696691 | 2.890852 | 0.932836 |
pagination = {'start': 1, 'end': PAGE_SIZE, 'current': current_page_num}
if total_page_num <= PAGE_SIZE:
pagination['end'] = total_page_num
else:
# base on front four and back five
pagination['start'] = current_page_num - 4
pagination['end'] = current_page_num + 5
... | def generate_pagination(total_page_num, current_page_num) | >>> PAGE_SIZE = 10
>>> generate_pagination(total_page_num=9, current_page_num=1)
{'start': 1, 'end': 9, 'current': 1}
>>> generate_pagination(total_page_num=20, current_page_num=12)
{'start': 8, 'end': 17, 'current': 12}
>>> generate_pagination(total_page_num=20, current_page_num=4)
{'start': 1,... | 2.168034 | 2.153745 | 1.006634 |
# Prepare font.
font_family = 'arial'
font = Font(font_family, bold=True)
if not font:
raise RuntimeError('No font found for %r' % font_family)
# Initialize PDF document on a stream.
with Document('output.pdf') as document:
# Initialize a new page and begin its context.
... | def main(filename) | Creates a PDF by embedding the first page from the given image and
writes some text to it.
@param[in] filename
The source filename of the image to embed. | 4.790123 | 4.610879 | 1.038874 |
method, url = get_URL('login')
payload = {
'apikey': self.config.get('apikey'),
'username': self.username,
'password': password,
'source': 'Desktop'
}
res = getattr(self.session, method)(url, params=payload)
if res.s... | def login(self, password) | Login to filemail as the current user.
:param password:
:type password: ``str`` | 4.872898 | 5.189201 | 0.939046 |
# Check if all transfers are complete before logout
self.transfers_complete
payload = {
'apikey': self.config.get('apikey'),
'logintoken': self.session.cookies.get('logintoken')
}
method, url = get_URL('logout')
res = getattr(self.s... | def logout(self) | Logout of filemail and closing the session. | 5.487619 | 5.220845 | 1.051098 |
for transfer in self.transfers:
if not transfer.is_complete:
error = {
'errorcode': 4003,
'errormessage': 'You must complete transfer before logout.'
}
hellraiser(error) | def transfers_complete(self) | Check if all transfers are completed. | 9.551641 | 8.152093 | 1.17168 |
method, url = get_URL('get_sent')
payload = {
'apikey': self.session.cookies.get('apikey'),
'logintoken': self.session.cookies.get('logintoken'),
'getexpired': expired,
'getforallusers': for_all
}
res = getattr(self.session,... | def get_sent(self, expired=False, for_all=False) | Retreve information on previously sent transfers.
:param expired: Whether or not to return expired transfers.
:param for_all: Get transfers for all users.
Requires a Filemail Business account.
:type for_all: bool
:type expired: bool
:rtype: ``list`` of :class:`pyfilemai... | 5.292348 | 5.009604 | 1.05644 |
method, url = get_URL('user_get')
payload = {
'apikey': self.config.get('apikey'),
'logintoken': self.session.cookies.get('logintoken')
}
res = getattr(self.session, method)(url, params=payload)
if res.status_code == 200:
setti... | def get_user_info(self, save_to_config=True) | Get user info and settings from Filemail.
:param save_to_config: Whether or not to save settings to config file
:type save_to_config: ``bool``
:rtype: ``dict`` containig user information and default settings. | 4.124341 | 4.155388 | 0.992528 |
if kwargs:
self.config.update(kwargs)
method, url = get_URL('user_update')
res = getattr(self.session, method)(url, params=self.config)
if res.status_code == 200:
return True
hellraiser(res) | def update_user_info(self, **kwargs) | Update user info and settings.
:param \*\*kwargs: settings to be merged with
:func:`User.get_configfile` setings and sent to Filemail.
:rtype: ``bool`` | 5.938101 | 5.84316 | 1.016248 |
method, url = get_URL('received_get')
if age:
if not isinstance(age, int) or age < 0 or age > 90:
raise FMBaseError('Age must be <int> between 0-90')
past = datetime.utcnow() - timedelta(days=age)
age = timegm(past.utctimetuple())
... | def get_received(self, age=None, for_all=True) | Retrieve a list of transfers sent to you or your company
from other people.
:param age: between 1 and 90 days.
:param for_all: If ``True`` will return received files for
all users in the same business. (Available for business account
members only).
:type age: ``int``
... | 5.105049 | 4.924928 | 1.036573 |
transfers = []
for transfer_data in response.json()['transfers']:
transfer = Transfer(self, _restore=True)
transfer.transfer_info.update(transfer_data)
transfer.get_files()
transfers.append(transfer)
return transfers | def _restore_transfers(self, response) | Restore transfers from josn retreived Filemail
:param response: response object from request
:rtype: ``list`` with :class:`Transfer` objects | 4.315188 | 4.282083 | 1.007731 |
contacts = self.get_contacts()
for contact in contacts:
if contact['email'] == email:
return contact
msg = 'No contact with email: "{email}" found.'
raise FMBaseError(msg.format(email=email)) | def get_contact(self, email) | Get Filemail contact based on email.
:param email: address of contact
:type email: ``str``, ``unicode``
:rtype: ``dict`` with contact information | 3.849825 | 3.9817 | 0.96688 |
if not isinstance(contact, dict):
raise AttributeError('contact must be a <dict>')
method, url = get_URL('contacts_update')
payload = {
'apikey': self.config.get('apikey'),
'logintoken': self.session.cookies.get('logintoken'),
'contacti... | def update_contact(self, contact) | Update name and/or email for contact.
:param contact: with updated info
:type contact: ``dict``
:rtype: ``bool`` | 3.702374 | 3.593777 | 1.030218 |
groups = self.get_groups()
for group in groups:
if group['contactgroupname'] == name:
return group
msg = 'No group named: "{name}" found.'
raise FMBaseError(msg.format(name=name)) | def get_group(self, name) | Get contact group by name
:param name: name of group
:type name: ``str``, ``unicode``
:rtype: ``dict`` with group data | 5.14281 | 4.74408 | 1.084048 |
group = self.get_group(name)
method, url = get_URL('group_delete')
payload = {
'apikey': self.config.get('apikey'),
'logintoken': self.session.cookies.get('logintoken'),
'contactgroupid': group['contactgroupid']
}
res = getattr... | def delete_group(self, name) | Delete contact group
:param name: of group
:type name: ``str``, ``unicode``
:rtype: ``bool`` | 4.526685 | 4.441491 | 1.019181 |
if isinstance(group, basestring):
group = self.get_contact(group)
method, url = get_URL('group_update')
payload = {
'apikey': self.config.get('apikey'),
'logintoken': self.session.cookies.get('logintoken'),
'contactgroupid': group['cont... | def rename_group(self, group, newname) | Rename contact group
:param group: group data or name of group
:param newname: of group
:type group: ``str``, ``unicode``, ``dict``
:type newname: ``str``, ``unicode``
:rtype: ``bool`` | 4.266468 | 4.019211 | 1.061519 |
if isinstance(contact, basestring):
contact = self.get_contact(contact)
if isinstance(group, basestring):
group = self.get_group(group)
method, url = get_URL('contacts_add_to_group')
payload = {
'apikey': self.config.get('apikey'),
... | def add_contact_to_group(self, contact, group) | Add contact to group
:param contact: name or contact object
:param group: name or group object
:type contact: ``str``, ``unicode``, ``dict``
:type group: ``str``, ``unicode``, ``dict``
:rtype: ``bool`` | 3.274155 | 3.118195 | 1.050016 |
method, url = get_URL('company_get')
payload = {
'apikey': self.config.get('apikey'),
'logintoken': self.session.cookies.get('logintoken')
}
res = getattr(self.session, method)(url, params=payload)
if res.status_code == 200:
re... | def get_company_info(self) | Get company settings from Filemail
:rtype: ``dict`` with company data | 5.037606 | 5.036184 | 1.000282 |
if not isinstance(company, dict):
raise AttributeError('company must be a <dict>')
method, url = get_URL('company_update')
payload = {
'apikey': self.config.get('apikey'),
'logintoken': self.session.cookies.get('logintoken')
}
... | def update_company(self, company) | Update company settings
:param company: updated settings
:type company: ``dict``
:rtype: ``bool`` | 4.381846 | 4.373724 | 1.001857 |
users = self.get_company_users()
for user in users:
if user['email'] == email:
return user
msg = 'No user with email: "{email}" associated with this company.'
raise FMBaseError(msg.format(email=email)) | def get_company_user(self, email) | Get company user based on email.
:param email: address of contact
:type email: ``str``, ``unicode``
:rtype: ``dict`` with contact information | 4.177105 | 4.216835 | 0.990578 |
method, url = get_URL('company_add_user')
payload = {
'apikey': self.config.get('apikey'),
'logintoken': self.session.cookies.get('logintoken'),
'email': email,
'name': name,
'password': password,
'canreceivefiles': recei... | def company_add_user(self, email, name, password, receiver, admin) | Add a user to the company account.
:param email:
:param name:
:param password: Pass without storing in plain text
:param receiver: Can user receive files
:param admin:
:type email: ``str`` or ``unicode``
:type name: ``str`` or ``unicode``
:type password: ... | 4.0267 | 3.817498 | 1.054801 |
if not isinstance(userdata, dict):
raise AttributeError('userdata must be a <dict>')
method, url = get_URL('company_update_user')
payload = {
'apikey': self.config.get('apikey'),
'logintoken': self.session.cookies.get('logintoken'),
'us... | def update_company_user(self, email, userdata) | Update a company users settings
:param email: current email address of user
:param userdata: updated settings
:type email: ``str`` or ``unicode``
:type userdata: ``dict``
:rtype: ``bool`` | 4.027988 | 4.212899 | 0.956109 |
cage_list = Animal.objects.values("Cage").distinct()
cage_list_current = cage_list.filter(Alive=True)
animal_list = Animal.objects.all()
animal_list_current = animal_list.filter(Alive=True)
strain_list = animal_list.values("Strain").distinct()
strain_list_current = animal_list_current.value... | def home(request) | This view generates the data for the home page.
This login restricted view passes dictionaries containing the current cages, animals and strains as well as the totals for each. This data is passed to the template home.html | 1.951311 | 1.706517 | 1.143447 |
# type: () -> defaultdict
_widths = defaultdict(int)
all_rows = [self.headers]
all_rows.extend(self._rows)
for row in all_rows:
for idx, col in enumerate(row):
_col_l = len(col)
if _col_l > _widths[idx]:
_... | def col_widths(self) | Get MAX possible width of each column in the table.
:return: defaultdict | 3.143681 | 3.282338 | 0.957756 |
# type: () -> str
output = ''
for col in sorted(self.col_widths):
line = self.COLUMN_MARK + (self.DASH * (self.col_widths[col] + self.PADDING * 2))
output += line
output += self.COLUMN_MARK + '\n'
return output | def _marker_line(self) | Generate a correctly sized marker line.
e.g.
'+------------------+---------+----------+---------+'
:return: str | 5.137084 | 5.706378 | 0.900236 |
# type: (List[str]) -> str
_row_text = ''
for col, width in self.col_widths.items():
_row_text += self.COLUMN_SEP
l_pad, r_pad = self._split_int(width - len(row[col]))
_row_text += '{0}{1}{2}'.format(' ' * (l_pad + self.PADDING),
... | def _row_to_str(self, row) | Converts a list of strings to a correctly spaced and formatted
row string.
e.g.
['some', 'foo', 'bar'] --> '| some | foo | bar |'
:param row: list
:return: str | 3.244499 | 3.65773 | 0.887025 |
# type: () -> str
_marker_line = self._marker_line()
output = _marker_line + self._row_to_str(self.headers) + _marker_line
for row in self._rows:
output += self._row_to_str(row)
output += _marker_line
return output | def _table_to_str(self) | Return single formatted table string.
:return: str | 3.396052 | 3.855977 | 0.880724 |
t1, t2 = list(s1), list(s2)
l1, l2 = len(t1), len(t2)
if not s1:
return l2
if not s2:
return l1
# Cursors for each string
c1, c2 = 0, 0
# Largest common subsequence
lcss = 0
# Local common substring
local_cs = 0
# Number of transpositions ('ab' vs '... | def sift4(s1, s2, max_offset=5) | This is an implementation of general Sift4. | 2.277314 | 2.270687 | 1.002919 |
'''The slug field is auto-populated during the save from the name field.'''
if not self.id:
self.slug = slugify(self.name)
super(Cohort, self).save(*args, **kwargs) | def save(self, *args, **kwargs) | The slug field is auto-populated during the save from the name field. | 5.825425 | 2.728652 | 2.13491 |
filenames = sorted(filenames, reverse=True) # e.g., v2 before v1
for priority in sorted(self.rules.keys(), reverse=True):
patterns = self.rules[priority]
for pattern in patterns:
for filename in filenames:
if pattern.search(filename):... | def pick(self, filenames: Iterable[str]) -> str | Pick one filename based on priority rules. | 4.441654 | 3.221765 | 1.37864 |
print('Counting terms...')
results = parallel(count_tf, tokens_stream, n_jobs=-1)
print('Merging...')
tf = merge(results)
if out is not None:
with open(out, 'w') as f:
json.dump(tf, f)
return tf | def train_tf(tokens_stream, out=None, **kwargs) | Train a map of term frequencies on a list of files (parallelized). | 3.727245 | 3.139188 | 1.187328 |
tf = defaultdict(int)
for tokens in tokens_stream:
for token in tokens:
tf[token] += 1
return tf | def count_tf(tokens_stream) | Count term frequencies for a single file. | 2.181966 | 1.999439 | 1.091289 |
if "discovery" not in config:
raise ValueError("No discovery method defined.")
installed_balancers = Balancer.get_installed_classes().keys()
if not any([balancer in config for balancer in installed_balancers]):
raise ValueError("No available balancer configs de... | def validate_config(cls, config) | Validates a config dictionary parsed from a cluster config file.
Checks that a discovery method is defined and that at least one of
the balancers in the config are installed and available. | 9.268432 | 5.829453 | 1.589931 |
self.discovery = config["discovery"]
self.meta_cluster = config.get("meta_cluster")
for balancer_name in Balancer.get_installed_classes().keys():
if balancer_name in config:
setattr(self, balancer_name, config[balancer_name]) | def apply_config(self, config) | Sets the `discovery` and `meta_cluster` attributes, as well as the
configured + available balancer attributes from a given validated
config. | 5.94865 | 3.128489 | 1.901445 |
args = parser.parse_args(args[1:])
where_queries = []
params = {}
if args.watching or args.available:
where_queries.append('regexp IS NOT NULL')
if args.query:
where_queries.append('title LIKE :title')
params['title'] = _compile_sql_query(args.query)
if not where_qu... | def command(state, args) | Search Animanager database. | 4.286659 | 4.098425 | 1.045928 |
if os.path.exists(filepath): # Could be broken symlink
extension = os.path.splitext(filepath)[1]
return extension in ('.mkv', '.mp4', '.avi')
else:
return False | def _is_video(filepath) -> bool | Check filename extension to see if it's a video file. | 4.178118 | 3.212088 | 1.300748 |
for dirpath, dirnames, filenames in os.walk(dirpath, topdown=True,
followlinks=True):
if os.path.basename(dirpath).startswith('.'):
del dirnames[:]
for filename in filenames:
yield os.path.join(dirpath, filename) | def _find_files(dirpath: str) -> 'Iterable[str]' | Find files recursively.
Returns a generator that yields paths in no particular order. | 2.286686 | 2.324541 | 0.983715 |
name = socket.getfqdn()
ip = socket.gethostbyname(name)
return cls(name, ip) | def current(cls) | Helper method for getting the current peer of whichever host we're
running on. | 4.957308 | 5.039008 | 0.983787 |
return json.dumps({
"name": self.name,
"ip": self.ip,
"port": self.port
}, sort_keys=True) | def serialize(self) | Serializes the Peer data as a simple JSON map string. | 3.274526 | 2.384969 | 1.372985 |
parsed = json.loads(value)
if "name" not in parsed:
raise ValueError("No peer name.")
if "ip" not in parsed:
raise ValueError("No peer IP.")
if "port" not in parsed:
parsed["port"] = DEFAULT_PEER_PORT
return cls(parsed["name"], parse... | def deserialize(cls, value) | Generates a Peer instance via a JSON string of the sort generated
by `Peer.deserialize`.
The `name` and `ip` keys are required to be present in the JSON map,
if the `port` key is not present the default is used. | 2.611932 | 2.053325 | 1.27205 |
if isinstance(obj, np.ndarray):
data_b64 = base64.b64encode(obj.data).decode('utf-8')
return dict(__ndarray__=data_b64,
dtype=str(obj.dtype),
shape=obj.shape)
elif sps.issparse(obj):
data_b64 = base64.b64encode(... | def default(self, obj) | if input object is a ndarray it will be converted into a dict holding dtype, shape and the data base64 encoded | 1.730924 | 1.571617 | 1.101365 |
# type: (str, List[str]) -> str
try:
return [l[len(tag):] for l in self.meta_data if l.startswith(tag)][0]
except IndexError:
return '* Not Found *' | def _extract_meta_value(self, tag) | Find a target value by `tag` from given meta data.
:param tag: str
:param meta_data: list
:return: str | 5.107881 | 6.39668 | 0.798521 |
available_reader_list = []
module_dir = os.path.realpath(os.path.dirname(__file__))
module_names = filter(
lambda x: x.endswith('_reader.py'), os.listdir(module_dir))
for module_name in module_names:
markup = module_name.split('_')[0]
reader = get_reader(markup=markup)
... | def get_markup_choices() | Receives available markup options as list. | 3.120289 | 3.003728 | 1.038806 |
self.hosts = config["hosts"]
old_base_path = self.base_path
self.base_path = config["path"]
if not self.connected.is_set():
return
logger.debug("Setting ZK hosts to %s", self.hosts)
self.client.set_hosts(",".join(self.hosts))
if old_base_pat... | def apply_config(self, config) | Takes the given config dictionary and sets the hosts and base_path
attributes.
If the kazoo client connection is established, its hosts list is
updated to the newly configured value. | 4.970398 | 3.876407 | 1.282218 |
self.client = client.KazooClient(hosts=",".join(self.hosts))
self.client.add_listener(self.handle_connection_change)
self.client.start_async() | def connect(self) | Creates a new KazooClient and establishes a connection.
Passes the client the `handle_connection_change` method as a callback
to fire when the Zookeeper connection changes state. | 4.720167 | 3.12947 | 1.508296 |
logger.info("Disconnecting from Zookeeper.")
self.client.stop()
self.client.close() | def disconnect(self) | Stops and closes the kazoo connection. | 5.861669 | 3.580182 | 1.637254 |
if state == client.KazooState.LOST:
if not self.shutdown.is_set():
logger.info("Zookeeper session lost!")
self.connected.clear()
elif state == client.KazooState.SUSPENDED:
logger.info("Zookeeper connection suspended!")
self.connect... | def handle_connection_change(self, state) | Callback for handling changes in the kazoo client's connection state.
If the connection becomes lost or suspended, the `connected` Event
is cleared. Other given states imply that the connection is
established so `connected` is set. | 2.840587 | 2.338124 | 1.2149 |
logger.debug("starting to watch cluster %s", cluster.name)
wait_on_any(self.connected, self.shutdown)
logger.debug("done waiting on (connected, shutdown)")
znode_path = "/".join([self.base_path, cluster.name])
self.stop_events[znode_path] = threading.Event()
de... | def start_watching(self, cluster, callback) | Initiates the "watching" of a cluster's associated znode.
This is done via kazoo's ChildrenWatch object. When a cluster's
znode's child nodes are updated, a callback is fired and we update
the cluster's `nodes` attribute based on the existing child znodes
and fire a passed-in callback ... | 3.036545 | 2.707846 | 1.121388 |
znode_path = "/".join([self.base_path, cluster.name])
if znode_path in self.stop_events:
self.stop_events[znode_path].set() | def stop_watching(self, cluster) | Causes the thread that launched the watch of the cluster path
to end by setting the proper stop event found in `self.stop_events`. | 4.175066 | 3.027657 | 1.378976 |
wait_on_any(self.connected, self.shutdown)
node = Node.current(service, port)
path = self.path_of(service, node)
data = node.serialize().encode()
znode = self.client.exists(path)
if not znode:
logger.debug("ZNode at %s does not exist, creating new... | def report_up(self, service, port) | Report the given service's present node as up by creating/updating
its respective znode in Zookeeper and setting the znode's data to
the serialized representation of the node.
Waits for zookeeper to be connected before taking any action. | 3.607991 | 3.139972 | 1.149052 |
wait_on_any(self.connected, self.shutdown)
node = Node.current(service, port)
path = self.path_of(service, node)
try:
logger.debug("Deleting znode at %s", path)
self.client.delete(path)
except exceptions.NoNodeError:
pass | def report_down(self, service, port) | Reports the given service's present node as down by deleting the
node's znode in Zookeeper if the znode is present.
Waits for the Zookeeper connection to be established before further
action is taken. | 6.307225 | 4.888663 | 1.290174 |
return "/".join([self.base_path, service.name, node.name]) | def path_of(self, service, node) | Helper method for determining the Zookeeper path for a given cluster
member node. | 5.461053 | 4.911972 | 1.111784 |
if not user.is_authenticated() or not hasattr(obj, '_ratings_field'):
return False
ratings_descriptor = getattr(obj, obj._ratings_field)
try:
rating = ratings_descriptor.get(user=user).score
except ratings_descriptor.model.DoesNotExist:
rating = None
return rating | def rating_score(obj, user) | Returns the score a user has given an object | 3.343137 | 3.376776 | 0.990038 |
return reverse('ratings_rate_object', args=(
ContentType.objects.get_for_model(obj).pk,
obj.pk,
score,
)) | def rate_url(obj, score=1) | Generates a link to "rate" the given object with the provided score - this
can be used as a form target or for POSTing via Ajax. | 3.680907 | 4.175473 | 0.881555 |
return reverse('ratings_unrate_object', args=(
ContentType.objects.get_for_model(obj).pk,
obj.pk,
)) | def unrate_url(obj) | Generates a link to "un-rate" the given object - this
can be used as a form target or for POSTing via Ajax. | 3.933592 | 4.12146 | 0.954417 |
args = parser.parse_args(args[1:])
aid = state.results.parse_aid(args.aid, default_key='db')
query.update.reset(state.db, aid, args.episode) | def command(state, args) | Reset anime watched episodes. | 13.112599 | 9.57998 | 1.36875 |
prevstate = agent.cancel(project_name, job_id)['prevstate']
if prevstate == 'pending':
sqllite_agent.execute(ScrapydJobExtInfoSQLSet.DELETE_BY_ID, (job_id,)) | def cancel_job(agent, project_name, job_id) | cancel a job.
If the job is pending, it will be removed. If the job is running, it will be terminated. | 13.753421 | 12.657027 | 1.086623 |
ext_info = sqllite_agent.execute(ScrapydJobExtInfoSQLSet.SELECT_BY_ID, (job_lsit_DO.job_id,))
if ext_info is None or len(ext_info) <= 0: return
ext_info = ext_info[0]
job_lsit_DO.args = ext_info[1]
job_lsit_DO.priority = ext_info[2]
job_lsit_DO.creation_time = ext_info[3]
job_lsit_DO.lo... | def packing_job_ext_info(job_lsit_DO) | Packing additional information of the job into the job_list_DO(JobListDO) | 3.010172 | 2.976388 | 1.011351 |
project_list = agent.get_project_list()
if project_list['status'] == 'error':
raise ScrapydTimeoutException
project_list = project_list['projects']
pending_job_list = []
running_job_list = []
finished_job_list = []
for project_name in project_list:
job_list = agent.get_j... | def get_all_job_list(agent) | Get all job list by each project name then
return three job list on the base of different status(pending,running,finished). | 1.771885 | 1.689278 | 1.048901 |
job_list = agent.get_job_list(project_name)
pending_job_list = job_list['pending']
running_job_list = job_list['running']
finished_job_list = job_list['finished']
job_amounts = {}
if spider_name is None:
job_amounts['pending'] = len(pending_job_list)
job_amounts['running'] =... | def get_job_amounts(agent, project_name, spider_name=None) | Get amounts that pending job amount, running job amount, finished job amount. | 1.364747 | 1.297527 | 1.051806 |
'''Convert a CORBA CosNaming.Name to a string.'''
parts = []
if type(name) is not list and type(name) is not tuple:
raise NotCORBANameError(name)
if len(name) == 0:
raise NotCORBANameError(name)
for nc in name:
if not nc.kind:
parts.append(nc.id)
else:
... | def corba_name_to_string(name) | Convert a CORBA CosNaming.Name to a string. | 3.319065 | 3.142209 | 1.056284 |
'''Reparse all children of this directory.
This effectively rebuilds the tree below this node.
This operation takes an unbounded time to complete; if there are a lot
of objects registered below this directory's context, they will all
need to be parsed.
'''
self... | def reparse(self) | Reparse all children of this directory.
This effectively rebuilds the tree below this node.
This operation takes an unbounded time to complete; if there are a lot
of objects registered below this directory's context, they will all
need to be parsed. | 14.490912 | 2.703105 | 5.36084 |
'''Unbind an object from the context represented by this directory.
Warning: this is a dangerous operation. You may unlink an entire
section of the tree and be unable to recover it. Be careful what you
unbind.
The name should be in the format used in paths. For example,
... | def unbind(self, name) | Unbind an object from the context represented by this directory.
Warning: this is a dangerous operation. You may unlink an entire
section of the tree and be unable to recover it. Be careful what you
unbind.
The name should be in the format used in paths. For example,
'manager.m... | 10.097637 | 2.723748 | 3.707258 |
if self.n_jobs == 1:
return [self._tokenize(doc) for doc in docs]
else:
return parallel(self._tokenize, docs, self.n_jobs) | def tokenize(self, docs) | Tokenizes a document, using a lemmatizer.
Args:
| doc (str) -- the text document to process.
Returns:
| list -- the list of tokens. | 2.646935 | 3.584625 | 0.738413 |
code = Code.get_from_string(codelabel)
# set up calculation
calc = code.new_calc()
calc.label = "compute rips from distance matrix"
calc.set_max_wallclock_seconds(1 * 60)
calc.set_withmpi(False)
calc.set_resources({"num_machines": 1, "num_mpiprocs_per_machine": 1})
# Prepare input... | def main(codelabel, submit) | Command line interface for testing and submitting calculations.
This script extends submit.py, adding flexibility in the selected code/computer.
Run './cli.py --help' to see options. | 3.441988 | 3.476648 | 0.990031 |
args = parser.parse_args(args[1:])
aid = state.results.parse_aid(args.aid, default_key='db')
if args.query:
# Use regexp provided by user.
regexp = '.*'.join(args.query)
else:
# Make default regexp.
title = query.select.lookup(state.db, aid, fields=['title']).title
... | def command(state, args) | Register watching regexp for an anime. | 5.659237 | 5.250521 | 1.077843 |
self.table(table)
self.add_columns(*table.columns.get_with_version(version))
return self | def from_definition(self, table: Table, version: int) | Add all columns from the table added in the specified version | 8.727041 | 5.212247 | 1.674334 |
if keyBitLength not in ACCEPTABLE_KEY_LENGTHS:
raise Exception("keyBitLength must be 128, 192, or 256")
self.bitlen = keyBitLength
if len(rawKey) <= 0 or len(rawKey) > self.bitlen/8:
raise Exception("rawKey must be less than or equal to keyBitLength/8 (%d) characters long" % (self.bitlen/8)... | def keygen(self, keyBitLength, rawKey) | This must be called on the object before any encryption or
decryption can take place. Provide it the key bit length,
which must be 128, 192, or 256, and the key, which may be a
sequence of bytes or a simple string.
Does not return any value.
Raises an exception if the arguments are not sane. | 3.253376 | 3.161953 | 1.028914 |
encryptedResult = ''
for index in range(0, len(plainText), BLOCK_SIZE):
block = plainText[index:index + BLOCK_SIZE]
# Pad to required length if needed
if len(block) < BLOCK_SIZE:
block = zero_pad(block, BLOCK_SIZE)
encryptedResult += self.encrypt_block(block)
return encr... | def encrypt(self, plainText) | Encrypt an arbitrary-length block of data.
NOTE: This function formerly worked only on 16-byte blocks of `plainText`.
code that assumed this should still work fine, but can optionally be
modified to call `encrypt_block` instead.
Args:
plainText (str): data to encrypt. If the data is not a mult... | 3.161025 | 3.311641 | 0.954519 |
decryptedResult = ''
for index in range(0, len(cipherText), BLOCK_SIZE):
block = cipherText[index:index + BLOCK_SIZE]
# Pad to required length if needed
if len(block) < BLOCK_SIZE:
block = zero_pad(block, BLOCK_SIZE)
decryptedResult += self.decrypt_block(block)
return de... | def decrypt(self, cipherText) | Decrypt an arbitrary-length block of data.
NOTE: This function formerly worked only on 16-byte blocks of `cipherText`.
code that assumed this should still work fine, but can optionally be
modified to call `decrypt_block` instead.
Args:
cipherText (str): data to decrypt. If the data is not a mu... | 3.101268 | 3.406343 | 0.910439 |
if not self.initialized:
raise TypeError("CamCrypt object has not been initialized")
if len(plainText) != BLOCK_SIZE:
raise ValueError("plainText must be %d bytes long (received %d bytes)" %
(BLOCK_SIZE, len(plainText)))
cipher = ctypes.create_string_buffer(BLOCK_SIZE... | def encrypt_block(self, plainText) | Encrypt a 16-byte block of data.
NOTE: This function was formerly called `encrypt`, but was changed when
support for encrypting arbitrary-length strings was added.
Args:
plainText (str): 16-byte data.
Returns:
16-byte str.
Raises:
TypeError if CamCrypt object has not been... | 4.466871 | 3.485897 | 1.281412 |
if not self.initialized:
raise TypeError("CamCrypt object has not been initialized")
if len(cipherText) != BLOCK_SIZE:
raise ValueError("cipherText must be %d bytes long (received %d bytes)" %
(BLOCK_SIZE, len(cipherText)))
plain = ctypes.create_string_buffer(BLOCK_SI... | def decrypt_block(self, cipherText) | Decrypt a 16-byte block of data.
NOTE: This function was formerly called `decrypt`, but was changed when
support for decrypting arbitrary-length strings was added.
Args:
cipherText (str): 16-byte data.
Returns:
16-byte str.
Raises:
TypeError if CamCrypt object has not bee... | 4.658422 | 3.605082 | 1.292182 |
lock.acquire()
try:
if key not in backup:
backup[key] = {}
if key in fail_times and fail_times[key] % app.config[MAX_FAILURE_TIMES] == 0:
logger.error(
'<SERVER KEY %s> At present already reaching the upper limit of the max failure times, failure time... | def use_backup_if_fail(app, key) | Return a error flag for prompt message in front-end if failure times (unceasing fail)
greater than max failure times else return backup data (latest data in the cache) | 6.561727 | 5.95761 | 1.101403 |
lock.acquire()
try:
if key not in sleep_record:
return False
return time.time() < sleep_record[key]
finally:
lock.release() | def is_sleep(key) | Determine return data by use cache if this key is in the sleep time window(happened error) | 2.979656 | 2.983861 | 0.998591 |
args = parser.parse_args(args[1:])
if args.watching:
rows = query.select.select(state.db, 'regexp IS NOT NULL', [], ['aid'])
aids = [anime.aid for anime in rows]
elif args.incomplete:
rows = query.select.select(state.db, 'enddate IS NULL', [], ['aid'])
aids = [anime.aid ... | def command(state, args) | Add an anime from an AniDB search. | 3.541323 | 3.329427 | 1.063643 |
version = self.get_version()
command = [
"haproxy",
"-f", self.config_file_path, "-p", self.pid_file_path
]
if version and version >= (1, 5, 0):
command.extend(["-L", self.peer.name])
if os.path.exists(self.pid_file_path):
... | def restart(self) | Performs a soft reload of the HAProxy process. | 3.380098 | 3.16304 | 1.068623 |
command = ["haproxy", "-v"]
try:
output = subprocess.check_output(command)
version_line = output.split("\n")[0]
except subprocess.CalledProcessError as e:
logger.error("Could not get HAProxy version: %s", str(e))
return None
match... | def get_version(self) | Returns a tuple representing the installed HAProxy version.
The value of the tuple is (<major>, <minor>, <patch>), e.g. if HAProxy
version 1.5.3 is installed, this will return `(1, 5, 3)`. | 2.289129 | 2.036001 | 1.124326 |
info_response = self.send_command("show info")
if not info_response:
return {}
def convert_camel_case(string):
return all_cap_re.sub(
r'\1_\2',
first_cap_re.sub(r'\1_\2', string)
).lower()
return dict(
... | def get_info(self) | Parses the output of a "show info" HAProxy command and returns a
simple dictionary of the results. | 3.078422 | 2.758441 | 1.116001 |
# the -1 4 -1 args are the filters <proxy_id> <type> <server_id>,
# -1 for all proxies, 4 for servers only, -1 for all servers
stats_response = self.send_command("show stat -1 4 -1")
if not stats_response:
return []
lines = stats_response.split("\n")
... | def get_active_nodes(self) | Returns a dictionary of lists, where the key is the name of a service
and the list includes all active nodes associated with that service. | 4.665833 | 4.546423 | 1.026264 |
logger.info("Enabling server %s/%s", service_name, node_name)
return self.send_command(
"enable server %s/%s" % (service_name, node_name)
) | def enable_node(self, service_name, node_name) | Enables a given node name for the given service name via the
"enable server" HAProxy command. | 3.442752 | 2.805003 | 1.227361 |
logger.info("Disabling server %s/%s", service_name, node_name)
return self.send_command(
"disable server %s/%s" % (service_name, node_name)
) | def disable_node(self, service_name, node_name) | Disables a given node name for the given service name via the
"disable server" HAProxy command. | 3.353571 | 2.786322 | 1.203583 |
logger.debug("Connecting to socket %s", self.socket_file_path)
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.connect(self.socket_file_path)
except IOError as e:
if e.errno == errno.ECONNREFUSED:
logger.error("Connectio... | def send_command(self, command) | Sends a given command to the HAProxy control socket.
Returns the response from the socket as a string.
If a known error response (e.g. "Permission denied.") is given then
the appropriate exception is raised. | 2.274145 | 2.217287 | 1.025643 |
if response.startswith(b"Unknown command."):
raise UnknownCommandError(command)
if response == b"Permission denied.\n":
raise PermissionError(command)
if response == b"No such backend.\n":
raise UnknownServerError(command)
response = response... | def process_command_response(self, command, response) | Takes an HAProxy socket command and its response and either raises
an appropriate exception or returns the formatted response. | 4.466921 | 3.93641 | 1.13477 |
if len(source) < len(target):
return levenshtein(target, source)
# So now we have len(source) >= len(target).
if len(target) == 0:
return len(source)
# We call tuple() to force strings to be used as sequences
# ('c', 'a', 't', 's') - numpy uses them as values by default.
s... | def levenshtein(source, target) | Cribbed from <https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python> | 1.132758 | 1.109678 | 1.020799 |
qs_filter = {}
for key in list(request.GET.keys()):
if '__istartswith' in key:
qs_filter[str(key)] = request.GET[key]
break
return render_to_response(
template,
{'objects': queryset.filter(**qs_filter),
'unfiltered_objects': queryset},
... | def alphafilter(request, queryset, template) | Render the template with the filtered queryset | 3.104962 | 3.042154 | 1.020646 |
if channels == 1:
return self.volume_frames.reshape(-1, 1)
if channels == 2:
return np.tile(self.volume_frames, (2, 1)).T
raise Exception(
"RawVolume doesn't know what to do with %s channels" % channels) | def to_array(self, channels=2) | Return the array of multipliers for the dynamic | 4.394391 | 4.406138 | 0.997334 |
list = item['p_texts'] + item['links_text']
list.append(item['title'])
list.append(item['description'])
list.append(item['keywords'])
return Simhash(','.join(list).strip()).hash | def generate_simhash(self, item) | Generate simhash based on title, description, keywords, p_texts and links_text. | 6.423841 | 2.923102 | 2.197611 |
n = 0
for path in paths:
print('Counting lines for {0}...'.format(path))
n += sum(1 for line in open(path, 'r'))
print('Processing {0} lines...'.format(n))
# Change to use less memory. Default is 40m.
kwargs = {
'max_vocab_size': 40000000,
'threshold': 8.
}.... | def train_phrases(paths, out='data/bigram_model.phrases', tokenizer=word_tokenize, **kwargs) | Train a bigram phrase model on a list of files. | 4.026793 | 3.972299 | 1.013718 |
i = 0
p = Progress()
for path in paths:
with open(path, 'r') as f:
for line in f:
i += 1
p.print_progress(i/n)
for sent in sent_tokenize(line.lower()):
tokens = tokenizer(sent)
yield tokens | def _phrase_doc_stream(paths, n, tokenizer=word_tokenize) | Generator to feed sentences to the phrase model. | 2.693911 | 2.669279 | 1.009228 |
if content == "":
return 0
x = ord(content[0]) << 7
m = 1000003
mask = 2 ** hashbits - 1
for c in content:
x = ((x * m) ^ ord(c)) & mask
x ^= len(content)
if x == -1:
x = -2
return x | def _default_hashfunc(content, hashbits) | Default hash function is variable-length version of Python's builtin hash.
:param content: data that needs to hash.
:return: return a decimal number. | 2.955775 | 3.04998 | 0.969113 |
seg_list = jieba.lcut_for_search(content)
# Extract keyword-weight list by TF-IDF algorithms and by sorted maximum weight
return jieba.analyse.extract_tags("".join(seg_list), topK=keyword_weight_pair, withWeight=True) | def _default_tokenizer_func(content, keyword_weight_pair) | Default tokenizer function that uses jieba tokenizer.
:param keyword_weight_pair: maximum pair number of the keyword-weight list.
:return: return keyword-weight list. Example: [('Example',0.4511233019962264),('Hello',0.25548051420382073),...]. | 6.882565 | 6.325115 | 1.088133 |
if content is None:
self.hash = -1
return
if isinstance(content, str):
features = self.tokenizer_func(content, self.keyword_weight_pari)
self.hash = self.build_from_features(features)
elif isinstance(content, collections.Iterable):
... | def simhash(self, content) | Select policies for simhash on the different types of content. | 3.652057 | 3.653019 | 0.999737 |
v = [0] * self.hash_bit_number
if isinstance(features, dict):
features = features.items()
# Starting longitudinal accumulation of bits, current bit add current weight
# when the current bits equal 1 and else current bit minus the current weight.
for f in fea... | def build_from_features(self, features) | :param features: a list of (token,weight) tuples or a token -> weight dict,
if is a string so it need compute weight (a weight of 1 will be assumed).
:return: a decimal digit for the accumulative result of each after handled features-weight pair. | 4.501841 | 4.451454 | 1.011319 |
if another is None:
raise Exception("Parameter another is null")
if isinstance(another, int):
distance = self.hamming_distance(another)
elif isinstance(another, Simhash):
assert self.hash_bit_number == another.hash_bit_number
distance = s... | def is_equal(self, another, limit=0.8) | Determine two simhash are similar or not similar.
:param another: another simhash.
:param limit: a limit of the similarity.
:return: if similarity greater than limit return true and else return false. | 2.679732 | 2.59412 | 1.033002 |
x = (self.hash ^ another) & ((1 << self.hash_bit_number) - 1)
result = 0
while x:
result += 1
x &= x - 1
return result | def hamming_distance(self, another) | Compute hamming distance,hamming distance is a total number of different bits of two binary numbers.
:param another: another simhash value.
:return: a hamming distance that current simhash and another simhash. | 3.398692 | 3.431036 | 0.990573 |
if not str_:
return None
# Convert to datetime so we can validate it's a real date that exists then
# convert it back to the string.
try:
date = datetime.strptime(str_, DATE_FMT)
except ValueError:
msg = 'Invalid date format, should be YYYY-MM-DD'
raise argpars... | def _validate_date_str(str_) | Validate str as a date and return string version of date | 4.330255 | 3.849384 | 1.124922 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.