_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3 values | text stringlengths 75 19.8k | language stringclasses 1 value | meta_information dict |
|---|---|---|---|---|---|
q42900 | reindex | train | def reindex():
'''Reindex all advices'''
header('Reindexing all advices')
echo('Deleting index {0}', white(es.index_name))
if es.indices.exists(es.index_name):
es.indices.delete(index=es.index_name)
es.initialize()
idx = 0
for idx, advice in enumerate(Advice.objects, 1):
index(advice)
echo('.' if idx % 50 else white(idx), nl=False)
echo(white(idx) if idx % 50 else '')
es.indices.refresh(index=es.index_name)
success('Indexed {0} advices', idx) | python | {
"resource": ""
} |
q42901 | static | train | def static(path, no_input):
'''Compile and collect static files into path'''
log = logging.getLogger('webassets')
log.addHandler(logging.StreamHandler())
log.setLevel(logging.DEBUG)
cmdenv = CommandLineEnvironment(assets, log)
cmdenv.build()
if exists(path):
warning('{0} directory already exists and will be {1}', white(path), white('erased'))
if not no_input and not click.confirm('Are you sure'):
exit_with_error()
shutil.rmtree(path)
echo('Copying assets into {0}', white(path))
shutil.copytree(assets.directory, path)
success('Done') | python | {
"resource": ""
} |
q42902 | anon | train | def anon():
'''Check for candidates to anonymization'''
header(anon.__doc__)
filename = 'urls_to_check.csv'
candidates = Advice.objects(__raw__={
'$or': [
{'subject': {
'$regex': '(Monsieur|Madame|Docteur|Mademoiselle)\s+[^X\s\.]{3}',
'$options': 'imx',
}},
{'content': {
'$regex': '(Monsieur|Madame|Docteur|Mademoiselle)\s+[^X\s\.]{3}',
'$options': 'imx',
}}
]
})
with open(filename, 'wb') as csvfile:
writer = csv.writer(csvfile)
# Generate header
writer.writerow(csv.ANON_HEADER)
for idx, advice in enumerate(candidates, 1):
writer.writerow(csv.to_anon_row(advice))
echo('.' if idx % 50 else white(idx), nl=False)
echo(white(idx) if idx % 50 else '')
success('Total: {0} candidates', len(candidates)) | python | {
"resource": ""
} |
q42903 | Brain.login | train | def login(self, **kwargs):
"""Logs the current user into the server with the passed in credentials. If successful the apiToken will be changed to match the passed in credentials.
:param apiToken: use the passed apiToken to authenticate
:param user_id: optional instead of apiToken, must be passed with token
:param token: optional instead of apiToken, must be passed with user_id
:param authenticate: only valid with apiToken. Force a call to the server to authenticate the passed credentials.
:return:
"""
if 'signed_username' in kwargs:
apiToken = kwargs['signed_username']
if kwargs.get('authenticate', False):
self._checkReturn(requests.get("{}/users?signed_username={}".format(self.url, apiToken)))
self.signedUsername = apiToken
else:
auth = (kwargs['user_id'], kwargs['token'])
self.signedUsername = self._checkReturn(requests.get("{}/users/login".format(self.url), auth=auth))[
'signed_username'] | python | {
"resource": ""
} |
q42904 | Brain.createAssetFromURL | train | def createAssetFromURL(self, url, async=False, metadata=None, callback=None):
"""Users the passed URL to load data. If async=false a json with the result is returned otherwise a json with an asset_id is returned.
:param url:
:param metadata: arbitrary additional description information for the asset
:param async:
:param callback: Callback URL
:return:
"""
audio = {'uri': url}
config = {'async': async}
if callback is not None:
config['callback'] = callback
if metadata is not None:
body = {'audio': audio, 'config': config, 'metadata': metadata}
else:
body = {'audio': audio, 'config': config}
return self._checkReturn(
requests.post("{}/speech:recognize?signed_username={}".format(self.url, self.signedUsername), json=body)) | python | {
"resource": ""
} |
q42905 | reload | train | def reload(filename=None,
url=r"https://raw.githubusercontent.com/googlei18n/emoji4unicode/master/data/emoji4unicode.xml",
loader_class=None):
u"""reload google's `emoji4unicode` project's xml file. must call this method first to use `e4u` library."""
if loader_class is None:
loader_class = loader.Loader
global _loader
_loader = loader_class()
_loader.load(filename, url) | python | {
"resource": ""
} |
q42906 | AnsiVault.is_file_encrypted | train | def is_file_encrypted(self, filename):
'''
Given a file. Check if it is already encrypted.
'''
if not os.path.exists(filename):
print "Invalid filename %s. Does not exist" % filename
return False
fhandle = open(filename, "rb")
data = fhandle.read()
fhandle.close()
if data.startswith(AnsiVault.HEADER):
return True
else:
return False | python | {
"resource": ""
} |
q42907 | common_start | train | def common_start(*args):
""" returns the longest common substring from the beginning of sa and sb """
def _iter():
for s in zip(*args):
if len(set(s)) < len(args):
yield s[0]
else:
return
out = "".join(_iter()).strip()
result = [s for s in args if not s.startswith(out)]
result.insert(0, out)
return ', '.join(result) | python | {
"resource": ""
} |
q42908 | passgen | train | def passgen(length=12, punctuation=False, digits=True, letters=True,
case="both", **kwargs):
"""Generate random password.
Args:
length (int): The length of the password. Must be greater than
zero. Defaults to 12.
punctuation (bool): Whether to use punctuation or not. Defaults
to False.
limit_punctuation (str): Limits the allowed puncturation to defined
characters.
digits (bool): Whether to use digits or not. Defaults to True.
One of *digits* and *letters* must be True.
letters (bool): Whether to use letters or not. Defaults to
True. One of *digits* and *letters* must be True.
case (str): Letter case to use. Accepts 'upper' for upper case,
'lower' for lower case, and 'both' for both. Defaults to
'both'.
Returns:
str. The generated password.
Raises:
ValueError
Below are some basic examples.
>>> passgen()
z7GlutdEEbnk
>>> passgen(case='upper')
Q81J9DOAMBRN
>>> passgen(length=6)
EzJMRX
"""
p_min = punctuation
p_max = 0 if punctuation is False else length
d_min = digits
d_max = 0 if digits is False else length
a_min = letters
a_max = 0 if letters is False else length
if d_min + p_min + a_min > length:
raise ValueError("Minimum punctuation and digits number cannot be greater than length")
if not digits and not letters:
raise ValueError("digits and letters cannot be False at the same time")
if length < 1:
raise ValueError("length must be greater than zero")
if letters:
if case == "both":
alpha = string.ascii_uppercase + string.ascii_lowercase
elif case == "upper":
alpha = string.ascii_uppercase
elif case == "lower":
alpha = string.ascii_lowercase
else:
raise ValueError("case can only be 'both', 'upper' or 'lower'")
else:
alpha = string.ascii_uppercase + string.ascii_lowercase
if punctuation:
limit_punctuation = kwargs.get('limit_punctuation', '')
if limit_punctuation == '':
punctuation_set = string.punctuation
else:
# In case limit_punctuation contains non-punctuation characters
punctuation_set = ''.join([p for p in limit_punctuation
if p in string.punctuation])
else:
punctuation_set = string.punctuation
srandom = random.SystemRandom()
p_generator = Generator(punctuation_set, srandom, p_min, p_max)
d_generator = Generator(string.digits, srandom, d_min, d_max)
a_generator = Generator(alpha, srandom, a_min, a_max)
main_generator = SuperGenerator(srandom, length, length)
main_generator.add(p_generator)
main_generator.add(a_generator)
main_generator.add(d_generator)
chars = []
for i in main_generator:
chars.append(i)
try:
srandom.shuffle(chars, srandom)
except:
random.shuffle(chars)
return "".join(chars) | python | {
"resource": ""
} |
q42909 | main | train | def main():
"""The main entry point for command line invocation. It's output
is adjusted by command line arguments. By default it outputs 10
passwords.
For help on accepted arguments, run::
$ passgen -h
Or::
$ python -m passgen -h
"""
parser = argparse.ArgumentParser(
description="Generate random password."
)
parser.add_argument("-l", "--length",
help="the length of the generated "
"password (default: 12)",
type=int, default=12)
parser.add_argument("-n", "--number",
help="how many passwords to generate (default: 10)",
type=int, default=10)
parser.add_argument("-p", "--punctuation",
help="use punctuation characters",
action='store_true')
parser.add_argument("--limit-punctuation",
help="specify allowed punctuation characters",
action='store', default='')
alnum_group = parser.add_mutually_exclusive_group()
alnum_group.add_argument("--no-digits",
help="don't use digits",
action='store_false', dest='digits')
alnum_group.add_argument("--no-letters",
help="don't use letters",
action='store_false', dest='letters')
case_group = parser.add_mutually_exclusive_group()
case_group.add_argument("--upper",
help="use only upper case letters",
action='store_true')
case_group.add_argument("--lower",
help="use only lower case letters",
action='store_true')
args = parser.parse_args()
if args.length < 1:
_error("argument -l/--length must be greater than zero")
if args.number < 1:
_error("argument -n/--number must be greater than zero")
if args.lower:
case = "lower"
elif args.upper:
case = "upper"
else:
case = "both"
for _ in range(args.number):
print(passgen(args.length, punctuation=args.punctuation,
limit_punctuation=args.limit_punctuation,
digits=args.digits,
letters=args.letters, case=case)) | python | {
"resource": ""
} |
q42910 | BaseCommand.main | train | def main(cls):
"""Setuptools console-script entrypoint"""
cmd = cls()
cmd._parse_args()
cmd._setup_logging()
response = cmd._run()
output = cmd._handle_response(response)
if output is not None:
print(output) | python | {
"resource": ""
} |
q42911 | SetOrgMiddleware.set_language | train | def set_language(self, request, org):
"""Set the current language from the org configuration."""
if org:
lang = org.language or settings.DEFAULT_LANGUAGE
translation.activate(lang) | python | {
"resource": ""
} |
q42912 | SetOrgMiddleware.set_timezone | train | def set_timezone(self, request, org):
"""Set the current timezone from the org configuration."""
if org and org.timezone:
timezone.activate(org.timezone) | python | {
"resource": ""
} |
q42913 | TrackContainer.add | train | def add(self, obj):
"""
Add pre-created tracks.
If the tracks are already created, we hijack the data.
This way the pointer to the pre-created tracks are still valid.
"""
obj.controller = self.controller
# Is the track already loaded or created?
track = self.tracks.get(obj.name)
if track:
if track == obj:
return
# hijack the track data
obj.keys = track.keys
obj.controller = track.controller
self.tracks[track.name] = obj
self.track_index[self.track_index.index(track)] = obj
else:
# Add a new track
obj.controller = self.controller
self.tracks[obj.name] = obj
self.track_index.append(obj) | python | {
"resource": ""
} |
q42914 | Track.row_value | train | def row_value(self, row):
"""Get the tracks value at row"""
irow = int(row)
i = self._get_key_index(irow)
if i == -1:
return 0.0
# Are we dealing with the last key?
if i == len(self.keys) - 1:
return self.keys[-1].value
return TrackKey.interpolate(self.keys[i], self.keys[i + 1], row) | python | {
"resource": ""
} |
q42915 | Track.add_or_update | train | def add_or_update(self, row, value, kind):
"""Add or update a track value"""
i = bisect.bisect_left(self.keys, row)
# Are we simply replacing a key?
if i < len(self.keys) and self.keys[i].row == row:
self.keys[i].update(value, kind)
else:
self.keys.insert(i, TrackKey(row, value, kind)) | python | {
"resource": ""
} |
q42916 | Track.delete | train | def delete(self, row):
"""Delete a track value"""
i = self._get_key_index(row)
del self.keys[i] | python | {
"resource": ""
} |
q42917 | Track._get_key_index | train | def _get_key_index(self, row):
"""Get the key that should be used as the first interpolation value"""
# Don't bother with empty tracks
if len(self.keys) == 0:
return -1
# No track values are defined yet
if row < self.keys[0].row:
return -1
# Get the insertion index
index = bisect.bisect_left(self.keys, row)
# Index is within the array size?
if index < len(self.keys):
# Are we inside an interval?
if row < self.keys[index].row:
return index - 1
return index
# Return the last index
return len(self.keys) - 1 | python | {
"resource": ""
} |
q42918 | Track.load | train | def load(self, filepath):
"""Load the track file"""
with open(filepath, 'rb') as fd:
num_keys = struct.unpack(">i", fd.read(4))[0]
for i in range(num_keys):
row, value, kind = struct.unpack('>ifb', fd.read(9))
self.keys.append(TrackKey(row, value, kind)) | python | {
"resource": ""
} |
q42919 | Track.save | train | def save(self, path):
"""Save the track"""
name = Track.filename(self.name)
with open(os.path.join(path, name), 'wb') as fd:
fd.write(struct.pack('>I', len(self.keys)))
for k in self.keys:
fd.write(struct.pack('>ifb', k.row, k.value, k.kind)) | python | {
"resource": ""
} |
q42920 | iri2uri | train | def iri2uri(uri):
"""Convert an IRI to a URI. Note that IRIs must be
passed in a unicode strings. That is, do not utf-8 encode
the IRI before passing it into the function."""
assert uri != None, 'iri2uri must be passed a non-none string!'
original = uri
if isinstance(uri ,str):
(scheme, authority, path, query, fragment) = urllib.parse.urlsplit(uri)
authority = authority.encode('idna').decode('utf-8')
# For each character in 'ucschar' or 'iprivate'
# 1. encode as utf-8
# 2. then %-encode each octet of that utf-8
# path = urllib.parse.quote(path)
uri = urllib.parse.urlunsplit((scheme, authority, path, query, fragment))
uri = "".join([encode(c) for c in uri])
# urllib.parse.urlunsplit(urllib.parse.urlsplit({something})
# strips any trailing "?" chars. While this may be legal according to the
# spec, it breaks some services. Therefore, we patch
# the "?" back in if it has been removed.
if original.endswith("?") and not uri.endswith("?"):
uri = uri+"?"
return uri | python | {
"resource": ""
} |
q42921 | AnsibleRunner.validate_host_parameters | train | def validate_host_parameters(self, host_list, remote_user):
'''
Validate and set the host list and remote user parameters.
'''
if host_list is None:
host_list = self.host_list
if remote_user is None:
remote_user = self.remote_user
if host_list is None or remote_user is None:
print "Host list [%s], remote user [%s] are required" % \
(host_list, remote_user)
return (None, None)
return (host_list, remote_user) | python | {
"resource": ""
} |
q42922 | AnsibleRunner.validate_results | train | def validate_results(self, results, checks=None):
'''
Valdiate results from the Anisble Run.
'''
results['status'] = 'PASS'
failed_hosts = []
###################################################
# First validation is to make sure connectivity to
# all the hosts was ok.
###################################################
if results['dark']:
print "Host connectivity issues on %s",
results['dark'].keys()
failed_hosts.append(results['dark'].keys())
results['status'] = 'FAIL'
##################################################
# Now look for status 'failed'
##################################################
for node in results['contacted'].keys():
if 'failed' in results['contacted'][node]:
if results['contacted'][node]['failed'] is True:
results['status'] = 'FAIL'
#################################################
# Check for the return code 'rc' for each host.
#################################################
for node in results['contacted'].keys():
rc = results['contacted'][node].get('rc', None)
if rc is not None and rc != 0:
print "Operation 'return code' %s on host %s" % \
(results['contacted'][node]['rc'], node)
failed_hosts.append(node)
results['status'] = 'FAIL'
##################################################
# Additional checks. If passed is a list of key/value
# pairs that should be matched.
##################################################
if checks is None:
#print "No additional checks validated"
return results, failed_hosts
for check in checks:
key = check.keys()[0]
value = check.values()[0]
for node in results['contacted'].keys():
if key in results['contacted'][node].keys():
if results['contacted'][node][key] != value:
failed_hosts.append(node)
results['status'] = 'FAIL'
return (results, failed_hosts) | python | {
"resource": ""
} |
q42923 | AnsibleRunner.ansible_perform_operation | train | def ansible_perform_operation(self,
host_list=None,
remote_user=None,
remote_pass=None,
module=None,
complex_args=None,
module_args='',
environment=None,
check=False,
sudo=False,
sudo_user=None,
sudo_pass=None,
forks=20):
'''
Perform any ansible operation.
'''
(host_list, remote_user) = \
self.validate_host_parameters(host_list, remote_user)
if (host_list, remote_user) is (None, None):
return None
if module is None:
print "ANSIBLE Perform operation: No module specified"
return None
runner = ansible.runner.Runner(
module_name=module,
host_list=host_list,
remote_user=remote_user,
remote_pass=remote_pass,
module_args=module_args,
complex_args=complex_args,
environment=environment,
check=check,
become=sudo,
become_user=sudo_user,
become_pass=sudo_pass,
forks=forks)
results = runner.run()
results, failed_hosts = self.validate_results(results)
if results['status'] != 'PASS':
print "ANSIBLE: [%s] operation failed [%s] [hosts: %s]" % \
(module, complex_args, failed_hosts)
return results, failed_hosts | python | {
"resource": ""
} |
q42924 | PoToXls.strings | train | def strings(self):
"""
Write strings sheet.
"""
sheet = self.result.add_sheet("strings")
self.header(sheet, "strings")
n_row = 1 # row number
for entry in self.po:
row = sheet.row(n_row)
row.write(0, entry.msgid)
row.write(1, entry.msgstr)
n_row += 1
sheet.flush_row_data() | python | {
"resource": ""
} |
q42925 | PoToXls.metadata | train | def metadata(self):
"""
Write metadata sheet.
"""
sheet = self.result.add_sheet("metadata")
self.header(sheet, "metadata")
n_row = 1 # row number
for k in self.po.metadata:
row = sheet.row(n_row)
row.write(0, k)
row.write(1, self.po.metadata[k])
n_row += 1
sheet.flush_row_data() | python | {
"resource": ""
} |
q42926 | PoToXls.convert | train | def convert(self, *args, **kwargs):
"""
Yes it is, thanks captain.
"""
self.strings()
self.metadata()
# save file
self.result.save(self.output()) | python | {
"resource": ""
} |
q42927 | sync_from_remote | train | def sync_from_remote(org, syncer, remote):
"""
Sync local instance against a single remote object
:param * org: the org
:param * syncer: the local model syncer
:param * remote: the remote object
:return: the outcome (created, updated or deleted)
"""
identity = syncer.identify_remote(remote)
with syncer.lock(org, identity):
existing = syncer.fetch_local(org, identity)
# derive kwargs for the local model (none return here means don't keep)
remote_as_kwargs = syncer.local_kwargs(org, remote)
# exists locally
if existing:
existing.org = org # saves pre-fetching since we already have the org
if remote_as_kwargs:
if syncer.update_required(existing, remote, remote_as_kwargs) or not existing.is_active:
for field, value in remote_as_kwargs.items():
setattr(existing, field, value)
existing.is_active = True
existing.save()
return SyncOutcome.updated
elif existing.is_active: # exists locally, but shouldn't now to due to model changes
syncer.delete_local(existing)
return SyncOutcome.deleted
elif remote_as_kwargs:
syncer.model.objects.create(**remote_as_kwargs)
return SyncOutcome.created
return SyncOutcome.ignored | python | {
"resource": ""
} |
q42928 | sync_local_to_set | train | def sync_local_to_set(org, syncer, remote_set):
"""
Syncs an org's set of local instances of a model to match the set of remote objects. Local objects not in the remote
set are deleted.
:param org: the org
:param * syncer: the local model syncer
:param remote_set: the set of remote objects
:return: tuple of number of local objects created, updated, deleted and ignored
"""
outcome_counts = defaultdict(int)
remote_identities = set()
for remote in remote_set:
outcome = sync_from_remote(org, syncer, remote)
outcome_counts[outcome] += 1
remote_identities.add(syncer.identify_remote(remote))
# active local objects which weren't in the remote set need to be deleted
active_locals = syncer.fetch_all(org).filter(is_active=True)
delete_locals = active_locals.exclude(**{syncer.local_id_attr + "__in": remote_identities})
for local in delete_locals:
with syncer.lock(org, syncer.identify_local(local)):
syncer.delete_local(local)
outcome_counts[SyncOutcome.deleted] += 1
return (
outcome_counts[SyncOutcome.created],
outcome_counts[SyncOutcome.updated],
outcome_counts[SyncOutcome.deleted],
outcome_counts[SyncOutcome.ignored],
) | python | {
"resource": ""
} |
q42929 | sync_local_to_changes | train | def sync_local_to_changes(org, syncer, fetches, deleted_fetches, progress_callback=None):
"""
Sync local instances against iterators which return fetches of changed and deleted remote objects.
:param * org: the org
:param * syncer: the local model syncer
:param * fetches: an iterator returning fetches of modified remote objects
:param * deleted_fetches: an iterator returning fetches of deleted remote objects
:param * progress_callback: callable for tracking progress - called for each fetch with number of contacts fetched
:return: tuple containing counts of created, updated and deleted local instances
"""
num_synced = 0
outcome_counts = defaultdict(int)
for fetch in fetches:
for remote in fetch:
outcome = sync_from_remote(org, syncer, remote)
outcome_counts[outcome] += 1
num_synced += len(fetch)
if progress_callback:
progress_callback(num_synced)
# any item that has been deleted remotely should also be released locally
for deleted_fetch in deleted_fetches:
for deleted_remote in deleted_fetch:
identity = syncer.identify_remote(deleted_remote)
with syncer.lock(org, identity):
existing = syncer.fetch_local(org, identity)
if existing:
syncer.delete_local(existing)
outcome_counts[SyncOutcome.deleted] += 1
num_synced += len(deleted_fetch)
if progress_callback:
progress_callback(num_synced)
return (
outcome_counts[SyncOutcome.created],
outcome_counts[SyncOutcome.updated],
outcome_counts[SyncOutcome.deleted],
outcome_counts[SyncOutcome.ignored],
) | python | {
"resource": ""
} |
q42930 | Rpn.fsto | train | def fsto(self):
"""sto operation.
"""
a = float(self.tmpopslist.pop())
var = self.opslist.pop()
if isinstance(var, basestring):
self.variables.update({var: a})
return a
else:
print("Can only sto into a variable.")
return 'ERROR' | python | {
"resource": ""
} |
q42931 | Rpn.solve | train | def solve(self):
"""Solve rpn expression, return None if not valid."""
popflag = True
self.tmpopslist = []
while True:
while self.opslist and popflag:
op = self.opslist.pop()
if self.is_variable(op):
op = self.variables.get(op)
if self.is_operator(op):
popflag = False
break
self.tmpopslist.append(op)
# operations
tmpr = self._get_temp_result(op)
if tmpr == 'ERROR':
return None
if tmpr is not None:
self.opslist.append('{r:.20f}'.format(r=tmpr))
if len(self.tmpopslist) > 0 or len(self.opslist) > 1:
popflag = True
else:
break
return float(self.opslist[0]) | python | {
"resource": ""
} |
q42932 | build_sort | train | def build_sort():
'''Build sort query paramter from kwargs'''
sorts = request.args.getlist('sort')
sorts = [sorts] if isinstance(sorts, basestring) else sorts
sorts = [s.split(' ') for s in sorts]
return [{SORTS[s]: d} for s, d in sorts if s in SORTS] | python | {
"resource": ""
} |
q42933 | show_list_translations | train | def show_list_translations(context, item):
"""
Return the widget to select the translations we want
to order or delete from the item it's being edited
:param context:
:param item:
:return:
"""
if not item:
return
manager = Manager()
manager.set_master(item)
ct_item = ContentType.objects.get_for_model(item)
item_language_codes = manager.get_languages_from_item(ct_item, item)
model_language_codes = manager.get_languages_from_model(ct_item.app_label, ct_item.model)
item_languages = [{'lang': lang, 'from_model': lang.code in model_language_codes}
for lang in TransLanguage.objects.filter(code__in=item_language_codes).order_by('name')]
more_languages = [{'lang': lang, 'from_model': lang.code in model_language_codes}
for lang in TransLanguage.objects.exclude(main_language=True).order_by('name')]
return render_to_string('languages/translation_language_selector.html', {
'item_languages': item_languages,
'more_languages': more_languages,
'api_url': TM_API_URL,
'app_label': manager.app_label,
'model': manager.model_label,
'object_pk': item.pk
}) | python | {
"resource": ""
} |
q42934 | Table._xml_pretty_print | train | def _xml_pretty_print(self, data):
"""Pretty print xml data
"""
raw_string = xtree.tostring(data, 'utf-8')
parsed_string = minidom.parseString(raw_string)
return parsed_string.toprettyxml(indent='\t') | python | {
"resource": ""
} |
q42935 | Table._create_table_xml_file | train | def _create_table_xml_file(self, data, fname=None):
"""Creates a xml file of the table
"""
content = self._xml_pretty_print(data)
if not fname:
fname = self.name
with open(fname+".xml", 'w') as f:
f.write(content) | python | {
"resource": ""
} |
q42936 | Table.save | train | def save(self, name=None, path=None):
"""Save file as xml
"""
if path :
name = os.path.join(path,name)
try:
self._create_table_xml_file(self.etree, name)
except (Exception,) as e:
print(e)
return False
return True | python | {
"resource": ""
} |
q42937 | Table.addBinder | train | def addBinder(self, binder):
"""Adds a binder to the file
"""
root = self.etree
bindings = root.find('bindings')
bindings.append(binder.etree)
return True | python | {
"resource": ""
} |
q42938 | Table.removeBinder | train | def removeBinder(self, name):
"""Remove a binder from a table
"""
root = self.etree
t_bindings = root.find('bindings')
t_binder = t_bindings.find(name)
if t_binder :
t_bindings.remove(t_binder)
return True
return False | python | {
"resource": ""
} |
q42939 | CentrifugoAuthentication.post | train | def post(self, request, *args, **kwargs):
"""
Returns a token identifying the user in Centrifugo.
"""
current_timestamp = "%.0f" % time.time()
user_id_str = u"{0}".format(request.user.id)
token = generate_token(settings.CENTRIFUGE_SECRET, user_id_str, "{0}".format(current_timestamp), info="")
# we get all the channels to which the user can subscribe
participant = Participant.objects.get(id=request.user.id)
# we use the threads as channels ids
channels = []
for thread in Thread.managers.get_threads_where_participant_is_active(participant_id=participant.id):
channels.append(
build_channel(settings.CENTRIFUGO_MESSAGE_NAMESPACE, thread.id, thread.participants.all())
)
# we also have a channel to alert us about new threads
threads_channel = build_channel(settings.CENTRIFUGO_THREAD_NAMESPACE, request.user.id, [request.user.id]) # he is the only one to have access to the channel
channels.append(threads_channel)
# we return the information
to_return = {
'user': user_id_str,
'timestamp': current_timestamp,
'token': token,
'connection_url': "{0}connection/".format(settings.CENTRIFUGE_ADDRESS),
'channels': channels,
'debug': settings.DEBUG,
}
return HttpResponse(json.dumps(to_return), content_type='application/json; charset=utf-8') | python | {
"resource": ""
} |
q42940 | Base.removeFunction | train | def removeFunction(self):
"""Remove function tag
"""
root = self.etree
t_execute = root.find('execute')
try:
root.remove(t_execute)
return True
except (Exception,) as e:
print(e)
return False | python | {
"resource": ""
} |
q42941 | BaseBinder._buildElementTree | train | def _buildElementTree(self,):
"""Turns object into a Element Tree
"""
t_binder = ctree.Element(self.name)
for k,v in self.__dict__.items():
if k not in ('name', 'urls', 'inputs', 'paging') and v :
t_binder.set(k,v)
self.etree = t_binder
return t_binder | python | {
"resource": ""
} |
q42942 | BaseBinder.addUrl | train | def addUrl(self, url):
"""Add url to binder
"""
if url not in self.urls:
self.urls.append(url)
root = self.etree
t_urls = root.find('urls')
if not t_urls:
t_urls = ctree.SubElement(root, 'urls')
t_url = ctree.SubElement(t_urls, 'url')
t_url.text = url
return True | python | {
"resource": ""
} |
q42943 | BaseBinder.removeUrl | train | def removeUrl(self, url):
"""Remove passed url from a binder
"""
root = self.etree
t_urls = root.find('urls')
if not t_urls:
return False
for t_url in t_urls.findall('url'):
if t_url.text == url.strip():
t_urls.remove(t_url)
if url in self.urls:
self.urls.remove(url)
return True
return False | python | {
"resource": ""
} |
q42944 | BaseBinder.addPaging | train | def addPaging(self,paging):
"""Add paging to Binder
"""
if not vars(self).get('paging', None):
self.paging = paging
root = self.etree
try:
root.append(paging.etree)
return True
except (Exception,) as e:
print(e)
return False | python | {
"resource": ""
} |
q42945 | BaseBinder.removePaging | train | def removePaging(self,):
"""Remove paging from Binder
"""
root = self.etree
t_paging = root.find('paging')
try:
root.remove(t_paging)
return True
except (Exception,) as e:
print(e)
return False | python | {
"resource": ""
} |
q42946 | BaseInput._buildElementTree | train | def _buildElementTree(self,):
"""Turn object into an ElementTree
"""
t_elt = ctree.Element(self.name)
for k,v in [ (key,value) for key,value in self.__dict__.items() if key != 'name']: # Excluding name from list of items
if v and v != 'false' :
t_elt.set(k if k != 'like' else 'as', str(v).lower())
self._etree = t_elt
return t_elt | python | {
"resource": ""
} |
q42947 | BasePaging._buildElementTree | train | def _buildElementTree(self,):
"""Turn object into an Element Tree
"""
t_paging = ctree.Element('paging')
t_paging.set('model', self.model)
for key in self.__dict__.keys():
if key != 'model':
t_tag = ctree.SubElement(t_paging, key)
for item in self.__dict__[key].items():
t_tag.set(*item)
self.etree = t_paging
return t_paging | python | {
"resource": ""
} |
q42948 | get_application_choices | train | def get_application_choices():
"""
Get the select options for the application selector
:return:
"""
result = []
keys = set()
for ct in ContentType.objects.order_by('app_label', 'model'):
try:
if issubclass(ct.model_class(), TranslatableModel) and ct.app_label not in keys:
result.append(('{}'.format(ct.app_label), '{}'.format(ct.app_label.capitalize())))
keys.add(ct.app_label)
except TypeError:
continue
return result | python | {
"resource": ""
} |
q42949 | get_model_choices | train | def get_model_choices():
"""
Get the select options for the model selector
:return:
"""
result = []
for ct in ContentType.objects.order_by('app_label', 'model'):
try:
if issubclass(ct.model_class(), TranslatableModel):
result.append(
('{} - {}'.format(ct.app_label, ct.model.lower()),
'{} - {}'.format(ct.app_label.capitalize(), ct.model_class()._meta.verbose_name_plural))
)
except TypeError:
continue
return result | python | {
"resource": ""
} |
q42950 | has_field | train | def has_field(mc, field_name):
"""
detect if a model has a given field has
:param field_name:
:param mc:
:return:
"""
try:
mc._meta.get_field(field_name)
except FieldDoesNotExist:
return False
return True | python | {
"resource": ""
} |
q42951 | reader | train | def reader(f):
'''CSV Reader factory for CADA format'''
return unicodecsv.reader(f, encoding='utf-8', delimiter=b',', quotechar=b'"') | python | {
"resource": ""
} |
q42952 | writer | train | def writer(f):
'''CSV writer factory for CADA format'''
return unicodecsv.writer(f, encoding='utf-8', delimiter=b',', quotechar=b'"') | python | {
"resource": ""
} |
q42953 | from_row | train | def from_row(row):
'''Create an advice from a CSV row'''
subject = (row[5][0].upper() + row[5][1:]) if row[5] else row[5]
return Advice.objects.create(
id=row[0],
administration=cleanup(row[1]),
type=row[2],
session=datetime.strptime(row[4], '%d/%m/%Y'),
subject=cleanup(subject),
topics=[t.title() for t in cleanup(row[6]).split(', ')],
tags=[tag.strip() for tag in row[7].split(',') if tag.strip()],
meanings=cleanup(row[8]).replace(' / ', '/').split(', '),
part=_part(row[9]),
content=cleanup(row[10]),
) | python | {
"resource": ""
} |
q42954 | to_row | train | def to_row(advice):
'''Serialize an advice into a CSV row'''
return [
advice.id,
advice.administration,
advice.type,
advice.session.year,
advice.session.strftime('%d/%m/%Y'),
advice.subject,
', '.join(advice.topics),
', '.join(advice.tags),
', '.join(advice.meanings),
ROMAN_NUMS.get(advice.part, ''),
advice.content,
] | python | {
"resource": ""
} |
q42955 | clean_dict | train | def clean_dict(data):
"""Remove None-valued keys from a dictionary, recursively."""
if is_mapping(data):
out = {}
for k, v in data.items():
if v is not None:
out[k] = clean_dict(v)
return out
elif is_sequence(data):
return [clean_dict(d) for d in data if d is not None]
return data | python | {
"resource": ""
} |
q42956 | keys_values | train | def keys_values(data, *keys):
"""Get an entry as a list from a dict. Provide a fallback key."""
values = []
if is_mapping(data):
for key in keys:
if key in data:
values.extend(ensure_list(data[key]))
return values | python | {
"resource": ""
} |
q42957 | userinput | train | def userinput(prompttext="", times=1):
"""
Get the input of the user via a universally secure method.
:type prompttext: string
:param prompttext: The text to display while receiving the data.
:type times: integer
:param times: The amount of times to ask the user. If value is not 1, a list will be returned. Default is 1.
:return: What the user typed in.
:rtype: string
"""
# If times is 1
if times == 1:
# Return the result
return input(str(prompttext))
# Create new empty list
inputlist = []
# For each time in range
for _ in range(times):
# Append the result of another input request
inputlist.append(input(str(prompttext)))
# Return the final result
return inputlist | python | {
"resource": ""
} |
q42958 | shellinput | train | def shellinput(initialtext='>> ', splitpart=' '):
"""
Give the user a shell-like interface to enter commands which
are returned as a multi-part list containing the command
and each of the arguments.
:type initialtext: string
:param initialtext: Set the text to be displayed as the prompt.
:type splitpart: string
:param splitpart: The character to split when generating the list item.
:return: A string of the user's input or a list of the user's input split by the split character.
:rtype: string or list
"""
# Get the user's input
shelluserinput = input(str(initialtext))
# Return the computed result
return shelluserinput if splitpart in (
'', None) else shelluserinput.split(splitpart) | python | {
"resource": ""
} |
q42959 | splitstring | train | def splitstring(string, splitcharacter=' ', part=None):
"""
Split a string based on a character and get the parts as a list.
:type string: string
:param string: The string to split.
:type splitcharacter: string
:param splitcharacter: The character to split for the string.
:type part: integer
:param part: Get a specific part of the list.
:return: The split string or a specific part of it
:rtype: list or string
>>> splitstring('hello world !')
['hello', 'world', '!']
>>> splitstring('hello world !', ' ', None)
['hello', 'world', '!']
>>> splitstring('hello world !', ' ', None)
['hello', 'world', '!']
>>> splitstring('hello world !', ' ', 0)
'hello'
"""
# If the part is empty
if part in [None, '']:
# Return an array of the splitted text
return str(string).split(splitcharacter)
# Return an array of the splitted text with a specific part
return str(string).split(splitcharacter)[part] | python | {
"resource": ""
} |
q42960 | pykeyword | train | def pykeyword(operation='list', keywordtotest=None):
"""
Check if a keyword exists in the Python keyword dictionary.
:type operation: string
:param operation: Whether to list or check the keywords. Possible options are 'list' and 'in'.
:type keywordtotest: string
:param keywordtotest: The keyword to check.
:return: The list of keywords or if a keyword exists.
:rtype: list or boolean
>>> "True" in pykeyword("list")
True
>>> pykeyword("in", "True")
True
>>> pykeyword("in", "foo")
False
>>> pykeyword("foo", "foo")
Traceback (most recent call last):
...
ValueError: Invalid operation specified.
"""
# If the operation was 'list'
if operation == 'list':
# Return an array of keywords
return str(keyword.kwlist)
# If the operation was 'in'
elif operation == 'in':
# Return a boolean for if the string was a keyword
return keyword.iskeyword(str(keywordtotest))
# Raise a warning
raise ValueError("Invalid operation specified.") | python | {
"resource": ""
} |
q42961 | warnconfig | train | def warnconfig(action='default'):
"""
Configure the Python warnings.
:type action: string
:param action: The configuration to set. Options are: 'default', 'error', 'ignore', 'always', 'module' and 'once'.
"""
# If action is 'default'
if action.lower() == 'default':
# Change warning settings
warnings.filterwarnings('default')
# If action is 'error'
elif action.lower() == 'error':
# Change warning settings
warnings.filterwarnings('error')
# If action is 'ignore'
elif action.lower() == 'ignore':
# Change warning settings
warnings.filterwarnings('ignore')
# If action is 'always'
elif action.lower() == 'always':
# Change warning settings
warnings.filterwarnings('always')
# If action is 'module'
elif action.lower() == 'module':
# Change warning settings
warnings.filterwarnings('module')
# If action is 'once'
elif action.lower() == 'once':
# Change warning settings
warnings.filterwarnings('once')
# Raise runtime warning
raise ValueError("Invalid action specified.") | python | {
"resource": ""
} |
q42962 | happybirthday | train | def happybirthday(person):
"""
Sing Happy Birthday
"""
print('Happy Birthday To You')
time.sleep(2)
print('Happy Birthday To You')
time.sleep(2)
print('Happy Birthday Dear ' + str(person[0].upper()) + str(person[1:]))
time.sleep(2)
print('Happy Birthday To You') | python | {
"resource": ""
} |
q42963 | convertbinary | train | def convertbinary(value, argument):
"""
Convert text to binary form or backwards.
:type value: string
:param value: The text or the binary text
:type argument: string
:param argument: The action to perform on the value. Can be "to" or "from".
"""
if argument == 'to':
return bin(value)
elif argument == 'from':
return format(value)
raise ValueError("Invalid argument specified.") | python | {
"resource": ""
} |
q42964 | reversetext | train | def reversetext(contenttoreverse, reconvert=True):
"""
Reverse any content
:type contenttoreverse: string
:param contenttoreverse: The content to be reversed
:type reeval: boolean
:param reeval: Wether or not to reconvert the object back into it's initial state. Default is "True".
"""
# If reconvert is specified
if reconvert is True:
# Return the evalated form
return eval(
str(type(contenttoreverse)).split("'")[1] + "('" +
str(contenttoreverse)[::-1] + "')")
# Return the raw version
return contenttoreverse[::-1] | python | {
"resource": ""
} |
q42965 | convertascii | train | def convertascii(value, command='to'):
"""
Convert an ASCII value to a symbol
:type value: string
:param value: The text or the text in ascii form.
:type argument: string
:param argument: The action to perform on the value. Can be "to" or "from".
"""
command = command.lower()
if command == 'to':
return chr(value)
elif command == 'from':
return ord(value)
else:
raise ValueError('Invalid operation provided.') | python | {
"resource": ""
} |
q42966 | availchars | train | def availchars(charactertype):
"""
Get all the available characters for a specific type.
:type charactertype: string
:param charactertype: The characters to get. Can be 'letters', 'lowercase, 'uppercase', 'digits', 'hexdigits', 'punctuation', 'printable', 'whitespace' or 'all'.
>>> availchars("lowercase")
'abcdefghijklmnopqrstuvwxyz'
"""
# If the lowercase version of the character type is 'letters'
if charactertype.lower() == 'letters':
# Return the result
return string.ascii_letters
# If the lowercase version of the character type is 'lowercase'
elif charactertype.lower() == 'lowercase':
# Return the result
return string.ascii_lowercase
# If the lowercase version of the character type is 'uppercase'
elif charactertype.lower() == 'uppercase':
# Return the result
return string.ascii_uppercase
# If the lowercase version of the character type is 'digits'
elif charactertype.lower() == 'digits':
# Return the result
return string.digits
# If the lowercase version of the character type is 'hexdigits'
elif charactertype.lower() == 'hexdigits':
# Return the result
return string.hexdigits
# If the lowercase version of the character type is 'punctuation'
elif charactertype.lower() == 'punctuation':
# Return the result
return string.punctuation
# If the lowercase version of the character type is 'printable'
elif charactertype.lower() == 'printable':
# Return the result
return string.printable
# If the lowercase version of the character type is 'whitespace'
elif charactertype.lower() == 'whitespace':
# Return the result
return string.whitespace
# If the lowercase version of the character type is 'all'
elif charactertype.lower() == 'all':
# Return the result
return string.ascii_letters + string.ascii_lowercase + string.ascii_uppercase + string.digits + string.hexdigits + string.punctuation + string.printable + string.whitespace
# Raise a warning
raise ValueError("Invalid character type provided.") | python | {
"resource": ""
} |
q42967 | textbetween | train | def textbetween(variable,
firstnum=None,
secondnum=None,
locationoftext='regular'):
"""
Get The Text Between Two Parts
"""
if locationoftext == 'regular':
return variable[firstnum:secondnum]
elif locationoftext == 'toend':
return variable[firstnum:]
elif locationoftext == 'tostart':
return variable[:secondnum] | python | {
"resource": ""
} |
q42968 | letternum | train | def letternum(letter):
"""
Get The Number Corresponding To A Letter
"""
if not isinstance(letter, str):
raise TypeError("Invalid letter provided.")
if not len(letter) == 1:
raise ValueError("Invalid letter length provided.")
letter = letter.lower()
alphaletters = string.ascii_lowercase
for i in range(len(alphaletters)):
if letter[0] == alphaletters[i]:
return i + 1 | python | {
"resource": ""
} |
q42969 | wordvalue | train | def wordvalue(word):
"""
Get the value of each letter of a string's position in the alphabet added up
:type word: string
:param word: The word to find the value of
"""
# Set total to 0
total = 0
# For each character of word
for i in enumerate(word):
# Add it's letter value to total
total += letternum(word[i[0]])
# Return the final value
return total | python | {
"resource": ""
} |
q42970 | spacelist | train | def spacelist(listtospace, spacechar=" "):
"""
Convert a list to a string with all of the list's items spaced out.
:type listtospace: list
:param listtospace: The list to space out.
:type spacechar: string
:param spacechar: The characters to insert between each list item. Default is: " ".
"""
output = ''
space = ''
output += str(listtospace[0])
space += spacechar
for listnum in range(1, len(listtospace)):
output += space
output += str(listtospace[listnum])
return output | python | {
"resource": ""
} |
q42971 | numlistbetween | train | def numlistbetween(num1, num2, option='list', listoption='string'):
"""
List Or Count The Numbers Between Two Numbers
"""
if option == 'list':
if listoption == 'string':
output = ''
output += str(num1)
for currentnum in range(num1 + 1, num2 + 1):
output += ','
output += str(currentnum)
elif listoption == 'list':
output = []
for currentnum in range(num1, num2 + 1):
output.append(str(currentnum))
return output
elif option == 'count':
return num2 - num1 | python | {
"resource": ""
} |
q42972 | textalign | train | def textalign(text, maxlength, align='left'):
"""
Align Text When Given Full Length
"""
if align == 'left':
return text
elif align == 'centre' or align == 'center':
spaces = ' ' * (int((maxlength - len(text)) / 2))
elif align == 'right':
spaces = (maxlength - len(text))
else:
raise ValueError("Invalid alignment specified.")
return spaces + text | python | {
"resource": ""
} |
q42973 | shapesides | train | def shapesides(inputtocheck, inputtype='shape'):
"""
Get the sides of a shape.
inputtocheck:
The amount of sides or the shape to be checked,
depending on the value of inputtype.
inputtype:
The type of input provided.
Can be: 'shape', 'sides'.
"""
# Define the array of sides to a shape
shapestosides = {
'triangle': 3,
'square': 4,
'pentagon': 5,
'hexagon': 6,
'heptagon': 7,
'octagon': 8,
'nonagon': 9,
'decagon': 10,
'hendecagon': 11,
'dodecagon': 12,
'triskaidecagon': 13,
'tetrakaidecagon': 14,
'pentadecagon': 15,
'hexakaidecagon': 16,
'heptadecagon': 17,
'octakaidecagon': 18,
'enneadecagon': 19,
'icosagon': 20,
'triacontagon': 30,
'tetracontagon': 40,
'pentacontagon': 50,
'hexacontagon': 60,
'heptacontagon': 70,
'octacontagon': 80,
'enneacontagon': 90,
'hectagon': 100,
'chiliagon': 1000,
'myriagon': 10000,
'megagon': 1000000,
'googolgon': pow(10, 100),
'ngon': 'n'
}
# Define an array with the flipped version of the sides to a shape
sidestoshapes = dictflip(shapestosides)
# If the lowercase version of the input type is 'shape'
if inputtype.lower() == 'shape':
# If the lowercase version of the shape is in the array
if inputtocheck.lower() in shapestosides:
# Return the corresponding sides
return shapestosides[inputtocheck.lower()]
# Return 'n'
return shapestosides['n']
if inputtype.lower() == 'sides':
# If the lowercase version of the shape is in the array
if inputtocheck.lower() in sidestoshapes:
# Return the corresponding sides
return sidestoshapes[inputtocheck.lower()]
# Return 'ngon'
return sidestoshapes['ngon']
# Raise a warning
raise ValueError("Invalid input type.") | python | {
"resource": ""
} |
q42974 | autosolve | train | def autosolve(equation):
"""
Automatically solve an easy maths problem.
:type equation: string
:param equation: The equation to calculate.
>>> autosolve("300 + 600")
900
"""
try:
# Try to set a variable to an integer
num1 = int(equation.split(" ")[0])
except ValueError:
# Try to set a variable to a decimal
num1 = float(equation.split(" ")[0])
try:
# Try to set a variable to an integer
num2 = int(equation.split(" ")[2])
except ValueError:
# Try to set a variable to a decimal
num2 = float(equation.split(" ")[2])
# If the lowercase version of the operator is '+', 'plus' or 'add'
if equation.split(" ")[1].lower() in ["+", "plus", "add"]:
# Return the answer
return num1 + num2
# If the lowercase version of the operator is '-', 'minus' or 'subtract'
elif equation.split(" ")[1].lower() in ["-", "minus", "subtract"]:
# Return the answer
return num1 - num2
# If the lowercase version of the operator is '*', 'times', 'multiply'
elif equation.split(" ")[1].lower() in ["*", "times", "multiply"]:
# Return the answer
return num1 * num2
# If the lowercase version of the operator is '/', 'divide' or 'quotient'
elif equation.split(" ")[1].lower() in ["/", "divide", "quotient"]:
# Return the answer
return num1 / num2
# If the lowercase version of the operator is '%, 'remainder' or 'rem'
elif equation.split(" ")[1].lower() in ["%", "remainder", "rem"]:
# Return the answer
return num1 % num2
# Raise a warning
raise ValueError("Invalid operation provided.") | python | {
"resource": ""
} |
q42975 | autohard | train | def autohard(equation):
"""
Automatically solve a hard maths problem.
:type equation: string
:param equation: The equation to solve.
>>> autohard("log 10")
2.302585092994046
"""
try:
# Try to set a variable to an integer
num1 = int(equation.split(" ")[1])
except ValueError:
# Try to set a variable to a decimal
num1 = float(equation.split(" ")[1])
# If the lowercase version of the operation equals 'log'
if equation.split(" ")[0].lower() == "log":
# Return the answer
return math.log(num1)
# If the lowercase version of the operation equals 'acos'
elif equation.split(" ")[0].lower() == "acos":
# Return the answer
return math.acos(num1)
# If the lowercase version of the operation equals 'asin'
elif equation.split(" ")[0].lower() == "asin":
# Return the answer
return math.asin(num1)
# If the lowercase version of the operation equals 'atan'
elif equation.split(" ")[0].lower() == "atan":
# Return the answer
return math.atan(num1)
# If the lowercase version of the operation equals 'cos'
elif equation.split(" ")[0].lower() == "cos":
# Return the answer
return math.cos(num1)
# If the lowercase version of the operation equals 'hypot'
elif equation.split(" ")[0].lower() == "hypot":
try:
# Try to set a variable to an integer
num2 = int(equation.split(" ")[2])
except ValueError:
# Try to set a variable to an decimal
num2 = float(equation.split(" ")[2])
# Return the answer
return math.hypot(num1, num2)
# If the lowercase version of the operation equals 'sin'
elif equation.split(" ")[0].lower() == "sin":
# Return the answer
return math.sin(num1)
# If the lowercase version of the operation equals 'tan'
elif equation.split(" ")[0].lower() == "tan":
# Return the answer
return math.tan(num1)
# Raise a warning
raise ValueError("Invalid operation entered.") | python | {
"resource": ""
} |
q42976 | equation | train | def equation(operation, firstnum, secondnum):
"""
Solve a simple maths equation manually
"""
if operation == 'plus':
return firstnum + secondnum
elif operation == 'minus':
return firstnum - secondnum
elif operation == 'multiply':
return firstnum * secondnum
elif operation == 'divide':
if not secondnum == 0:
return firstnum / secondnum
raise ZeroDivisionError("Unable to divide by 0.")
raise ValueError('Invalid operation provided.') | python | {
"resource": ""
} |
q42977 | scientific | train | def scientific(number, operation, number2=None, logbase=10):
"""
Solve scientific operations manually
"""
if operation == 'log':
return math.log(number, logbase)
elif operation == 'acos':
return math.acos(number)
elif operation == 'asin':
return math.asin(number)
elif operation == 'atan':
return math.atan(number)
elif operation == 'cos':
return math.cos(number)
elif operation == 'hypot':
return math.hypot(number, number2)
elif operation == 'sin':
return math.sin(number)
elif operation == 'tan':
return math.tan(number) | python | {
"resource": ""
} |
q42978 | fracsimplify | train | def fracsimplify(numerator, denominator):
"""
Simplify a fraction.
:type numerator: integer
:param numerator: The numerator of the fraction to simplify
:type denominator: integer
:param denominator: The denominator of the fraction to simplify
:return: The simplified fraction
:rtype: list
"""
# If the numerator is the same as the denominator
if numerator == denominator:
# Return the most simplified fraction
return '1/1'
# If the numerator is larger than the denominator
elif int(numerator) > int(denominator):
# Set the limit to half of the numerator
limit = int(numerator / 2)
elif int(numerator) < int(denominator):
# Set the limit to half of the denominator
limit = int(denominator / 2)
# For each item in range from 2 to the limit
for i in range(2, limit):
# Set the number to check as the limit minus i
checknum = limit - i
# If the number is divisible by the numerator and denominator
if numerator % checknum == 0 and denominator % checknum == 0:
# Set the numerator to half of the number
numerator = numerator / checknum
# Set the denominator to half of the number
denominator = denominator / checknum
# Return the integer version of the numerator and denominator
return [int(numerator), int(denominator)] | python | {
"resource": ""
} |
q42979 | circleconvert | train | def circleconvert(amount, currentformat, newformat):
"""
Convert a circle measurement.
:type amount: number
:param amount: The number to convert.
:type currentformat: string
:param currentformat: The format of the provided value.
:type newformat: string
:param newformat: The intended format of the value.
>>> circleconvert(45, "radius", "diameter")
90
"""
# If the same format was provided
if currentformat.lower() == newformat.lower():
# Return the provided value
return amount
# If the lowercase version of the current format is 'radius'
if currentformat.lower() == 'radius':
# If the lowercase version of the new format is 'diameter'
if newformat.lower() == 'diameter':
# Return the converted value
return amount * 2
# If the lowercase version of the new format is 'circumference'
elif newformat.lower() == 'circumference':
# Return the converted value
return amount * 2 * math.pi
# Raise a warning
raise ValueError("Invalid new format provided.")
# If the lowercase version of the current format is 'diameter'
elif currentformat.lower() == 'diameter':
# If the lowercase version of the new format is 'radius'
if newformat.lower() == 'radius':
# Return the converted value
return amount / 2
# If the lowercase version of the new format is 'circumference'
elif newformat.lower() == 'circumference':
# Return the converted value
return amount * math.pi
# Raise a warning
raise ValueError("Invalid new format provided.")
# If the lowercase version of the current format is 'circumference'
elif currentformat.lower() == 'circumference':
# If the lowercase version of the new format is 'radius'
if newformat.lower() == 'radius':
# Return the converted value
return amount / math.pi / 2
# If the lowercase version of the new format is 'diameter'
elif newformat.lower() == 'diameter':
# Return the converted value
return amount / math.pi | python | {
"resource": ""
} |
q42980 | amountdiv | train | def amountdiv(number, minnum, maxnum):
"""
Get the amount of numbers divisable by a number.
:type number: number
:param number: The number to use.
:type minnum: integer
:param minnum: The minimum number to check.
:type maxnum: integer
:param maxnum: The maximum number to check.
>>> amountdiv(20, 1, 15)
5
"""
# Set the amount to 0
amount = 0
# For each item in range of minimum and maximum
for i in range(minnum, maxnum + 1):
# If the remainder of the divided number is 0
if number % i == 0:
# Add 1 to the total amount
amount += 1
# Return the result
return amount | python | {
"resource": ""
} |
q42981 | constant | train | def constant(constanttype):
"""
Get A Constant
"""
constanttype = constanttype.lower()
if constanttype == 'pi':
return math.pi
elif constanttype == 'e':
return math.e
elif constanttype == 'tau':
return math.tau
elif constanttype == 'inf':
return math.inf
elif constanttype == 'nan':
return math.nan
elif constanttype in ['phi', 'golden']:
return (1 + 5**0.5) / 2 | python | {
"resource": ""
} |
q42982 | average | train | def average(numbers, averagetype='mean'):
"""
Find the average of a list of numbers
:type numbers: list
:param numbers: The list of numbers to find the average of.
:type averagetype: string
:param averagetype: The type of average to find.
>>> average([1, 2, 3, 4, 5], 'median')
3
"""
try:
# Try to get the mean of the numbers
statistics.mean(numbers)
except RuntimeError:
# Raise a warning
raise ValueError('Unable to parse the list.')
# If the lowercase version of the average type is 'mean'
if averagetype.lower() == 'mean':
# Return the answer
return statistics.mean(numbers)
# If the lowercase version of the average type is 'mode'
elif averagetype.lower() == 'mode':
# Return the answer
return statistics.mode(numbers)
# If the lowercase version of the average type is 'median'
elif averagetype.lower() == 'median':
# Return the answer
return statistics.median(numbers)
# If the lowercase version of the average type is 'min'
elif averagetype.lower() == 'min':
# Return the answer
return min(numbers)
# If the lowercase version of the average type is 'max'
elif averagetype.lower() == 'max':
# Return the answer
return max(numbers)
# If the lowercase version of the average type is 'range'
elif averagetype.lower() == 'range':
# Return the answer
return max(numbers) - min(numbers)
# Raise a warning
raise ValueError('Invalid average type provided.') | python | {
"resource": ""
} |
q42983 | numprop | train | def numprop(value, propertyexpected):
"""
Check If A Number Is A Type
"""
if propertyexpected == 'triangular':
x = (math.sqrt(8 * value + 1) - 1) / 2
return bool(x - int(x) > 0)
elif propertyexpected == 'square':
return math.sqrt(value).is_integer()
elif propertyexpected == 'cube':
x = value**(1 / 3)
x = int(round(x))
return bool(x**3 == value)
elif propertyexpected == 'even':
return value % 2 == 0
elif propertyexpected == 'odd':
return not value % 2 == 0
elif propertyexpected == 'positive':
return bool(value > 0)
elif propertyexpected == 'negative':
return bool(value < 0)
elif propertyexpected == 'zero':
return bool(value == 0) | python | {
"resource": ""
} |
q42984 | compare | train | def compare(value1, value2, comparison):
"""
Compare 2 values
:type value1: object
:param value1: The first value to compare.
:type value2: object
:param value2: The second value to compare.
:type comparison: string
:param comparison: The comparison to make. Can be "is", "or", "and".
:return: If the value is, or, and of another value
:rtype: boolean
"""
if not isinstance(comparison, str):
raise TypeError("Comparison argument must be a string.")
if comparison == 'is':
return value1 == value2
elif comparison == 'or':
return value1 or value2
elif comparison == 'and':
return value1 and value2
raise ValueError("Invalid comparison operator specified.") | python | {
"resource": ""
} |
q42985 | factors | train | def factors(number):
"""
Find all of the factors of a number and return it as a list.
:type number: integer
:param number: The number to find the factors for.
"""
if not (isinstance(number, int)):
raise TypeError(
"Incorrect number type provided. Only integers are accepted.")
factors = []
for i in range(1, number + 1):
if number % i == 0:
factors.append(i)
return factors | python | {
"resource": ""
} |
q42986 | randomnum | train | def randomnum(minimum=1, maximum=2, seed=None):
"""
Generate a random number.
:type minimum: integer
:param minimum: The minimum number to generate.
:type maximum: integer
:param maximum: The maximum number to generate.
:type seed: integer
:param seed: A seed to use when generating the random number.
:return: The randomized number.
:rtype: integer
:raises TypeError: Minimum number is not a number.
:raises TypeError: Maximum number is not a number.
>>> randomnum(1, 100, 150)
42
"""
if not (isnum(minimum)):
raise TypeError("Minimum number is not a number.")
if not (isnum(maximum)):
raise TypeError("Maximum number is not a number.")
if seed is None:
return random.randint(minimum, maximum)
random.seed(seed)
return random.randint(minimum, maximum) | python | {
"resource": ""
} |
q42987 | tokhex | train | def tokhex(length=10, urlsafe=False):
"""
Return a random string in hexadecimal
"""
if urlsafe is True:
return secrets.token_urlsafe(length)
return secrets.token_hex(length) | python | {
"resource": ""
} |
q42988 | isfib | train | def isfib(number):
"""
Check if a number is in the Fibonacci sequence.
:type number: integer
:param number: Number to check
"""
num1 = 1
num2 = 1
while True:
if num2 < number:
tempnum = num2
num2 += num1
num1 = tempnum
elif num2 == number:
return True
else:
return False | python | {
"resource": ""
} |
q42989 | isprime | train | def isprime(number):
"""
Check if a number is a prime number
:type number: integer
:param number: The number to check
"""
if number == 1:
return False
for i in range(2, int(number**0.5) + 1):
if number % i == 0:
return False
return True | python | {
"resource": ""
} |
q42990 | convertbase | train | def convertbase(number, base=10):
"""
Convert a number in base 10 to another base
:type number: number
:param number: The number to convert
:type base: integer
:param base: The base to convert to.
"""
integer = number
if not integer:
return '0'
sign = 1 if integer > 0 else -1
alphanum = string.digits + string.ascii_lowercase
nums = alphanum[:base]
res = ''
integer *= sign
while integer:
integer, mod = divmod(integer, base)
res += nums[mod]
return ('' if sign == 1 else '-') + res[::-1] | python | {
"resource": ""
} |
q42991 | quadrant | train | def quadrant(xcoord, ycoord):
"""
Find the quadrant a pair of coordinates are located in
:type xcoord: integer
:param xcoord: The x coordinate to find the quadrant for
:type ycoord: integer
:param ycoord: The y coordinate to find the quadrant for
"""
xneg = bool(xcoord < 0)
yneg = bool(ycoord < 0)
if xneg is True:
if yneg is False:
return 2
return 3
if yneg is False:
return 1
return 4 | python | {
"resource": ""
} |
q42992 | flipcoords | train | def flipcoords(xcoord, ycoord, axis):
"""
Flip the coordinates over a specific axis, to a different quadrant
:type xcoord: integer
:param xcoord: The x coordinate to flip
:type ycoord: integer
:param ycoord: The y coordinate to flip
:type axis: string
:param axis: The axis to flip across. Could be 'x' or 'y'
"""
axis = axis.lower()
if axis == 'y':
if xcoord > 0:
return str(xcoord - xcoord - xcoord) + ', ' + str(ycoord)
elif xcoord < 0:
return str(xcoord + abs(xcoord) * 2) + ', ' + str(ycoord)
elif xcoord == 0:
return str(xcoord) + ', ' + str(ycoord)
raise ValueError(
"The X coordinate is neither larger, smaller or the same as 0.")
elif axis == 'x':
if ycoord > 0:
return str(xcoord) + ', ' + str(ycoord - ycoord - ycoord)
elif ycoord < 0:
return str(ycoord + abs(ycoord) * 2) + ', ' + str(xcoord)
elif ycoord == 0:
return str(xcoord) + ', ' + str(ycoord)
raise ValueError(
"The Y coordinate is neither larger, smaller or the same as 0.")
raise ValueError("Invalid axis. Neither x nor y was specified.") | python | {
"resource": ""
} |
q42993 | lcm | train | def lcm(num1, num2):
"""
Find the lowest common multiple of 2 numbers
:type num1: number
:param num1: The first number to find the lcm for
:type num2: number
:param num2: The second number to find the lcm for
"""
if num1 > num2:
bigger = num1
else:
bigger = num2
while True:
if bigger % num1 == 0 and bigger % num2 == 0:
return bigger
bigger += 1 | python | {
"resource": ""
} |
q42994 | hcf | train | def hcf(num1, num2):
"""
Find the highest common factor of 2 numbers
:type num1: number
:param num1: The first number to find the hcf for
:type num2: number
:param num2: The second number to find the hcf for
"""
if num1 > num2:
smaller = num2
else:
smaller = num1
for i in range(1, smaller + 1):
if ((num1 % i == 0) and (num2 % i == 0)):
return i | python | {
"resource": ""
} |
q42995 | randstring | train | def randstring(length=1):
"""
Generate a random string consisting of letters, digits and punctuation
:type length: integer
:param length: The length of the generated string.
"""
charstouse = string.ascii_letters + string.digits + string.punctuation
newpass = ''
for _ in range(length):
newpass += str(charstouse[random.randint(0, len(charstouse) - 1)])
return newpass | python | {
"resource": ""
} |
q42996 | case | train | def case(text, casingformat='sentence'):
"""
Change the casing of some text.
:type text: string
:param text: The text to change the casing of.
:type casingformat: string
:param casingformat: The format of casing to apply to the text. Can be 'uppercase', 'lowercase', 'sentence' or 'caterpillar'.
:raises ValueError: Invalid text format specified.
>>> case("HELLO world", "uppercase")
'HELLO WORLD'
"""
# If the lowercase version of the casing format is 'uppercase'
if casingformat.lower() == 'uppercase':
# Return the uppercase version
return str(text.upper())
# If the lowercase version of the casing format is 'lowercase'
elif casingformat.lower() == 'lowercase':
# Return the lowercase version
return str(text.lower())
# If the lowercase version of the casing format is 'sentence'
elif casingformat.lower() == 'sentence':
# Return the sentence case version
return str(text[0].upper()) + str(text[1:])
# If the lowercase version of the casing format is 'caterpillar'
elif casingformat.lower() == 'caterpillar':
# Return the caterpillar case version
return str(text.lower().replace(" ", "_"))
# Raise a warning
raise ValueError("Invalid text format specified.") | python | {
"resource": ""
} |
q42997 | encryptstring | train | def encryptstring(text, password):
"""
Encrypt a string according to a specific password.
:type text: string
:param text: The text to encrypt.
:type pass: string
:param pass: The password to encrypt the text with.
"""
enc = []
for i in enumerate(text):
key_c = password[i[0] % len(password)]
enc_c = chr((ord(i[1]) + ord(key_c)) % 256)
enc.append(enc_c)
return base64.urlsafe_b64encode("".join(enc).encode()).decode() | python | {
"resource": ""
} |
q42998 | decryptstring | train | def decryptstring(enc, password):
"""
Decrypt an encrypted string according to a specific password.
:type enc: string
:param enc: The encrypted text.
:type pass: string
:param pass: The password used to encrypt the text.
"""
dec = []
enc = base64.urlsafe_b64decode(enc).decode()
for i in enumerate(enc):
key_c = password[i[0] % len(password)]
dec_c = chr((256 + ord(i[1]) - ord(key_c)) % 256)
dec.append(dec_c)
return "".join(dec) | python | {
"resource": ""
} |
q42999 | pipinstall | train | def pipinstall(packages):
"""
Install one or more pip packages.
:type packages: string or list
:param packages: The package or list of packages to install.
:raises TypeError: Nor a string or a list was provided.
"""
if isinstance(packages, str):
if hasattr(pip, 'main'):
pip.main(['install', packages])
else:
pip._internal.main(['install', packages])
elif isinstance(packages, list):
for i in enumerate(packages):
if hasattr(pip, 'main'):
pip.main(['install', i[1]])
else:
pip._internal.main(['install', i[1]])
else:
raise TypeError("Nor a string or a list was provided.") | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.