_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q41000 | DCSVectorizer._semsim | train | def _semsim(self, c1, c2):
"""
Computes the semantic similarity between two concepts.
The semantic similarity is a combination of two sem sims:
1. An "explicit" sem sim metric, that is, one which is directly
encoded in the WordNet graph. Here it is just Wu-Palmer simila... | python | {
"resource": ""
} |
q41001 | DCSVectorizer._core_semantics | train | def _core_semantics(self, lex_chains, concept_weights):
"""
Returns the n representative lexical chains for a document.
"""
chain_scores = [self._score_chain(lex_chain, adj_submat, concept_weights) for lex_chain, adj_submat in lex_chains]
scored_chains = zip(lex_chains, chain_sco... | python | {
"resource": ""
} |
q41002 | DCSVectorizer._extract_core_semantics | train | def _extract_core_semantics(self, docs):
"""
Extracts core semantics for a list of documents, returning them along with
a list of all the concepts represented.
"""
all_concepts = []
doc_core_sems = []
for doc in docs:
core_sems = self._process_doc(doc)... | python | {
"resource": ""
} |
q41003 | DCSVectorizer._lexical_chains | train | def _lexical_chains(self, doc, term_concept_map):
"""
Builds lexical chains, as an adjacency matrix,
using a disambiguated term-concept map.
"""
concepts = list({c for c in term_concept_map.values()})
# Build an adjacency matrix for the graph
# Using the encoding... | python | {
"resource": ""
} |
q41004 | DCSVectorizer._score_chain | train | def _score_chain(self, lexical_chain, adj_submat, concept_weights):
"""
Computes the score for a lexical chain.
"""
scores = []
# Compute scores for concepts in the chain
for i, c in enumerate(lexical_chain):
score = concept_weights[c] * self.relation_weights... | python | {
"resource": ""
} |
q41005 | DCSVectorizer._weight_concepts | train | def _weight_concepts(self, tokens, term_concept_map):
"""
Calculates weights for concepts in a document.
This is just the frequency of terms which map to a concept.
"""
weights = {c: 0 for c in term_concept_map.values()}
for t in tokens:
# Skip terms that ar... | python | {
"resource": ""
} |
q41006 | DCSVectorizer._description | train | def _description(self, concept):
"""
Returns a "description" of a concept,
as defined in the paper.
The paper describes the description as a string,
so this is a slight modification where we instead represent
the definition as a list of tokens.
"""
if con... | python | {
"resource": ""
} |
q41007 | DCSVectorizer._related | train | def _related(self, concept):
"""
Returns related concepts for a concept.
"""
return concept.hypernyms() + \
concept.hyponyms() + \
concept.member_meronyms() + \
concept.substance_meronyms() + \
concept.part_meronyms() + \
... | python | {
"resource": ""
} |
q41008 | init_tasks | train | def init_tasks():
"""
Performs basic setup before any of the tasks are run. All tasks needs to
run this before continuing. It only fires once.
"""
# Make sure exist are set
if "exists" not in env:
env.exists = exists
if "run" not in env:
env.run = run
if "cd" not in en... | python | {
"resource": ""
} |
q41009 | setup | train | def setup():
"""
Creates shared and upload directory then fires setup to recipes.
"""
init_tasks()
run_hook("before_setup")
# Create shared folder
env.run("mkdir -p %s" % (paths.get_shared_path()))
env.run("chmod 755 %s" % (paths.get_shared_path()))
# Create backup folder
env... | python | {
"resource": ""
} |
q41010 | deploy | train | def deploy():
"""
Performs a deploy by invoking copy, then generating next release name and
invoking necessary hooks.
"""
init_tasks()
if not has_hook("copy"):
return report("No copy method has been defined")
if not env.exists(paths.get_shared_path()):
return report("You n... | python | {
"resource": ""
} |
q41011 | rollback | train | def rollback():
"""
Rolls back to previous release
"""
init_tasks()
run_hook("before_rollback")
# Remove current version
current_release = paths.get_current_release_path()
if current_release:
env.run("rm -rf %s" % current_release)
# Restore previous version
old_releas... | python | {
"resource": ""
} |
q41012 | cleanup_releases | train | def cleanup_releases(limit=5):
"""
Removes older releases.
"""
init_tasks()
max_versions = limit + 1
env.run("ls -dt %s/*/ | tail -n +%s | xargs rm -rf" % (
paths.get_releases_path(),
max_versions)
) | python | {
"resource": ""
} |
q41013 | CachedView.from_db | train | def from_db(cls, db, force=False):
"""Make instance from database.
For performance, this caches the episode types for the database. The
`force` parameter can be used to bypass this.
"""
if force or db not in cls._cache:
cls._cache[db] = cls._new_from_db(db)
... | python | {
"resource": ""
} |
q41014 | prune | train | 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.
"""
all_terms = set([t for toks in tdocs for t in toks])
terms = set()
phrases = set()
fo... | python | {
"resource": ""
} |
q41015 | build_CLASS | train | def build_CLASS(prefix):
"""
Function to dowwnload CLASS from github and and build the library
"""
# 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.sy... | python | {
"resource": ""
} |
q41016 | main | train | 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.
"""
# Prepare font.
font_family = 'arial'
font = Font(font_family, bold=True)
if not font:
... | python | {
"resource": ""
} |
q41017 | User.login | train | def login(self, password):
"""Login to filemail as the current user.
:param password:
:type password: ``str``
"""
method, url = get_URL('login')
payload = {
'apikey': self.config.get('apikey'),
'username': self.username,
'password': p... | python | {
"resource": ""
} |
q41018 | User.logout | train | def logout(self):
"""Logout of filemail and closing the session."""
# Check if all transfers are complete before logout
self.transfers_complete
payload = {
'apikey': self.config.get('apikey'),
'logintoken': self.session.cookies.get('logintoken')
}
... | python | {
"resource": ""
} |
q41019 | User.transfers_complete | train | def transfers_complete(self):
"""Check if all transfers are completed."""
for transfer in self.transfers:
if not transfer.is_complete:
error = {
'errorcode': 4003,
'errormessage': 'You must complete transfer before logout.'
... | python | {
"resource": ""
} |
q41020 | User.get_sent | train | 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
:typ... | python | {
"resource": ""
} |
q41021 | User.get_user_info | train | 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.
"""
method, ... | python | {
"resource": ""
} |
q41022 | User.update_user_info | train | 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``
"""
if kwargs:
self.config.update(kwargs)
method, url =... | python | {
"resource": ""
} |
q41023 | User.get_received | train | 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 ... | python | {
"resource": ""
} |
q41024 | User.get_contact | train | 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
"""
contacts = self.get_contacts()
for contact in contacts:
if contact[... | python | {
"resource": ""
} |
q41025 | User.get_group | train | def get_group(self, name):
"""Get contact group by name
:param name: name of group
:type name: ``str``, ``unicode``
:rtype: ``dict`` with group data
"""
groups = self.get_groups()
for group in groups:
if group['contactgroupname'] == name:
... | python | {
"resource": ""
} |
q41026 | User.delete_group | train | def delete_group(self, name):
"""Delete contact group
:param name: of group
:type name: ``str``, ``unicode``
:rtype: ``bool``
"""
group = self.get_group(name)
method, url = get_URL('group_delete')
payload = {
'apikey': self.config.get('apik... | python | {
"resource": ""
} |
q41027 | User.rename_group | train | 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``
"""
if isinstance(group, b... | python | {
"resource": ""
} |
q41028 | User.add_contact_to_group | train | 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``
"""
... | python | {
"resource": ""
} |
q41029 | User.get_company_info | train | def get_company_info(self):
"""Get company settings from Filemail
:rtype: ``dict`` with company data
"""
method, url = get_URL('company_get')
payload = {
'apikey': self.config.get('apikey'),
'logintoken': self.session.cookies.get('logintoken')
... | python | {
"resource": ""
} |
q41030 | User.update_company | train | def update_company(self, company):
"""Update company settings
:param company: updated settings
:type company: ``dict``
:rtype: ``bool``
"""
if not isinstance(company, dict):
raise AttributeError('company must be a <dict>')
method, url = get_URL('com... | python | {
"resource": ""
} |
q41031 | User.get_company_user | train | 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
"""
users = self.get_company_users()
for user in users:
if user['email... | python | {
"resource": ""
} |
q41032 | User.company_add_user | train | 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 ... | python | {
"resource": ""
} |
q41033 | User.update_company_user | train | 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``
"""
if not isin... | python | {
"resource": ""
} |
q41034 | home | train | 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"""
cage_list = Animal.objects.values("Cage").distinct()
... | python | {
"resource": ""
} |
q41035 | PrintTable.col_widths | train | def col_widths(self):
# type: () -> defaultdict
"""Get MAX possible width of each column in the table.
:return: defaultdict
"""
_widths = defaultdict(int)
all_rows = [self.headers]
all_rows.extend(self._rows)
for row in all_rows:
for idx, co... | python | {
"resource": ""
} |
q41036 | PrintTable._marker_line | train | def _marker_line(self):
# type: () -> str
"""Generate a correctly sized marker line.
e.g.
'+------------------+---------+----------+---------+'
:return: str
"""
output = ''
for col in sorted(self.col_widths):
line = self.COLUMN_MARK + (self.... | python | {
"resource": ""
} |
q41037 | PrintTable._row_to_str | train | def _row_to_str(self, row):
# type: (List[str]) -> str
"""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
"""
_row_text = ''
... | python | {
"resource": ""
} |
q41038 | PrintTable._table_to_str | train | def _table_to_str(self):
# type: () -> str
"""Return single formatted table string.
:return: 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_t... | python | {
"resource": ""
} |
q41039 | sift4 | train | def sift4(s1, s2, max_offset=5):
"""
This is an implementation of general Sift4.
"""
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 =... | python | {
"resource": ""
} |
q41040 | Cohort.save | train | def save(self, *args, **kwargs):
'''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) | python | {
"resource": ""
} |
q41041 | FilePicker.pick | train | def pick(self, filenames: Iterable[str]) -> str:
"""Pick one filename based on priority rules."""
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 patt... | python | {
"resource": ""
} |
q41042 | count_tf | train | def count_tf(tokens_stream):
"""
Count term frequencies for a single file.
"""
tf = defaultdict(int)
for tokens in tokens_stream:
for token in tokens:
tf[token] += 1
return tf | python | {
"resource": ""
} |
q41043 | Cluster.validate_config | train | 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.
"""
if "discovery" not in config:
... | python | {
"resource": ""
} |
q41044 | Cluster.apply_config | train | 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.
"""
self.discovery = config["discovery"]
self.meta_cluster = config.get("meta_cluster")... | python | {
"resource": ""
} |
q41045 | command | train | def command(state, args):
"""Search Animanager database."""
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['t... | python | {
"resource": ""
} |
q41046 | _is_video | train | def _is_video(filepath) -> bool:
"""Check filename extension to see if it's a video file."""
if os.path.exists(filepath): # Could be broken symlink
extension = os.path.splitext(filepath)[1]
return extension in ('.mkv', '.mp4', '.avi')
else:
return False | python | {
"resource": ""
} |
q41047 | _find_files | train | def _find_files(dirpath: str) -> 'Iterable[str]':
"""Find files recursively.
Returns a generator that yields paths in no particular order.
"""
for dirpath, dirnames, filenames in os.walk(dirpath, topdown=True,
followlinks=True):
if os.path.basenam... | python | {
"resource": ""
} |
q41048 | Peer.current | train | def current(cls):
"""
Helper method for getting the current peer of whichever host we're
running on.
"""
name = socket.getfqdn()
ip = socket.gethostbyname(name)
return cls(name, ip) | python | {
"resource": ""
} |
q41049 | Peer.serialize | train | def serialize(self):
"""
Serializes the Peer data as a simple JSON map string.
"""
return json.dumps({
"name": self.name,
"ip": self.ip,
"port": self.port
}, sort_keys=True) | python | {
"resource": ""
} |
q41050 | Peer.deserialize | train | 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.
"""
parsed = json.... | python | {
"resource": ""
} |
q41051 | CryoEncoder.default | train | 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
"""
if isinstance(obj, np.ndarray):
data_b64 = base64.b64encode(obj.data).decode('utf-8')
return dict(__ndarray__=data_b64,
... | python | {
"resource": ""
} |
q41052 | Package._extract_meta_value | train | def _extract_meta_value(self, tag):
# type: (str, List[str]) -> str
"""Find a target value by `tag` from given meta data.
:param tag: str
:param meta_data: list
:return: str
"""
try:
return [l[len(tag):] for l in self.meta_data if l.startswith(tag)][0... | python | {
"resource": ""
} |
q41053 | get_markup_choices | train | def get_markup_choices():
"""
Receives available markup options as list.
"""
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:
... | python | {
"resource": ""
} |
q41054 | ZookeeperDiscovery.apply_config | train | 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.
"""
self.hosts = config["hosts"]
old... | python | {
"resource": ""
} |
q41055 | ZookeeperDiscovery.connect | train | 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.
"""
self.client = client.KazooClient(hosts=",".join(self.hosts))
... | python | {
"resource": ""
} |
q41056 | ZookeeperDiscovery.disconnect | train | def disconnect(self):
"""
Stops and closes the kazoo connection.
"""
logger.info("Disconnecting from Zookeeper.")
self.client.stop()
self.client.close() | python | {
"resource": ""
} |
q41057 | ZookeeperDiscovery.handle_connection_change | train | 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.... | python | {
"resource": ""
} |
q41058 | ZookeeperDiscovery.start_watching | train | 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... | python | {
"resource": ""
} |
q41059 | ZookeeperDiscovery.stop_watching | train | 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`.
"""
znode_path = "/".join([self.base_path, cluster.name])
if znode_path in self.stop_events:
... | python | {
"resource": ""
} |
q41060 | ZookeeperDiscovery.report_down | train | 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.
"""
wait_on_any(self... | python | {
"resource": ""
} |
q41061 | ZookeeperDiscovery.path_of | train | def path_of(self, service, node):
"""
Helper method for determining the Zookeeper path for a given cluster
member node.
"""
return "/".join([self.base_path, service.name, node.name]) | python | {
"resource": ""
} |
q41062 | rating_score | train | def rating_score(obj, user):
"""
Returns the score a user has given an object
"""
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
ex... | python | {
"resource": ""
} |
q41063 | rate_url | train | 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.
"""
return reverse('ratings_rate_object', args=(
ContentType.objects.get_for_model(obj).pk,
obj.pk,
score,
)) | python | {
"resource": ""
} |
q41064 | unrate_url | train | 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.
"""
return reverse('ratings_unrate_object', args=(
ContentType.objects.get_for_model(obj).pk,
obj.pk,
)) | python | {
"resource": ""
} |
q41065 | command | train | def command(state, args):
"""Reset anime watched episodes."""
args = parser.parse_args(args[1:])
aid = state.results.parse_aid(args.aid, default_key='db')
query.update.reset(state.db, aid, args.episode) | python | {
"resource": ""
} |
q41066 | cancel_job | train | 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.
"""
prevstate = agent.cancel(project_name, job_id)['prevstate']
if prevstate == 'pending':
sqllite_agent.execute(ScrapydJobExtInfoSQLSet... | python | {
"resource": ""
} |
q41067 | get_job_amounts | train | def get_job_amounts(agent, project_name, spider_name=None):
"""
Get amounts that pending job amount, running job amount, finished job amount.
"""
job_list = agent.get_job_list(project_name)
pending_job_list = job_list['pending']
running_job_list = job_list['running']
finished_job_list = job_... | python | {
"resource": ""
} |
q41068 | corba_name_to_string | train | def corba_name_to_string(name):
'''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:
part... | python | {
"resource": ""
} |
q41069 | Directory.reparse | train | 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.
... | python | {
"resource": ""
} |
q41070 | Directory.unbind | train | 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 pat... | python | {
"resource": ""
} |
q41071 | LemmaTokenizer.tokenize | train | def tokenize(self, docs):
""" Tokenizes a document, using a lemmatizer.
Args:
| doc (str) -- the text document to process.
Returns:
| list -- the list of tokens.
"""
if self.n_jobs == 1:
return [self._toke... | python | {
"resource": ""
} |
q41072 | command | train | def command(state, args):
"""Register watching regexp for an anime."""
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.
... | python | {
"resource": ""
} |
q41073 | AlterTable.from_definition | train | def from_definition(self, table: Table, version: int):
"""Add all columns from the table added in the specified version"""
self.table(table)
self.add_columns(*table.columns.get_with_version(version))
return self | python | {
"resource": ""
} |
q41074 | CamCrypt.keygen | train | 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... | python | {
"resource": ""
} |
q41075 | CamCrypt.encrypt | train | 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 ... | python | {
"resource": ""
} |
q41076 | CamCrypt.decrypt | train | 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): da... | python | {
"resource": ""
} |
q41077 | CamCrypt.encrypt_block | train | 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:
... | python | {
"resource": ""
} |
q41078 | CamCrypt.decrypt_block | train | 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:
... | python | {
"resource": ""
} |
q41079 | HAProxyControl.restart | train | def restart(self):
"""
Performs a soft reload of the HAProxy process.
"""
version = self.get_version()
command = [
"haproxy",
"-f", self.config_file_path, "-p", self.pid_file_path
]
if version and version >= (1, 5, 0):
command.... | python | {
"resource": ""
} |
q41080 | HAProxyControl.get_version | train | 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)`.
"""
command = ["haproxy", "-v"]
try:
... | python | {
"resource": ""
} |
q41081 | HAProxyControl.get_info | train | def get_info(self):
"""
Parses the output of a "show info" HAProxy command and returns a
simple dictionary of the results.
"""
info_response = self.send_command("show info")
if not info_response:
return {}
def convert_camel_case(string):
... | python | {
"resource": ""
} |
q41082 | HAProxyControl.get_active_nodes | train | 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.
"""
# the -1 4 -1 args are the filters <proxy_id> <type> <server_id>,
# -1 for all proxies, 4 for ser... | python | {
"resource": ""
} |
q41083 | HAProxyControl.enable_node | train | def enable_node(self, service_name, node_name):
"""
Enables a given node name for the given service name via the
"enable server" HAProxy command.
"""
logger.info("Enabling server %s/%s", service_name, node_name)
return self.send_command(
"enable server %s/%s" ... | python | {
"resource": ""
} |
q41084 | HAProxyControl.disable_node | train | def disable_node(self, service_name, node_name):
"""
Disables a given node name for the given service name via the
"disable server" HAProxy command.
"""
logger.info("Disabling server %s/%s", service_name, node_name)
return self.send_command(
"disable server %s... | python | {
"resource": ""
} |
q41085 | HAProxyControl.send_command | train | 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.
"""
logger.debug(... | python | {
"resource": ""
} |
q41086 | HAProxyControl.process_command_response | train | 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.
"""
if response.startswith(b"Unknown command."):
raise UnknownCommandError(command... | python | {
"resource": ""
} |
q41087 | alphafilter | train | def alphafilter(request, queryset, template):
"""
Render the template with the filtered queryset
"""
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(
te... | python | {
"resource": ""
} |
q41088 | RawVolume.to_array | train | def to_array(self, channels=2):
"""Return the array of multipliers for the dynamic"""
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 wha... | python | {
"resource": ""
} |
q41089 | SimpleCrawler.generate_simhash | train | def generate_simhash(self, item):
"""
Generate simhash based on title, description, keywords, p_texts and links_text.
"""
list = item['p_texts'] + item['links_text']
list.append(item['title'])
list.append(item['description'])
list.append(item['keywords'])
... | python | {
"resource": ""
} |
q41090 | train_phrases | train | def train_phrases(paths, out='data/bigram_model.phrases', tokenizer=word_tokenize, **kwargs):
"""
Train a bigram phrase model on a list of files.
"""
n = 0
for path in paths:
print('Counting lines for {0}...'.format(path))
n += sum(1 for line in open(path, 'r'))
print('Processing... | python | {
"resource": ""
} |
q41091 | _phrase_doc_stream | train | def _phrase_doc_stream(paths, n, tokenizer=word_tokenize):
"""
Generator to feed sentences to the phrase model.
"""
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)
f... | python | {
"resource": ""
} |
q41092 | _default_hashfunc | train | 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.
"""
if content == "":
return 0
x = ord(content[0]) << 7
m = 1000003
mask = 2 *... | python | {
"resource": ""
} |
q41093 | _default_tokenizer_func | train | 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),..... | python | {
"resource": ""
} |
q41094 | Simhash.simhash | train | def simhash(self, content):
"""
Select policies for simhash on the different types of content.
"""
if content is None:
self.hash = -1
return
if isinstance(content, str):
features = self.tokenizer_func(content, self.keyword_weight_pari)
... | python | {
"resource": ""
} |
q41095 | Simhash.is_equal | train | 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.
"""
if another is ... | python | {
"resource": ""
} |
q41096 | Simhash.hamming_distance | train | 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.
"""
x = (self.hash ^... | python | {
"resource": ""
} |
q41097 | _validate_date_str | train | def _validate_date_str(str_):
"""Validate str as a date and return string version of date"""
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... | python | {
"resource": ""
} |
q41098 | _parse_args | train | def _parse_args():
"""Parse sys.argv arguments"""
token_file = os.path.expanduser('~/.nikeplus_access_token')
parser = argparse.ArgumentParser(description='Export NikePlus data to CSV')
parser.add_argument('-t', '--token', required=False, default=None,
help=('Access token for ... | python | {
"resource": ""
} |
q41099 | EntKeySimilarity.similarity | train | def similarity(self, d, d_):
"""
Compute a similarity score for two documents.
Optionally pass in a `term_sim_ref` dict-like, which should be able
to take `term1, term2` as args and return their similarity.
"""
es = set([e.name for e in d.entities])
es_ = set([e.... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.