id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
246,700 | mattimck/python-exist | exist/exist.py | Exist.arquire_attributes | def arquire_attributes(self, attributes, active=True):
"""
Claims a list of attributes for the current client.
Can also disable attributes. Returns update response object.
"""
attribute_update = self._post_object(self.update_api.attributes.acquire, attributes)
return ExistAttributeResponse(attribute_update) | python | def arquire_attributes(self, attributes, active=True):
"""
Claims a list of attributes for the current client.
Can also disable attributes. Returns update response object.
"""
attribute_update = self._post_object(self.update_api.attributes.acquire, attributes)
return ExistAttributeResponse(attribute_update) | [
"def",
"arquire_attributes",
"(",
"self",
",",
"attributes",
",",
"active",
"=",
"True",
")",
":",
"attribute_update",
"=",
"self",
".",
"_post_object",
"(",
"self",
".",
"update_api",
".",
"attributes",
".",
"acquire",
",",
"attributes",
")",
"return",
"ExistAttributeResponse",
"(",
"attribute_update",
")"
] | Claims a list of attributes for the current client.
Can also disable attributes. Returns update response object. | [
"Claims",
"a",
"list",
"of",
"attributes",
"for",
"the",
"current",
"client",
".",
"Can",
"also",
"disable",
"attributes",
".",
"Returns",
"update",
"response",
"object",
"."
] | 2c4be9d176d8e8007c4e020ee7cd6263a2096abb | https://github.com/mattimck/python-exist/blob/2c4be9d176d8e8007c4e020ee7cd6263a2096abb/exist/exist.py#L72-L78 |
246,701 | mattimck/python-exist | exist/exist.py | Exist.owned_attributes | def owned_attributes(self):
"""
Returns a list of attributes owned by this service.
"""
attributes = self._get_object(self.update_api.attributes.owned)
return [ExistOwnedAttributeResponse(attribute) for attribute in attributes] | python | def owned_attributes(self):
"""
Returns a list of attributes owned by this service.
"""
attributes = self._get_object(self.update_api.attributes.owned)
return [ExistOwnedAttributeResponse(attribute) for attribute in attributes] | [
"def",
"owned_attributes",
"(",
"self",
")",
":",
"attributes",
"=",
"self",
".",
"_get_object",
"(",
"self",
".",
"update_api",
".",
"attributes",
".",
"owned",
")",
"return",
"[",
"ExistOwnedAttributeResponse",
"(",
"attribute",
")",
"for",
"attribute",
"in",
"attributes",
"]"
] | Returns a list of attributes owned by this service. | [
"Returns",
"a",
"list",
"of",
"attributes",
"owned",
"by",
"this",
"service",
"."
] | 2c4be9d176d8e8007c4e020ee7cd6263a2096abb | https://github.com/mattimck/python-exist/blob/2c4be9d176d8e8007c4e020ee7cd6263a2096abb/exist/exist.py#L87-L92 |
246,702 | frejanordsiek/GeminiMotorDrive | GeminiMotorDrive/compilers/move_sequence.py | compile_sequence | def compile_sequence(cycles, program_or_profile='program',
unit_converter=None):
""" Makes the command list for a move sequence.
Constructs the list of commands to execute the given sequence of
motion. Program/command line commands or profile commands can be
generated depending on the value of `program_or_profile` so that the
commands can be used to construct a program or profile later. Types
of motion supported (see Notes for how to specify) are moves from
one position to another (the motion will always come to a stop
before doing the next motion), waiting a given interval of time till
starting the next move, and looping over a sequence of moves.
Parameters
----------
cycles : iterable of dicts
The iterable of cycles of motion to do one after another. See
Notes for format.
program_or_profile : {'program', 'profile'}, optional
Whether program or profile motion commands should be used.
Anything other than these two values implies the default.
unit_converter : UnitConverter, optional
``GeminiMotorDrive.utilities.UnitConverter`` to use to convert
the units in `cycles` to motor units. ``None`` indicates that
they are already in motor units.
Returns
-------
commands : list of str
``list`` of ``str`` commands making up the move sequence.
Notes
-----
`cycles` is an iterable of individual cycles of motion. Each cycle
is a ``dict`` that represents a sequence of moves that could
possibly be looped over. The field ``'iterations'`` gives how many
times the sequence of moves should be done (a value > 1 implies a
loop). Then the field ``'moves'`` is an iterable of the individual
moves. Each individual move is a ``dict`` with the acceleration
(``'A'``), deceleration (``'AD'`` with 0 meaning the value of the
acceleration is used), velocity (``'V'``), and the distance/position
(``'D'``). Back in the cycle, the field ``'wait_times'`` is an
iterable of numbers giving the time in seconds to wait after each
move before going onto the next.
See Also
--------
get_sequence_time
convert_sequence_to_motor_units
GeminiMotorDrive.utilities.UnitConverter
Examples
--------
Simple program style two motions with a pause in between.
>>> from GeminiMotorDrive.compilers.move_sequence import *
>>> cycles = [{'iterations':1, 'wait_times':[1, 0],
... 'moves':[{'A':100, 'AD':0, 'D':-1000, 'V':100},
... {'A':90, 'AD':0, 'D':-1000, 'V':100}]}]
>>> compile_sequence(cycles)
['A100',
'AD0',
'V100',
'D-1000',
'GO1',
'WAIT(AS.1=b0)',
'T1',
'A90',
'GO1',
'WAIT(AS.1=b0)']
The same motion but in profile style commands
>>> from GeminiMotorDrive.compilers.move_sequence import *
>>> cycles = [{'iterations':1, 'wait_times':[1, 0],
... 'moves':[{'A':100, 'AD':0, 'D':-1000, 'V':100},
... {'A':90, 'AD':0, 'D':-1000, 'V':100}]}]
>>> compile_sequence(cycles, program_or_profile='profile')
['A100',
'AD100',
'V100',
'D-1000',
'VF0',
'GOBUF1',
'GOWHEN(T=1000)',
'A90',
'AD90',
'VF0',
'GOBUF1']
Another motion with a back and forth loop (100 iterations) in the
middle, done in program style commands.
>>> from GeminiMotorDrive.compilers.move_sequence import *
>>> cycles = [{'iterations':1, 'wait_times':[1],
... 'moves':[{'A':100, 'AD':0, 'D':-1000, 'V':100}]},
... {'iterations':100, 'wait_times':[0, 0],
... 'moves':[{'A':50, 'AD':40, 'D':-1000, 'V':30},
... {'A':50, 'AD':40, 'D':1000, 'V':30}]},
... {'iterations':1, 'wait_times':[0],
... 'moves':[{'A':100, 'AD':0, 'D':1000, 'V':100}]}]
>>> compile_sequence(cycles)
['A100',
'AD0',
'V100',
'D-1000',
'GO1',
'WAIT(AS.1=b0)',
'T1',
'L100',
'A50',
'AD40',
'V30',
'D-1000',
'GO1',
'WAIT(AS.1=b0)',
'D~',
'GO1',
'WAIT(AS.1=b0)',
'LN',
'A100',
'AD0',
'V100',
'GO1',
'WAIT(AS.1=b0)']
"""
# If needed, cycles needs to be converted to motor units.
if unit_converter is None:
cv_cycles = cycles
else:
cv_cycles = convert_sequence_to_motor_units(cycles, \
unit_converter=unit_converter)
# Initially, we have no commands in our command list.
commands = []
# The A, AD, D, and V parameters of the previous motion should be
# kept track of because if they don't change from one motion to the
# next, the commands to set them don't need to be included. They
# will be started blank since there are no previous motions yet.
previous_motion = {'A': [], 'AD': [], 'D': [], 'V': []}
# Construct each cycle one by one.
for cycle in cv_cycles:
# If more than one iteration is being done, a loop needs to be
# setup. It will be either 'L' or 'PLOOP' with the number of
# iterations attached if it is a program or a profile
# respectively. Since it will be tough to keep track of what
# motion changed from the end of a loop to the beginning of it,
# it is easier to just forget all previous motion values and set
# them all at the beginning of the loop (clear previous_motion).
iterations = int(cycle['iterations'])
if iterations > 1:
previous_motion = {'A': [], 'AD': [], 'D': [], 'V': []}
if program_or_profile != 'profile':
commands.append('L' + str(iterations))
else:
commands.append('PLOOP' + str(iterations))
# Construct each individual move in the cycle.
for i in range(0, len(cycle['moves'])):
# Grab the motion indicated by the current move.
new_motion = cycle['moves'][i]
# If we are doing a profile, AD must be set explicitly
# to A if it is 0.
if program_or_profile == 'profile' \
and new_motion['AD'] == 0.0:
new_motion['AD'] = new_motion['A']
# Set A, AD, and V if they have changed.
for k in ('A', 'AD', 'V'):
if previous_motion[k] != new_motion[k]:
# Grab it and round it to 4 places after the decimal
# point because that is the most that is
# supported. Then, if it is an integer value,
# convert it to an integer because that is what the
# drive will send back if requested (makes
# comparisons easier). Then add the command.
val = round(float(new_motion[k]), 4)
if val == int(val):
val = int(val)
commands.append(k + str(val))
# If the sign of D has flipped, we just need to issue a 'D~'
# command. If the value has changed in another way, it needs
# to be reset.
if previous_motion['D'] != new_motion['D']:
if previous_motion['D'] == -new_motion['D']:
commands.append('D~')
else:
commands.append('D'
+ str(int(new_motion['D'])))
# Grab the amount of time that should be waited after the
# move is done.
wait_time = cycle['wait_times'][i]
# Give the motion command (GO or GOBUF), tell the drive to
# wait till the motor has stopped (a WAIT command if it is a
# program and a VF0 command if it is a profile), and make it
# wait the period of time wait_time (T and GOWHEN commands).
if program_or_profile != 'profile':
commands.append('GO1')
commands.append('WAIT(AS.1=b0)')
if wait_time != 0:
# The wait time needs to be rounded to 3 places
# after the decimal. If it is an integer, it should
# be converted to an int so that the drive will send
# back what we send (makes compairisons easier).
wait_time = round(float(wait_time), 3)
if wait_time == int(wait_time):
wait_time = int(wait_time)
commands.append('T' + str(wait_time))
else:
commands.append('VF0')
commands.append('GOBUF1')
if wait_time != 0:
commands.append('GOWHEN(T='
+ str(int(1000*wait_time))
+ ')')
# Before going onto the next move, previous_motion needs to
# be set to the one just done.
previous_motion = new_motion
# Done with all the moves of the cycle. If we are looping, the
# loop end needs to be put in.
if iterations > 1:
if program_or_profile != 'profile':
commands.append('LN')
else:
commands.append('PLN')
# Done constructing the command list.
return commands | python | def compile_sequence(cycles, program_or_profile='program',
unit_converter=None):
""" Makes the command list for a move sequence.
Constructs the list of commands to execute the given sequence of
motion. Program/command line commands or profile commands can be
generated depending on the value of `program_or_profile` so that the
commands can be used to construct a program or profile later. Types
of motion supported (see Notes for how to specify) are moves from
one position to another (the motion will always come to a stop
before doing the next motion), waiting a given interval of time till
starting the next move, and looping over a sequence of moves.
Parameters
----------
cycles : iterable of dicts
The iterable of cycles of motion to do one after another. See
Notes for format.
program_or_profile : {'program', 'profile'}, optional
Whether program or profile motion commands should be used.
Anything other than these two values implies the default.
unit_converter : UnitConverter, optional
``GeminiMotorDrive.utilities.UnitConverter`` to use to convert
the units in `cycles` to motor units. ``None`` indicates that
they are already in motor units.
Returns
-------
commands : list of str
``list`` of ``str`` commands making up the move sequence.
Notes
-----
`cycles` is an iterable of individual cycles of motion. Each cycle
is a ``dict`` that represents a sequence of moves that could
possibly be looped over. The field ``'iterations'`` gives how many
times the sequence of moves should be done (a value > 1 implies a
loop). Then the field ``'moves'`` is an iterable of the individual
moves. Each individual move is a ``dict`` with the acceleration
(``'A'``), deceleration (``'AD'`` with 0 meaning the value of the
acceleration is used), velocity (``'V'``), and the distance/position
(``'D'``). Back in the cycle, the field ``'wait_times'`` is an
iterable of numbers giving the time in seconds to wait after each
move before going onto the next.
See Also
--------
get_sequence_time
convert_sequence_to_motor_units
GeminiMotorDrive.utilities.UnitConverter
Examples
--------
Simple program style two motions with a pause in between.
>>> from GeminiMotorDrive.compilers.move_sequence import *
>>> cycles = [{'iterations':1, 'wait_times':[1, 0],
... 'moves':[{'A':100, 'AD':0, 'D':-1000, 'V':100},
... {'A':90, 'AD':0, 'D':-1000, 'V':100}]}]
>>> compile_sequence(cycles)
['A100',
'AD0',
'V100',
'D-1000',
'GO1',
'WAIT(AS.1=b0)',
'T1',
'A90',
'GO1',
'WAIT(AS.1=b0)']
The same motion but in profile style commands
>>> from GeminiMotorDrive.compilers.move_sequence import *
>>> cycles = [{'iterations':1, 'wait_times':[1, 0],
... 'moves':[{'A':100, 'AD':0, 'D':-1000, 'V':100},
... {'A':90, 'AD':0, 'D':-1000, 'V':100}]}]
>>> compile_sequence(cycles, program_or_profile='profile')
['A100',
'AD100',
'V100',
'D-1000',
'VF0',
'GOBUF1',
'GOWHEN(T=1000)',
'A90',
'AD90',
'VF0',
'GOBUF1']
Another motion with a back and forth loop (100 iterations) in the
middle, done in program style commands.
>>> from GeminiMotorDrive.compilers.move_sequence import *
>>> cycles = [{'iterations':1, 'wait_times':[1],
... 'moves':[{'A':100, 'AD':0, 'D':-1000, 'V':100}]},
... {'iterations':100, 'wait_times':[0, 0],
... 'moves':[{'A':50, 'AD':40, 'D':-1000, 'V':30},
... {'A':50, 'AD':40, 'D':1000, 'V':30}]},
... {'iterations':1, 'wait_times':[0],
... 'moves':[{'A':100, 'AD':0, 'D':1000, 'V':100}]}]
>>> compile_sequence(cycles)
['A100',
'AD0',
'V100',
'D-1000',
'GO1',
'WAIT(AS.1=b0)',
'T1',
'L100',
'A50',
'AD40',
'V30',
'D-1000',
'GO1',
'WAIT(AS.1=b0)',
'D~',
'GO1',
'WAIT(AS.1=b0)',
'LN',
'A100',
'AD0',
'V100',
'GO1',
'WAIT(AS.1=b0)']
"""
# If needed, cycles needs to be converted to motor units.
if unit_converter is None:
cv_cycles = cycles
else:
cv_cycles = convert_sequence_to_motor_units(cycles, \
unit_converter=unit_converter)
# Initially, we have no commands in our command list.
commands = []
# The A, AD, D, and V parameters of the previous motion should be
# kept track of because if they don't change from one motion to the
# next, the commands to set them don't need to be included. They
# will be started blank since there are no previous motions yet.
previous_motion = {'A': [], 'AD': [], 'D': [], 'V': []}
# Construct each cycle one by one.
for cycle in cv_cycles:
# If more than one iteration is being done, a loop needs to be
# setup. It will be either 'L' or 'PLOOP' with the number of
# iterations attached if it is a program or a profile
# respectively. Since it will be tough to keep track of what
# motion changed from the end of a loop to the beginning of it,
# it is easier to just forget all previous motion values and set
# them all at the beginning of the loop (clear previous_motion).
iterations = int(cycle['iterations'])
if iterations > 1:
previous_motion = {'A': [], 'AD': [], 'D': [], 'V': []}
if program_or_profile != 'profile':
commands.append('L' + str(iterations))
else:
commands.append('PLOOP' + str(iterations))
# Construct each individual move in the cycle.
for i in range(0, len(cycle['moves'])):
# Grab the motion indicated by the current move.
new_motion = cycle['moves'][i]
# If we are doing a profile, AD must be set explicitly
# to A if it is 0.
if program_or_profile == 'profile' \
and new_motion['AD'] == 0.0:
new_motion['AD'] = new_motion['A']
# Set A, AD, and V if they have changed.
for k in ('A', 'AD', 'V'):
if previous_motion[k] != new_motion[k]:
# Grab it and round it to 4 places after the decimal
# point because that is the most that is
# supported. Then, if it is an integer value,
# convert it to an integer because that is what the
# drive will send back if requested (makes
# comparisons easier). Then add the command.
val = round(float(new_motion[k]), 4)
if val == int(val):
val = int(val)
commands.append(k + str(val))
# If the sign of D has flipped, we just need to issue a 'D~'
# command. If the value has changed in another way, it needs
# to be reset.
if previous_motion['D'] != new_motion['D']:
if previous_motion['D'] == -new_motion['D']:
commands.append('D~')
else:
commands.append('D'
+ str(int(new_motion['D'])))
# Grab the amount of time that should be waited after the
# move is done.
wait_time = cycle['wait_times'][i]
# Give the motion command (GO or GOBUF), tell the drive to
# wait till the motor has stopped (a WAIT command if it is a
# program and a VF0 command if it is a profile), and make it
# wait the period of time wait_time (T and GOWHEN commands).
if program_or_profile != 'profile':
commands.append('GO1')
commands.append('WAIT(AS.1=b0)')
if wait_time != 0:
# The wait time needs to be rounded to 3 places
# after the decimal. If it is an integer, it should
# be converted to an int so that the drive will send
# back what we send (makes compairisons easier).
wait_time = round(float(wait_time), 3)
if wait_time == int(wait_time):
wait_time = int(wait_time)
commands.append('T' + str(wait_time))
else:
commands.append('VF0')
commands.append('GOBUF1')
if wait_time != 0:
commands.append('GOWHEN(T='
+ str(int(1000*wait_time))
+ ')')
# Before going onto the next move, previous_motion needs to
# be set to the one just done.
previous_motion = new_motion
# Done with all the moves of the cycle. If we are looping, the
# loop end needs to be put in.
if iterations > 1:
if program_or_profile != 'profile':
commands.append('LN')
else:
commands.append('PLN')
# Done constructing the command list.
return commands | [
"def",
"compile_sequence",
"(",
"cycles",
",",
"program_or_profile",
"=",
"'program'",
",",
"unit_converter",
"=",
"None",
")",
":",
"# If needed, cycles needs to be converted to motor units.",
"if",
"unit_converter",
"is",
"None",
":",
"cv_cycles",
"=",
"cycles",
"else",
":",
"cv_cycles",
"=",
"convert_sequence_to_motor_units",
"(",
"cycles",
",",
"unit_converter",
"=",
"unit_converter",
")",
"# Initially, we have no commands in our command list.",
"commands",
"=",
"[",
"]",
"# The A, AD, D, and V parameters of the previous motion should be",
"# kept track of because if they don't change from one motion to the",
"# next, the commands to set them don't need to be included. They",
"# will be started blank since there are no previous motions yet.",
"previous_motion",
"=",
"{",
"'A'",
":",
"[",
"]",
",",
"'AD'",
":",
"[",
"]",
",",
"'D'",
":",
"[",
"]",
",",
"'V'",
":",
"[",
"]",
"}",
"# Construct each cycle one by one.",
"for",
"cycle",
"in",
"cv_cycles",
":",
"# If more than one iteration is being done, a loop needs to be",
"# setup. It will be either 'L' or 'PLOOP' with the number of",
"# iterations attached if it is a program or a profile",
"# respectively. Since it will be tough to keep track of what",
"# motion changed from the end of a loop to the beginning of it,",
"# it is easier to just forget all previous motion values and set",
"# them all at the beginning of the loop (clear previous_motion).",
"iterations",
"=",
"int",
"(",
"cycle",
"[",
"'iterations'",
"]",
")",
"if",
"iterations",
">",
"1",
":",
"previous_motion",
"=",
"{",
"'A'",
":",
"[",
"]",
",",
"'AD'",
":",
"[",
"]",
",",
"'D'",
":",
"[",
"]",
",",
"'V'",
":",
"[",
"]",
"}",
"if",
"program_or_profile",
"!=",
"'profile'",
":",
"commands",
".",
"append",
"(",
"'L'",
"+",
"str",
"(",
"iterations",
")",
")",
"else",
":",
"commands",
".",
"append",
"(",
"'PLOOP'",
"+",
"str",
"(",
"iterations",
")",
")",
"# Construct each individual move in the cycle.",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"cycle",
"[",
"'moves'",
"]",
")",
")",
":",
"# Grab the motion indicated by the current move.",
"new_motion",
"=",
"cycle",
"[",
"'moves'",
"]",
"[",
"i",
"]",
"# If we are doing a profile, AD must be set explicitly",
"# to A if it is 0.",
"if",
"program_or_profile",
"==",
"'profile'",
"and",
"new_motion",
"[",
"'AD'",
"]",
"==",
"0.0",
":",
"new_motion",
"[",
"'AD'",
"]",
"=",
"new_motion",
"[",
"'A'",
"]",
"# Set A, AD, and V if they have changed.",
"for",
"k",
"in",
"(",
"'A'",
",",
"'AD'",
",",
"'V'",
")",
":",
"if",
"previous_motion",
"[",
"k",
"]",
"!=",
"new_motion",
"[",
"k",
"]",
":",
"# Grab it and round it to 4 places after the decimal",
"# point because that is the most that is",
"# supported. Then, if it is an integer value,",
"# convert it to an integer because that is what the",
"# drive will send back if requested (makes",
"# comparisons easier). Then add the command.",
"val",
"=",
"round",
"(",
"float",
"(",
"new_motion",
"[",
"k",
"]",
")",
",",
"4",
")",
"if",
"val",
"==",
"int",
"(",
"val",
")",
":",
"val",
"=",
"int",
"(",
"val",
")",
"commands",
".",
"append",
"(",
"k",
"+",
"str",
"(",
"val",
")",
")",
"# If the sign of D has flipped, we just need to issue a 'D~'",
"# command. If the value has changed in another way, it needs",
"# to be reset.",
"if",
"previous_motion",
"[",
"'D'",
"]",
"!=",
"new_motion",
"[",
"'D'",
"]",
":",
"if",
"previous_motion",
"[",
"'D'",
"]",
"==",
"-",
"new_motion",
"[",
"'D'",
"]",
":",
"commands",
".",
"append",
"(",
"'D~'",
")",
"else",
":",
"commands",
".",
"append",
"(",
"'D'",
"+",
"str",
"(",
"int",
"(",
"new_motion",
"[",
"'D'",
"]",
")",
")",
")",
"# Grab the amount of time that should be waited after the",
"# move is done.",
"wait_time",
"=",
"cycle",
"[",
"'wait_times'",
"]",
"[",
"i",
"]",
"# Give the motion command (GO or GOBUF), tell the drive to",
"# wait till the motor has stopped (a WAIT command if it is a",
"# program and a VF0 command if it is a profile), and make it",
"# wait the period of time wait_time (T and GOWHEN commands).",
"if",
"program_or_profile",
"!=",
"'profile'",
":",
"commands",
".",
"append",
"(",
"'GO1'",
")",
"commands",
".",
"append",
"(",
"'WAIT(AS.1=b0)'",
")",
"if",
"wait_time",
"!=",
"0",
":",
"# The wait time needs to be rounded to 3 places",
"# after the decimal. If it is an integer, it should",
"# be converted to an int so that the drive will send",
"# back what we send (makes compairisons easier).",
"wait_time",
"=",
"round",
"(",
"float",
"(",
"wait_time",
")",
",",
"3",
")",
"if",
"wait_time",
"==",
"int",
"(",
"wait_time",
")",
":",
"wait_time",
"=",
"int",
"(",
"wait_time",
")",
"commands",
".",
"append",
"(",
"'T'",
"+",
"str",
"(",
"wait_time",
")",
")",
"else",
":",
"commands",
".",
"append",
"(",
"'VF0'",
")",
"commands",
".",
"append",
"(",
"'GOBUF1'",
")",
"if",
"wait_time",
"!=",
"0",
":",
"commands",
".",
"append",
"(",
"'GOWHEN(T='",
"+",
"str",
"(",
"int",
"(",
"1000",
"*",
"wait_time",
")",
")",
"+",
"')'",
")",
"# Before going onto the next move, previous_motion needs to",
"# be set to the one just done.",
"previous_motion",
"=",
"new_motion",
"# Done with all the moves of the cycle. If we are looping, the",
"# loop end needs to be put in.",
"if",
"iterations",
">",
"1",
":",
"if",
"program_or_profile",
"!=",
"'profile'",
":",
"commands",
".",
"append",
"(",
"'LN'",
")",
"else",
":",
"commands",
".",
"append",
"(",
"'PLN'",
")",
"# Done constructing the command list.",
"return",
"commands"
] | Makes the command list for a move sequence.
Constructs the list of commands to execute the given sequence of
motion. Program/command line commands or profile commands can be
generated depending on the value of `program_or_profile` so that the
commands can be used to construct a program or profile later. Types
of motion supported (see Notes for how to specify) are moves from
one position to another (the motion will always come to a stop
before doing the next motion), waiting a given interval of time till
starting the next move, and looping over a sequence of moves.
Parameters
----------
cycles : iterable of dicts
The iterable of cycles of motion to do one after another. See
Notes for format.
program_or_profile : {'program', 'profile'}, optional
Whether program or profile motion commands should be used.
Anything other than these two values implies the default.
unit_converter : UnitConverter, optional
``GeminiMotorDrive.utilities.UnitConverter`` to use to convert
the units in `cycles` to motor units. ``None`` indicates that
they are already in motor units.
Returns
-------
commands : list of str
``list`` of ``str`` commands making up the move sequence.
Notes
-----
`cycles` is an iterable of individual cycles of motion. Each cycle
is a ``dict`` that represents a sequence of moves that could
possibly be looped over. The field ``'iterations'`` gives how many
times the sequence of moves should be done (a value > 1 implies a
loop). Then the field ``'moves'`` is an iterable of the individual
moves. Each individual move is a ``dict`` with the acceleration
(``'A'``), deceleration (``'AD'`` with 0 meaning the value of the
acceleration is used), velocity (``'V'``), and the distance/position
(``'D'``). Back in the cycle, the field ``'wait_times'`` is an
iterable of numbers giving the time in seconds to wait after each
move before going onto the next.
See Also
--------
get_sequence_time
convert_sequence_to_motor_units
GeminiMotorDrive.utilities.UnitConverter
Examples
--------
Simple program style two motions with a pause in between.
>>> from GeminiMotorDrive.compilers.move_sequence import *
>>> cycles = [{'iterations':1, 'wait_times':[1, 0],
... 'moves':[{'A':100, 'AD':0, 'D':-1000, 'V':100},
... {'A':90, 'AD':0, 'D':-1000, 'V':100}]}]
>>> compile_sequence(cycles)
['A100',
'AD0',
'V100',
'D-1000',
'GO1',
'WAIT(AS.1=b0)',
'T1',
'A90',
'GO1',
'WAIT(AS.1=b0)']
The same motion but in profile style commands
>>> from GeminiMotorDrive.compilers.move_sequence import *
>>> cycles = [{'iterations':1, 'wait_times':[1, 0],
... 'moves':[{'A':100, 'AD':0, 'D':-1000, 'V':100},
... {'A':90, 'AD':0, 'D':-1000, 'V':100}]}]
>>> compile_sequence(cycles, program_or_profile='profile')
['A100',
'AD100',
'V100',
'D-1000',
'VF0',
'GOBUF1',
'GOWHEN(T=1000)',
'A90',
'AD90',
'VF0',
'GOBUF1']
Another motion with a back and forth loop (100 iterations) in the
middle, done in program style commands.
>>> from GeminiMotorDrive.compilers.move_sequence import *
>>> cycles = [{'iterations':1, 'wait_times':[1],
... 'moves':[{'A':100, 'AD':0, 'D':-1000, 'V':100}]},
... {'iterations':100, 'wait_times':[0, 0],
... 'moves':[{'A':50, 'AD':40, 'D':-1000, 'V':30},
... {'A':50, 'AD':40, 'D':1000, 'V':30}]},
... {'iterations':1, 'wait_times':[0],
... 'moves':[{'A':100, 'AD':0, 'D':1000, 'V':100}]}]
>>> compile_sequence(cycles)
['A100',
'AD0',
'V100',
'D-1000',
'GO1',
'WAIT(AS.1=b0)',
'T1',
'L100',
'A50',
'AD40',
'V30',
'D-1000',
'GO1',
'WAIT(AS.1=b0)',
'D~',
'GO1',
'WAIT(AS.1=b0)',
'LN',
'A100',
'AD0',
'V100',
'GO1',
'WAIT(AS.1=b0)'] | [
"Makes",
"the",
"command",
"list",
"for",
"a",
"move",
"sequence",
"."
] | 8de347ffb91228fbfe3832098b4996fa0141d8f1 | https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/compilers/move_sequence.py#L28-L265 |
246,703 | frejanordsiek/GeminiMotorDrive | GeminiMotorDrive/compilers/move_sequence.py | get_sequence_time | def get_sequence_time(cycles, unit_converter=None, eres=None):
""" Calculates the time the move sequence will take to complete.
Calculates the amount of time it will take to complete the given
move sequence. Types of motion supported are moves from one position
to another (the motion will always come to a stop before doing the
next motion), waiting a given interval of time till starting the
next move, and looping over a sequence of moves.
Parameters
----------
cycles : list of dicts
The ``list`` of cycles of motion to do one after another. See
``compile_sequence`` for format.
unit_converter : UnitConverter, optional
``GeminiMotorDrive.utilities.UnitConverter`` to use to convert
the units in `cycles` to motor units. ``None`` indicates that
they are already in motor units.
eres : int
Encoder resolution. Only relevant if `unit_converter` is
``None``.
Returns
-------
time : float
Time the move sequence will take in seconds.
See Also
--------
compile_sequence
GeminiMotorDrive.utilities.UnitConverter
move_time
"""
# If we are doing unit conversion, then that is equivalent to motor
# units but with eres equal to one.
if unit_converter is not None:
eres = 1
# Starting with 0 time, steadily add the time of each movement.
tme = 0.0
# Go through each cycle and collect times.
for cycle in cycles:
# Add all the wait times.
tme += cycle['iterations']*sum(cycle['wait_times'])
# Add the time for each individual move.
for move in cycle['moves']:
tme += cycle['iterations'] \
* move_time(move, eres=eres)
# Done.
return tme | python | def get_sequence_time(cycles, unit_converter=None, eres=None):
""" Calculates the time the move sequence will take to complete.
Calculates the amount of time it will take to complete the given
move sequence. Types of motion supported are moves from one position
to another (the motion will always come to a stop before doing the
next motion), waiting a given interval of time till starting the
next move, and looping over a sequence of moves.
Parameters
----------
cycles : list of dicts
The ``list`` of cycles of motion to do one after another. See
``compile_sequence`` for format.
unit_converter : UnitConverter, optional
``GeminiMotorDrive.utilities.UnitConverter`` to use to convert
the units in `cycles` to motor units. ``None`` indicates that
they are already in motor units.
eres : int
Encoder resolution. Only relevant if `unit_converter` is
``None``.
Returns
-------
time : float
Time the move sequence will take in seconds.
See Also
--------
compile_sequence
GeminiMotorDrive.utilities.UnitConverter
move_time
"""
# If we are doing unit conversion, then that is equivalent to motor
# units but with eres equal to one.
if unit_converter is not None:
eres = 1
# Starting with 0 time, steadily add the time of each movement.
tme = 0.0
# Go through each cycle and collect times.
for cycle in cycles:
# Add all the wait times.
tme += cycle['iterations']*sum(cycle['wait_times'])
# Add the time for each individual move.
for move in cycle['moves']:
tme += cycle['iterations'] \
* move_time(move, eres=eres)
# Done.
return tme | [
"def",
"get_sequence_time",
"(",
"cycles",
",",
"unit_converter",
"=",
"None",
",",
"eres",
"=",
"None",
")",
":",
"# If we are doing unit conversion, then that is equivalent to motor",
"# units but with eres equal to one.",
"if",
"unit_converter",
"is",
"not",
"None",
":",
"eres",
"=",
"1",
"# Starting with 0 time, steadily add the time of each movement.",
"tme",
"=",
"0.0",
"# Go through each cycle and collect times.",
"for",
"cycle",
"in",
"cycles",
":",
"# Add all the wait times.",
"tme",
"+=",
"cycle",
"[",
"'iterations'",
"]",
"*",
"sum",
"(",
"cycle",
"[",
"'wait_times'",
"]",
")",
"# Add the time for each individual move.",
"for",
"move",
"in",
"cycle",
"[",
"'moves'",
"]",
":",
"tme",
"+=",
"cycle",
"[",
"'iterations'",
"]",
"*",
"move_time",
"(",
"move",
",",
"eres",
"=",
"eres",
")",
"# Done.",
"return",
"tme"
] | Calculates the time the move sequence will take to complete.
Calculates the amount of time it will take to complete the given
move sequence. Types of motion supported are moves from one position
to another (the motion will always come to a stop before doing the
next motion), waiting a given interval of time till starting the
next move, and looping over a sequence of moves.
Parameters
----------
cycles : list of dicts
The ``list`` of cycles of motion to do one after another. See
``compile_sequence`` for format.
unit_converter : UnitConverter, optional
``GeminiMotorDrive.utilities.UnitConverter`` to use to convert
the units in `cycles` to motor units. ``None`` indicates that
they are already in motor units.
eres : int
Encoder resolution. Only relevant if `unit_converter` is
``None``.
Returns
-------
time : float
Time the move sequence will take in seconds.
See Also
--------
compile_sequence
GeminiMotorDrive.utilities.UnitConverter
move_time | [
"Calculates",
"the",
"time",
"the",
"move",
"sequence",
"will",
"take",
"to",
"complete",
"."
] | 8de347ffb91228fbfe3832098b4996fa0141d8f1 | https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/compilers/move_sequence.py#L268-L318 |
246,704 | frejanordsiek/GeminiMotorDrive | GeminiMotorDrive/compilers/move_sequence.py | move_time | def move_time(move, eres):
""" Calculates the time it takes to do a move.
Calculates how long it will take to complete a move of the motor. It
is assumed that the motor will decerate to a stop for the end of the
move as opposed to keep moving at velocity.
Everything is in motor units which are encoder counts for distance,
pitches/s for velocity, and pitches/s^2 for acceleration.
Parameters
----------
move : dict
Contains the move parameters in its fields: acceleration ('A'),
deceleration ('AD' with 0 meaning the value of the acceleration
is used), velocity ('V'), and the distance/position ('D').
eres : int
Encoder resolution.
Returns
-------
time : float
Time the move will take in seconds.
See Also
--------
compile_sequence
get_sequence_time
"""
# Grab the move parameters. If the deceleration is given as zero,
# that means it has the same value as the acceleration. Distance is
# converted to the same units as the others by dividing by the
# encoder resolution. The absolute value of everything is taken for
# simplicity.
A = abs(move['A'])
AD = abs(move['AD'])
if AD == 0.0:
AD = A
V = abs(move['V'])
D = abs(move['D'])/eres
# Calculate the times it would take to accelerate from stop to V and
# decelerate to stop at rates A and AD respectively.
accel_times = [V/A, V/AD]
# Calculate the distances that would be moved in those times.
dists = [0.5*A*(accel_times[0]**2), 0.5*AD*(accel_times[1]**2)]
# If the sum of those dists is greater than D, then the velocity V
# is never reached. The way the time is calculated depends on which
# case it is.
if sum(dists) <= D:
# The time is just the sum of the acceleration times plus the
# remaining distance divided by V.
return (sum(accel_times) + (D-sum(dists))/V)
else:
# We need to find the time it takes for the acceleration path
# and deceleration path to meet and have the same speeds.
#
# (1) t = t_1 + t_2
# (2) A*t_1 = AD*t_2
# (3) D = 0.5*A*(t_1**2) + 0.5*AD*(t_2**2)
#
# Re-writing t_2 in terms of t_1 using (2)
# (4) t_2 = (A / AD) * t_1
#
# Putting that into (1) and (3)
# (4) t = (1 + (A / AD)) * t_1
# (5) D = 0.5*A*(1 + (A / AD)) * (t_1**2)
#
# Solving (5) for t_1,
# (6) t_1 = sqrt( 2*D / (A * (1 + (A / AD))))
#
# Putting that into (4),
# t = sqrt(2*D*(1 + (A / AD)) / A)
return math.sqrt(2*D * (1 + (A / AD)) / A) | python | def move_time(move, eres):
""" Calculates the time it takes to do a move.
Calculates how long it will take to complete a move of the motor. It
is assumed that the motor will decerate to a stop for the end of the
move as opposed to keep moving at velocity.
Everything is in motor units which are encoder counts for distance,
pitches/s for velocity, and pitches/s^2 for acceleration.
Parameters
----------
move : dict
Contains the move parameters in its fields: acceleration ('A'),
deceleration ('AD' with 0 meaning the value of the acceleration
is used), velocity ('V'), and the distance/position ('D').
eres : int
Encoder resolution.
Returns
-------
time : float
Time the move will take in seconds.
See Also
--------
compile_sequence
get_sequence_time
"""
# Grab the move parameters. If the deceleration is given as zero,
# that means it has the same value as the acceleration. Distance is
# converted to the same units as the others by dividing by the
# encoder resolution. The absolute value of everything is taken for
# simplicity.
A = abs(move['A'])
AD = abs(move['AD'])
if AD == 0.0:
AD = A
V = abs(move['V'])
D = abs(move['D'])/eres
# Calculate the times it would take to accelerate from stop to V and
# decelerate to stop at rates A and AD respectively.
accel_times = [V/A, V/AD]
# Calculate the distances that would be moved in those times.
dists = [0.5*A*(accel_times[0]**2), 0.5*AD*(accel_times[1]**2)]
# If the sum of those dists is greater than D, then the velocity V
# is never reached. The way the time is calculated depends on which
# case it is.
if sum(dists) <= D:
# The time is just the sum of the acceleration times plus the
# remaining distance divided by V.
return (sum(accel_times) + (D-sum(dists))/V)
else:
# We need to find the time it takes for the acceleration path
# and deceleration path to meet and have the same speeds.
#
# (1) t = t_1 + t_2
# (2) A*t_1 = AD*t_2
# (3) D = 0.5*A*(t_1**2) + 0.5*AD*(t_2**2)
#
# Re-writing t_2 in terms of t_1 using (2)
# (4) t_2 = (A / AD) * t_1
#
# Putting that into (1) and (3)
# (4) t = (1 + (A / AD)) * t_1
# (5) D = 0.5*A*(1 + (A / AD)) * (t_1**2)
#
# Solving (5) for t_1,
# (6) t_1 = sqrt( 2*D / (A * (1 + (A / AD))))
#
# Putting that into (4),
# t = sqrt(2*D*(1 + (A / AD)) / A)
return math.sqrt(2*D * (1 + (A / AD)) / A) | [
"def",
"move_time",
"(",
"move",
",",
"eres",
")",
":",
"# Grab the move parameters. If the deceleration is given as zero,",
"# that means it has the same value as the acceleration. Distance is",
"# converted to the same units as the others by dividing by the",
"# encoder resolution. The absolute value of everything is taken for",
"# simplicity.",
"A",
"=",
"abs",
"(",
"move",
"[",
"'A'",
"]",
")",
"AD",
"=",
"abs",
"(",
"move",
"[",
"'AD'",
"]",
")",
"if",
"AD",
"==",
"0.0",
":",
"AD",
"=",
"A",
"V",
"=",
"abs",
"(",
"move",
"[",
"'V'",
"]",
")",
"D",
"=",
"abs",
"(",
"move",
"[",
"'D'",
"]",
")",
"/",
"eres",
"# Calculate the times it would take to accelerate from stop to V and",
"# decelerate to stop at rates A and AD respectively.",
"accel_times",
"=",
"[",
"V",
"/",
"A",
",",
"V",
"/",
"AD",
"]",
"# Calculate the distances that would be moved in those times.",
"dists",
"=",
"[",
"0.5",
"*",
"A",
"*",
"(",
"accel_times",
"[",
"0",
"]",
"**",
"2",
")",
",",
"0.5",
"*",
"AD",
"*",
"(",
"accel_times",
"[",
"1",
"]",
"**",
"2",
")",
"]",
"# If the sum of those dists is greater than D, then the velocity V",
"# is never reached. The way the time is calculated depends on which",
"# case it is.",
"if",
"sum",
"(",
"dists",
")",
"<=",
"D",
":",
"# The time is just the sum of the acceleration times plus the",
"# remaining distance divided by V.",
"return",
"(",
"sum",
"(",
"accel_times",
")",
"+",
"(",
"D",
"-",
"sum",
"(",
"dists",
")",
")",
"/",
"V",
")",
"else",
":",
"# We need to find the time it takes for the acceleration path",
"# and deceleration path to meet and have the same speeds.",
"#",
"# (1) t = t_1 + t_2",
"# (2) A*t_1 = AD*t_2",
"# (3) D = 0.5*A*(t_1**2) + 0.5*AD*(t_2**2)",
"#",
"# Re-writing t_2 in terms of t_1 using (2)",
"# (4) t_2 = (A / AD) * t_1",
"#",
"# Putting that into (1) and (3)",
"# (4) t = (1 + (A / AD)) * t_1",
"# (5) D = 0.5*A*(1 + (A / AD)) * (t_1**2)",
"#",
"# Solving (5) for t_1,",
"# (6) t_1 = sqrt( 2*D / (A * (1 + (A / AD))))",
"#",
"# Putting that into (4),",
"# t = sqrt(2*D*(1 + (A / AD)) / A)",
"return",
"math",
".",
"sqrt",
"(",
"2",
"*",
"D",
"*",
"(",
"1",
"+",
"(",
"A",
"/",
"AD",
")",
")",
"/",
"A",
")"
] | Calculates the time it takes to do a move.
Calculates how long it will take to complete a move of the motor. It
is assumed that the motor will decerate to a stop for the end of the
move as opposed to keep moving at velocity.
Everything is in motor units which are encoder counts for distance,
pitches/s for velocity, and pitches/s^2 for acceleration.
Parameters
----------
move : dict
Contains the move parameters in its fields: acceleration ('A'),
deceleration ('AD' with 0 meaning the value of the acceleration
is used), velocity ('V'), and the distance/position ('D').
eres : int
Encoder resolution.
Returns
-------
time : float
Time the move will take in seconds.
See Also
--------
compile_sequence
get_sequence_time | [
"Calculates",
"the",
"time",
"it",
"takes",
"to",
"do",
"a",
"move",
"."
] | 8de347ffb91228fbfe3832098b4996fa0141d8f1 | https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/compilers/move_sequence.py#L321-L397 |
246,705 | frejanordsiek/GeminiMotorDrive | GeminiMotorDrive/compilers/move_sequence.py | convert_sequence_to_motor_units | def convert_sequence_to_motor_units(cycles, unit_converter):
""" Converts a move sequence to motor units.
Converts a move sequence to motor units using the provied converter.
Parameters
----------
cycles : iterable of dicts
The iterable of cycles of motion to do one after another. See
``compile_sequence`` for format.
unit_converter : UnitConverter, optional
``GeminiMotorDrive.utilities.UnitConverter`` to use to convert
the units in `cycles` to motor units.
Returns
-------
motor_cycles : list of dicts
A deep copy of `cycles` with all units converted to motor units.
See Also
--------
compile_sequence
GeminiMotorDrive.utilities.UnitConverter
"""
# Make a deep copy of cycles so that the conversions don't damage
# the original one.
cv_cycles = copy.deepcopy(cycles)
# Go through each cycle and do the conversions.
for cycle in cv_cycles:
# Go through each of the moves and do the conversions.
for move in cycle['moves']:
move['A'] = unit_converter.to_motor_velocity_acceleration( \
move['A'])
move['AD'] = \
unit_converter.to_motor_velocity_acceleration( \
move['AD'])
move['V'] = unit_converter.to_motor_velocity_acceleration( \
move['V'])
move['D'] = int(unit_converter.to_motor_distance(move['D']))
# Now return the converted move sequence.
return cv_cycles | python | def convert_sequence_to_motor_units(cycles, unit_converter):
""" Converts a move sequence to motor units.
Converts a move sequence to motor units using the provied converter.
Parameters
----------
cycles : iterable of dicts
The iterable of cycles of motion to do one after another. See
``compile_sequence`` for format.
unit_converter : UnitConverter, optional
``GeminiMotorDrive.utilities.UnitConverter`` to use to convert
the units in `cycles` to motor units.
Returns
-------
motor_cycles : list of dicts
A deep copy of `cycles` with all units converted to motor units.
See Also
--------
compile_sequence
GeminiMotorDrive.utilities.UnitConverter
"""
# Make a deep copy of cycles so that the conversions don't damage
# the original one.
cv_cycles = copy.deepcopy(cycles)
# Go through each cycle and do the conversions.
for cycle in cv_cycles:
# Go through each of the moves and do the conversions.
for move in cycle['moves']:
move['A'] = unit_converter.to_motor_velocity_acceleration( \
move['A'])
move['AD'] = \
unit_converter.to_motor_velocity_acceleration( \
move['AD'])
move['V'] = unit_converter.to_motor_velocity_acceleration( \
move['V'])
move['D'] = int(unit_converter.to_motor_distance(move['D']))
# Now return the converted move sequence.
return cv_cycles | [
"def",
"convert_sequence_to_motor_units",
"(",
"cycles",
",",
"unit_converter",
")",
":",
"# Make a deep copy of cycles so that the conversions don't damage",
"# the original one.",
"cv_cycles",
"=",
"copy",
".",
"deepcopy",
"(",
"cycles",
")",
"# Go through each cycle and do the conversions.",
"for",
"cycle",
"in",
"cv_cycles",
":",
"# Go through each of the moves and do the conversions.",
"for",
"move",
"in",
"cycle",
"[",
"'moves'",
"]",
":",
"move",
"[",
"'A'",
"]",
"=",
"unit_converter",
".",
"to_motor_velocity_acceleration",
"(",
"move",
"[",
"'A'",
"]",
")",
"move",
"[",
"'AD'",
"]",
"=",
"unit_converter",
".",
"to_motor_velocity_acceleration",
"(",
"move",
"[",
"'AD'",
"]",
")",
"move",
"[",
"'V'",
"]",
"=",
"unit_converter",
".",
"to_motor_velocity_acceleration",
"(",
"move",
"[",
"'V'",
"]",
")",
"move",
"[",
"'D'",
"]",
"=",
"int",
"(",
"unit_converter",
".",
"to_motor_distance",
"(",
"move",
"[",
"'D'",
"]",
")",
")",
"# Now return the converted move sequence.",
"return",
"cv_cycles"
] | Converts a move sequence to motor units.
Converts a move sequence to motor units using the provied converter.
Parameters
----------
cycles : iterable of dicts
The iterable of cycles of motion to do one after another. See
``compile_sequence`` for format.
unit_converter : UnitConverter, optional
``GeminiMotorDrive.utilities.UnitConverter`` to use to convert
the units in `cycles` to motor units.
Returns
-------
motor_cycles : list of dicts
A deep copy of `cycles` with all units converted to motor units.
See Also
--------
compile_sequence
GeminiMotorDrive.utilities.UnitConverter | [
"Converts",
"a",
"move",
"sequence",
"to",
"motor",
"units",
"."
] | 8de347ffb91228fbfe3832098b4996fa0141d8f1 | https://github.com/frejanordsiek/GeminiMotorDrive/blob/8de347ffb91228fbfe3832098b4996fa0141d8f1/GeminiMotorDrive/compilers/move_sequence.py#L399-L442 |
246,706 | Sean1708/HipPy | hippy/compiler.py | Compiler.compile | def compile(self):
"""Return Hip string if already compiled else compile it."""
if self.buffer is None:
self.buffer = self._compile_value(self.data, 0)
return self.buffer.strip() | python | def compile(self):
"""Return Hip string if already compiled else compile it."""
if self.buffer is None:
self.buffer = self._compile_value(self.data, 0)
return self.buffer.strip() | [
"def",
"compile",
"(",
"self",
")",
":",
"if",
"self",
".",
"buffer",
"is",
"None",
":",
"self",
".",
"buffer",
"=",
"self",
".",
"_compile_value",
"(",
"self",
".",
"data",
",",
"0",
")",
"return",
"self",
".",
"buffer",
".",
"strip",
"(",
")"
] | Return Hip string if already compiled else compile it. | [
"Return",
"Hip",
"string",
"if",
"already",
"compiled",
"else",
"compile",
"it",
"."
] | d0ea8fb1e417f1fedaa8e215e3d420b90c4de691 | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/compiler.py#L15-L20 |
246,707 | Sean1708/HipPy | hippy/compiler.py | Compiler._compile_value | def _compile_value(self, data, indent_level):
"""Dispatch to correct compilation method."""
if isinstance(data, dict):
return self._compile_key_val(data, indent_level)
elif isinstance(data, list):
return self._compile_list(data, indent_level)
else:
return self._compile_literal(data) | python | def _compile_value(self, data, indent_level):
"""Dispatch to correct compilation method."""
if isinstance(data, dict):
return self._compile_key_val(data, indent_level)
elif isinstance(data, list):
return self._compile_list(data, indent_level)
else:
return self._compile_literal(data) | [
"def",
"_compile_value",
"(",
"self",
",",
"data",
",",
"indent_level",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"dict",
")",
":",
"return",
"self",
".",
"_compile_key_val",
"(",
"data",
",",
"indent_level",
")",
"elif",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"return",
"self",
".",
"_compile_list",
"(",
"data",
",",
"indent_level",
")",
"else",
":",
"return",
"self",
".",
"_compile_literal",
"(",
"data",
")"
] | Dispatch to correct compilation method. | [
"Dispatch",
"to",
"correct",
"compilation",
"method",
"."
] | d0ea8fb1e417f1fedaa8e215e3d420b90c4de691 | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/compiler.py#L22-L29 |
246,708 | Sean1708/HipPy | hippy/compiler.py | Compiler._compile_literal | def _compile_literal(self, data):
"""Write correct representation of literal."""
if data is None:
return 'nil'
elif data is True:
return 'yes'
elif data is False:
return 'no'
else:
return repr(data) | python | def _compile_literal(self, data):
"""Write correct representation of literal."""
if data is None:
return 'nil'
elif data is True:
return 'yes'
elif data is False:
return 'no'
else:
return repr(data) | [
"def",
"_compile_literal",
"(",
"self",
",",
"data",
")",
":",
"if",
"data",
"is",
"None",
":",
"return",
"'nil'",
"elif",
"data",
"is",
"True",
":",
"return",
"'yes'",
"elif",
"data",
"is",
"False",
":",
"return",
"'no'",
"else",
":",
"return",
"repr",
"(",
"data",
")"
] | Write correct representation of literal. | [
"Write",
"correct",
"representation",
"of",
"literal",
"."
] | d0ea8fb1e417f1fedaa8e215e3d420b90c4de691 | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/compiler.py#L31-L40 |
246,709 | Sean1708/HipPy | hippy/compiler.py | Compiler._compile_list | def _compile_list(self, data, indent_level):
"""Correctly write possibly nested list."""
if len(data) == 0:
return '--'
elif not any(isinstance(i, (dict, list)) for i in data):
return ', '.join(self._compile_literal(value) for value in data)
else:
# 'ere be dragons,
# granted there are fewer dragons than the parser,
# but dragons nonetheless
buffer = ''
i = 0
while i < len(data):
if isinstance(data[i], dict):
buffer += '\n'
buffer += self._indent * indent_level
while i < len(data) and isinstance(data[i], dict):
buffer += '-\n'
buffer += self._compile_key_val(data[i], indent_level)
buffer += self._indent * indent_level + '-'
i += 1
buffer += '\n'
elif (
isinstance(data[i], list) and
any(isinstance(item, (dict, list)) for item in data[i])
):
buffer += self._compile_list(data[i], indent_level+1)
elif isinstance(data[i], list):
buffer += '\n'
buffer += self._indent * indent_level
buffer += self._compile_list(data[i], indent_level+1)
else:
buffer += '\n'
buffer += self._indent * indent_level
buffer += self._compile_literal(data[i])
i += 1
return buffer | python | def _compile_list(self, data, indent_level):
"""Correctly write possibly nested list."""
if len(data) == 0:
return '--'
elif not any(isinstance(i, (dict, list)) for i in data):
return ', '.join(self._compile_literal(value) for value in data)
else:
# 'ere be dragons,
# granted there are fewer dragons than the parser,
# but dragons nonetheless
buffer = ''
i = 0
while i < len(data):
if isinstance(data[i], dict):
buffer += '\n'
buffer += self._indent * indent_level
while i < len(data) and isinstance(data[i], dict):
buffer += '-\n'
buffer += self._compile_key_val(data[i], indent_level)
buffer += self._indent * indent_level + '-'
i += 1
buffer += '\n'
elif (
isinstance(data[i], list) and
any(isinstance(item, (dict, list)) for item in data[i])
):
buffer += self._compile_list(data[i], indent_level+1)
elif isinstance(data[i], list):
buffer += '\n'
buffer += self._indent * indent_level
buffer += self._compile_list(data[i], indent_level+1)
else:
buffer += '\n'
buffer += self._indent * indent_level
buffer += self._compile_literal(data[i])
i += 1
return buffer | [
"def",
"_compile_list",
"(",
"self",
",",
"data",
",",
"indent_level",
")",
":",
"if",
"len",
"(",
"data",
")",
"==",
"0",
":",
"return",
"'--'",
"elif",
"not",
"any",
"(",
"isinstance",
"(",
"i",
",",
"(",
"dict",
",",
"list",
")",
")",
"for",
"i",
"in",
"data",
")",
":",
"return",
"', '",
".",
"join",
"(",
"self",
".",
"_compile_literal",
"(",
"value",
")",
"for",
"value",
"in",
"data",
")",
"else",
":",
"# 'ere be dragons,",
"# granted there are fewer dragons than the parser,",
"# but dragons nonetheless",
"buffer",
"=",
"''",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
"[",
"i",
"]",
",",
"dict",
")",
":",
"buffer",
"+=",
"'\\n'",
"buffer",
"+=",
"self",
".",
"_indent",
"*",
"indent_level",
"while",
"i",
"<",
"len",
"(",
"data",
")",
"and",
"isinstance",
"(",
"data",
"[",
"i",
"]",
",",
"dict",
")",
":",
"buffer",
"+=",
"'-\\n'",
"buffer",
"+=",
"self",
".",
"_compile_key_val",
"(",
"data",
"[",
"i",
"]",
",",
"indent_level",
")",
"buffer",
"+=",
"self",
".",
"_indent",
"*",
"indent_level",
"+",
"'-'",
"i",
"+=",
"1",
"buffer",
"+=",
"'\\n'",
"elif",
"(",
"isinstance",
"(",
"data",
"[",
"i",
"]",
",",
"list",
")",
"and",
"any",
"(",
"isinstance",
"(",
"item",
",",
"(",
"dict",
",",
"list",
")",
")",
"for",
"item",
"in",
"data",
"[",
"i",
"]",
")",
")",
":",
"buffer",
"+=",
"self",
".",
"_compile_list",
"(",
"data",
"[",
"i",
"]",
",",
"indent_level",
"+",
"1",
")",
"elif",
"isinstance",
"(",
"data",
"[",
"i",
"]",
",",
"list",
")",
":",
"buffer",
"+=",
"'\\n'",
"buffer",
"+=",
"self",
".",
"_indent",
"*",
"indent_level",
"buffer",
"+=",
"self",
".",
"_compile_list",
"(",
"data",
"[",
"i",
"]",
",",
"indent_level",
"+",
"1",
")",
"else",
":",
"buffer",
"+=",
"'\\n'",
"buffer",
"+=",
"self",
".",
"_indent",
"*",
"indent_level",
"buffer",
"+=",
"self",
".",
"_compile_literal",
"(",
"data",
"[",
"i",
"]",
")",
"i",
"+=",
"1",
"return",
"buffer"
] | Correctly write possibly nested list. | [
"Correctly",
"write",
"possibly",
"nested",
"list",
"."
] | d0ea8fb1e417f1fedaa8e215e3d420b90c4de691 | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/compiler.py#L42-L80 |
246,710 | Sean1708/HipPy | hippy/compiler.py | Compiler._compile_key_val | def _compile_key_val(self, data, indent_level):
"""Compile a dictionary."""
buffer = ''
for (key, val) in data.items():
buffer += self._indent * indent_level
# TODO: assumes key is a string
buffer += key + ':'
if isinstance(val, dict):
buffer += '\n'
buffer += self._compile_key_val(val, indent_level+1)
elif (
isinstance(val, list) and
any(isinstance(i, (dict, list)) for i in val)
):
buffer += self._compile_list(val, indent_level+1)
else:
buffer += ' '
buffer += self._compile_value(val, indent_level)
buffer += '\n'
return buffer | python | def _compile_key_val(self, data, indent_level):
"""Compile a dictionary."""
buffer = ''
for (key, val) in data.items():
buffer += self._indent * indent_level
# TODO: assumes key is a string
buffer += key + ':'
if isinstance(val, dict):
buffer += '\n'
buffer += self._compile_key_val(val, indent_level+1)
elif (
isinstance(val, list) and
any(isinstance(i, (dict, list)) for i in val)
):
buffer += self._compile_list(val, indent_level+1)
else:
buffer += ' '
buffer += self._compile_value(val, indent_level)
buffer += '\n'
return buffer | [
"def",
"_compile_key_val",
"(",
"self",
",",
"data",
",",
"indent_level",
")",
":",
"buffer",
"=",
"''",
"for",
"(",
"key",
",",
"val",
")",
"in",
"data",
".",
"items",
"(",
")",
":",
"buffer",
"+=",
"self",
".",
"_indent",
"*",
"indent_level",
"# TODO: assumes key is a string",
"buffer",
"+=",
"key",
"+",
"':'",
"if",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"buffer",
"+=",
"'\\n'",
"buffer",
"+=",
"self",
".",
"_compile_key_val",
"(",
"val",
",",
"indent_level",
"+",
"1",
")",
"elif",
"(",
"isinstance",
"(",
"val",
",",
"list",
")",
"and",
"any",
"(",
"isinstance",
"(",
"i",
",",
"(",
"dict",
",",
"list",
")",
")",
"for",
"i",
"in",
"val",
")",
")",
":",
"buffer",
"+=",
"self",
".",
"_compile_list",
"(",
"val",
",",
"indent_level",
"+",
"1",
")",
"else",
":",
"buffer",
"+=",
"' '",
"buffer",
"+=",
"self",
".",
"_compile_value",
"(",
"val",
",",
"indent_level",
")",
"buffer",
"+=",
"'\\n'",
"return",
"buffer"
] | Compile a dictionary. | [
"Compile",
"a",
"dictionary",
"."
] | d0ea8fb1e417f1fedaa8e215e3d420b90c4de691 | https://github.com/Sean1708/HipPy/blob/d0ea8fb1e417f1fedaa8e215e3d420b90c4de691/hippy/compiler.py#L82-L103 |
246,711 | boronine/discipline | disciplinesite/tools.py | word | def word(cap=False):
""" This function generates a fake word by creating between two and three
random syllables and then joining them together.
"""
syllables = []
for x in range(random.randint(2,3)):
syllables.append(_syllable())
word = "".join(syllables)
if cap: word = word[0].upper() + word[1:]
return word | python | def word(cap=False):
""" This function generates a fake word by creating between two and three
random syllables and then joining them together.
"""
syllables = []
for x in range(random.randint(2,3)):
syllables.append(_syllable())
word = "".join(syllables)
if cap: word = word[0].upper() + word[1:]
return word | [
"def",
"word",
"(",
"cap",
"=",
"False",
")",
":",
"syllables",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"random",
".",
"randint",
"(",
"2",
",",
"3",
")",
")",
":",
"syllables",
".",
"append",
"(",
"_syllable",
"(",
")",
")",
"word",
"=",
"\"\"",
".",
"join",
"(",
"syllables",
")",
"if",
"cap",
":",
"word",
"=",
"word",
"[",
"0",
"]",
".",
"upper",
"(",
")",
"+",
"word",
"[",
"1",
":",
"]",
"return",
"word"
] | This function generates a fake word by creating between two and three
random syllables and then joining them together. | [
"This",
"function",
"generates",
"a",
"fake",
"word",
"by",
"creating",
"between",
"two",
"and",
"three",
"random",
"syllables",
"and",
"then",
"joining",
"them",
"together",
"."
] | 68bea9bc2198cc91cee49a6e2d0f3333cc9bf476 | https://github.com/boronine/discipline/blob/68bea9bc2198cc91cee49a6e2d0f3333cc9bf476/disciplinesite/tools.py#L23-L32 |
246,712 | treycucco/bidon | bidon/db/access/data_access.py | transaction | def transaction(data_access):
"""Wrap statements in a transaction. If the statements succeed, commit, otherwise rollback.
:param data_access: a DataAccess instance
"""
old_autocommit = data_access.autocommit
data_access.autocommit = False
try:
yield data_access
except RollbackTransaction as ex:
data_access.rollback()
except Exception as ex:
data_access.rollback()
raise ex
else:
data_access.commit()
finally:
data_access.autocommit = old_autocommit | python | def transaction(data_access):
"""Wrap statements in a transaction. If the statements succeed, commit, otherwise rollback.
:param data_access: a DataAccess instance
"""
old_autocommit = data_access.autocommit
data_access.autocommit = False
try:
yield data_access
except RollbackTransaction as ex:
data_access.rollback()
except Exception as ex:
data_access.rollback()
raise ex
else:
data_access.commit()
finally:
data_access.autocommit = old_autocommit | [
"def",
"transaction",
"(",
"data_access",
")",
":",
"old_autocommit",
"=",
"data_access",
".",
"autocommit",
"data_access",
".",
"autocommit",
"=",
"False",
"try",
":",
"yield",
"data_access",
"except",
"RollbackTransaction",
"as",
"ex",
":",
"data_access",
".",
"rollback",
"(",
")",
"except",
"Exception",
"as",
"ex",
":",
"data_access",
".",
"rollback",
"(",
")",
"raise",
"ex",
"else",
":",
"data_access",
".",
"commit",
"(",
")",
"finally",
":",
"data_access",
".",
"autocommit",
"=",
"old_autocommit"
] | Wrap statements in a transaction. If the statements succeed, commit, otherwise rollback.
:param data_access: a DataAccess instance | [
"Wrap",
"statements",
"in",
"a",
"transaction",
".",
"If",
"the",
"statements",
"succeed",
"commit",
"otherwise",
"rollback",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L425-L442 |
246,713 | treycucco/bidon | bidon/db/access/data_access.py | autocommit | def autocommit(data_access):
"""Make statements autocommit.
:param data_access: a DataAccess instance
"""
if not data_access.autocommit:
data_access.commit()
old_autocommit = data_access.autocommit
data_access.autocommit = True
try:
yield data_access
finally:
data_access.autocommit = old_autocommit | python | def autocommit(data_access):
"""Make statements autocommit.
:param data_access: a DataAccess instance
"""
if not data_access.autocommit:
data_access.commit()
old_autocommit = data_access.autocommit
data_access.autocommit = True
try:
yield data_access
finally:
data_access.autocommit = old_autocommit | [
"def",
"autocommit",
"(",
"data_access",
")",
":",
"if",
"not",
"data_access",
".",
"autocommit",
":",
"data_access",
".",
"commit",
"(",
")",
"old_autocommit",
"=",
"data_access",
".",
"autocommit",
"data_access",
".",
"autocommit",
"=",
"True",
"try",
":",
"yield",
"data_access",
"finally",
":",
"data_access",
".",
"autocommit",
"=",
"old_autocommit"
] | Make statements autocommit.
:param data_access: a DataAccess instance | [
"Make",
"statements",
"autocommit",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L446-L458 |
246,714 | treycucco/bidon | bidon/db/access/data_access.py | DataAccess.autocommit | def autocommit(self, value):
"""Set the autocommit value.
:param value: the new autocommit value
"""
logger.debug("Setting autocommit from %s to %s", self.autocommit, value)
self.core.set_autocommit(self.connection, value) | python | def autocommit(self, value):
"""Set the autocommit value.
:param value: the new autocommit value
"""
logger.debug("Setting autocommit from %s to %s", self.autocommit, value)
self.core.set_autocommit(self.connection, value) | [
"def",
"autocommit",
"(",
"self",
",",
"value",
")",
":",
"logger",
".",
"debug",
"(",
"\"Setting autocommit from %s to %s\"",
",",
"self",
".",
"autocommit",
",",
"value",
")",
"self",
".",
"core",
".",
"set_autocommit",
"(",
"self",
".",
"connection",
",",
"value",
")"
] | Set the autocommit value.
:param value: the new autocommit value | [
"Set",
"the",
"autocommit",
"value",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L79-L85 |
246,715 | treycucco/bidon | bidon/db/access/data_access.py | DataAccess._configure_connection | def _configure_connection(self, name, value):
"""Sets a Postgres run-time connection configuration parameter.
:param name: the name of the parameter
:param value: a list of values matching the placeholders
"""
self.update("pg_settings", dict(setting=value), dict(name=name)) | python | def _configure_connection(self, name, value):
"""Sets a Postgres run-time connection configuration parameter.
:param name: the name of the parameter
:param value: a list of values matching the placeholders
"""
self.update("pg_settings", dict(setting=value), dict(name=name)) | [
"def",
"_configure_connection",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"self",
".",
"update",
"(",
"\"pg_settings\"",
",",
"dict",
"(",
"setting",
"=",
"value",
")",
",",
"dict",
"(",
"name",
"=",
"name",
")",
")"
] | Sets a Postgres run-time connection configuration parameter.
:param name: the name of the parameter
:param value: a list of values matching the placeholders | [
"Sets",
"a",
"Postgres",
"run",
"-",
"time",
"connection",
"configuration",
"parameter",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L87-L93 |
246,716 | treycucco/bidon | bidon/db/access/data_access.py | DataAccess.open | def open(self, *, autocommit=False):
"""Sets the connection with the core's open method.
:param autocommit: the default autocommit state
:type autocommit: boolean
:return: self
"""
if self.connection is not None:
raise Exception("Connection already set")
self.connection = self.core.open()
self.autocommit = autocommit
if self._search_path:
self._configure_connection(
"search_path",
self._search_path)
return self | python | def open(self, *, autocommit=False):
"""Sets the connection with the core's open method.
:param autocommit: the default autocommit state
:type autocommit: boolean
:return: self
"""
if self.connection is not None:
raise Exception("Connection already set")
self.connection = self.core.open()
self.autocommit = autocommit
if self._search_path:
self._configure_connection(
"search_path",
self._search_path)
return self | [
"def",
"open",
"(",
"self",
",",
"*",
",",
"autocommit",
"=",
"False",
")",
":",
"if",
"self",
".",
"connection",
"is",
"not",
"None",
":",
"raise",
"Exception",
"(",
"\"Connection already set\"",
")",
"self",
".",
"connection",
"=",
"self",
".",
"core",
".",
"open",
"(",
")",
"self",
".",
"autocommit",
"=",
"autocommit",
"if",
"self",
".",
"_search_path",
":",
"self",
".",
"_configure_connection",
"(",
"\"search_path\"",
",",
"self",
".",
"_search_path",
")",
"return",
"self"
] | Sets the connection with the core's open method.
:param autocommit: the default autocommit state
:type autocommit: boolean
:return: self | [
"Sets",
"the",
"connection",
"with",
"the",
"core",
"s",
"open",
"method",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L95-L110 |
246,717 | treycucco/bidon | bidon/db/access/data_access.py | DataAccess.close | def close(self, *, commit=True):
"""Closes the connection via the core's close method.
:param commit: if true the current transaction is commited, otherwise it is rolled back
:type commit: boolean
:return: self
"""
self.core.close(self.connection, commit=commit)
self.connection = None
return self | python | def close(self, *, commit=True):
"""Closes the connection via the core's close method.
:param commit: if true the current transaction is commited, otherwise it is rolled back
:type commit: boolean
:return: self
"""
self.core.close(self.connection, commit=commit)
self.connection = None
return self | [
"def",
"close",
"(",
"self",
",",
"*",
",",
"commit",
"=",
"True",
")",
":",
"self",
".",
"core",
".",
"close",
"(",
"self",
".",
"connection",
",",
"commit",
"=",
"commit",
")",
"self",
".",
"connection",
"=",
"None",
"return",
"self"
] | Closes the connection via the core's close method.
:param commit: if true the current transaction is commited, otherwise it is rolled back
:type commit: boolean
:return: self | [
"Closes",
"the",
"connection",
"via",
"the",
"core",
"s",
"close",
"method",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L112-L121 |
246,718 | treycucco/bidon | bidon/db/access/data_access.py | DataAccess.execute | def execute(self, query_string, params=None):
"""Executes a query. Returns the resulting cursor.
:query_string: the parameterized query string
:params: can be either a tuple or a dictionary, and must match the parameterization style of the
query
:return: a cursor object
"""
cr = self.connection.cursor()
logger.info("SQL: %s (%s)", query_string, params)
self.last_query = (query_string, params)
t0 = time.time()
cr.execute(query_string, params or self.core.empty_params)
ms = (time.time() - t0) * 1000
logger.info("RUNTIME: %.2f ms", ms)
self._update_cursor_stats(cr)
return cr | python | def execute(self, query_string, params=None):
"""Executes a query. Returns the resulting cursor.
:query_string: the parameterized query string
:params: can be either a tuple or a dictionary, and must match the parameterization style of the
query
:return: a cursor object
"""
cr = self.connection.cursor()
logger.info("SQL: %s (%s)", query_string, params)
self.last_query = (query_string, params)
t0 = time.time()
cr.execute(query_string, params or self.core.empty_params)
ms = (time.time() - t0) * 1000
logger.info("RUNTIME: %.2f ms", ms)
self._update_cursor_stats(cr)
return cr | [
"def",
"execute",
"(",
"self",
",",
"query_string",
",",
"params",
"=",
"None",
")",
":",
"cr",
"=",
"self",
".",
"connection",
".",
"cursor",
"(",
")",
"logger",
".",
"info",
"(",
"\"SQL: %s (%s)\"",
",",
"query_string",
",",
"params",
")",
"self",
".",
"last_query",
"=",
"(",
"query_string",
",",
"params",
")",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"cr",
".",
"execute",
"(",
"query_string",
",",
"params",
"or",
"self",
".",
"core",
".",
"empty_params",
")",
"ms",
"=",
"(",
"time",
".",
"time",
"(",
")",
"-",
"t0",
")",
"*",
"1000",
"logger",
".",
"info",
"(",
"\"RUNTIME: %.2f ms\"",
",",
"ms",
")",
"self",
".",
"_update_cursor_stats",
"(",
"cr",
")",
"return",
"cr"
] | Executes a query. Returns the resulting cursor.
:query_string: the parameterized query string
:params: can be either a tuple or a dictionary, and must match the parameterization style of the
query
:return: a cursor object | [
"Executes",
"a",
"query",
".",
"Returns",
"the",
"resulting",
"cursor",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L123-L139 |
246,719 | treycucco/bidon | bidon/db/access/data_access.py | DataAccess.callproc | def callproc(self, name, params, param_types=None):
"""Calls a procedure.
:param name: the name of the procedure
:param params: a list or tuple of parameters to pass to the procedure.
:param param_types: a list or tuple of type names. If given, each param will be cast via
sql_writers typecast method. This is useful to disambiguate procedure calls
when several parameters are null and therefore cause overload resoluation
issues.
:return: a 2-tuple of (cursor, params)
"""
if param_types:
placeholders = [self.sql_writer.typecast(self.sql_writer.to_placeholder(), t)
for t in param_types]
else:
placeholders = [self.sql_writer.to_placeholder() for p in params]
# TODO: This may be Postgres specific...
qs = "select * from {0}({1});".format(name, ", ".join(placeholders))
return self.execute(qs, params), params | python | def callproc(self, name, params, param_types=None):
"""Calls a procedure.
:param name: the name of the procedure
:param params: a list or tuple of parameters to pass to the procedure.
:param param_types: a list or tuple of type names. If given, each param will be cast via
sql_writers typecast method. This is useful to disambiguate procedure calls
when several parameters are null and therefore cause overload resoluation
issues.
:return: a 2-tuple of (cursor, params)
"""
if param_types:
placeholders = [self.sql_writer.typecast(self.sql_writer.to_placeholder(), t)
for t in param_types]
else:
placeholders = [self.sql_writer.to_placeholder() for p in params]
# TODO: This may be Postgres specific...
qs = "select * from {0}({1});".format(name, ", ".join(placeholders))
return self.execute(qs, params), params | [
"def",
"callproc",
"(",
"self",
",",
"name",
",",
"params",
",",
"param_types",
"=",
"None",
")",
":",
"if",
"param_types",
":",
"placeholders",
"=",
"[",
"self",
".",
"sql_writer",
".",
"typecast",
"(",
"self",
".",
"sql_writer",
".",
"to_placeholder",
"(",
")",
",",
"t",
")",
"for",
"t",
"in",
"param_types",
"]",
"else",
":",
"placeholders",
"=",
"[",
"self",
".",
"sql_writer",
".",
"to_placeholder",
"(",
")",
"for",
"p",
"in",
"params",
"]",
"# TODO: This may be Postgres specific...",
"qs",
"=",
"\"select * from {0}({1});\"",
".",
"format",
"(",
"name",
",",
"\", \"",
".",
"join",
"(",
"placeholders",
")",
")",
"return",
"self",
".",
"execute",
"(",
"qs",
",",
"params",
")",
",",
"params"
] | Calls a procedure.
:param name: the name of the procedure
:param params: a list or tuple of parameters to pass to the procedure.
:param param_types: a list or tuple of type names. If given, each param will be cast via
sql_writers typecast method. This is useful to disambiguate procedure calls
when several parameters are null and therefore cause overload resoluation
issues.
:return: a 2-tuple of (cursor, params) | [
"Calls",
"a",
"procedure",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L141-L161 |
246,720 | treycucco/bidon | bidon/db/access/data_access.py | DataAccess.get_callproc_signature | def get_callproc_signature(self, name, param_types):
"""Returns a procedure's signature from the name and list of types.
:name: the name of the procedure
:params: can be either strings, or 2-tuples. 2-tuples must be of the form (name, db_type).
:return: the procedure's signature
"""
if isinstance(param_types[0], (list, tuple)):
params = [self.sql_writer.to_placeholder(*pt) for pt in param_types]
else:
params = [self.sql_writer.to_placeholder(None, pt) for pt in param_types]
return name + self.sql_writer.to_tuple(params) | python | def get_callproc_signature(self, name, param_types):
"""Returns a procedure's signature from the name and list of types.
:name: the name of the procedure
:params: can be either strings, or 2-tuples. 2-tuples must be of the form (name, db_type).
:return: the procedure's signature
"""
if isinstance(param_types[0], (list, tuple)):
params = [self.sql_writer.to_placeholder(*pt) for pt in param_types]
else:
params = [self.sql_writer.to_placeholder(None, pt) for pt in param_types]
return name + self.sql_writer.to_tuple(params) | [
"def",
"get_callproc_signature",
"(",
"self",
",",
"name",
",",
"param_types",
")",
":",
"if",
"isinstance",
"(",
"param_types",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"params",
"=",
"[",
"self",
".",
"sql_writer",
".",
"to_placeholder",
"(",
"*",
"pt",
")",
"for",
"pt",
"in",
"param_types",
"]",
"else",
":",
"params",
"=",
"[",
"self",
".",
"sql_writer",
".",
"to_placeholder",
"(",
"None",
",",
"pt",
")",
"for",
"pt",
"in",
"param_types",
"]",
"return",
"name",
"+",
"self",
".",
"sql_writer",
".",
"to_tuple",
"(",
"params",
")"
] | Returns a procedure's signature from the name and list of types.
:name: the name of the procedure
:params: can be either strings, or 2-tuples. 2-tuples must be of the form (name, db_type).
:return: the procedure's signature | [
"Returns",
"a",
"procedure",
"s",
"signature",
"from",
"the",
"name",
"and",
"list",
"of",
"types",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L163-L175 |
246,721 | treycucco/bidon | bidon/db/access/data_access.py | DataAccess.find | def find(self, table_name, constraints=None, *, columns=None, order_by=None):
"""Returns the first record that matches the given criteria.
:table_name: the name of the table to search on
:constraints: is any construct that can be parsed by SqlWriter.parse_constraints.
:columns: either a string or a list of column names
:order_by: the order by clause
"""
query_string, params = self.sql_writer.get_find_all_query(
table_name, constraints, columns=columns, order_by=order_by)
query_string += " limit 1;"
return self.execute(query_string, params).fetchone() | python | def find(self, table_name, constraints=None, *, columns=None, order_by=None):
"""Returns the first record that matches the given criteria.
:table_name: the name of the table to search on
:constraints: is any construct that can be parsed by SqlWriter.parse_constraints.
:columns: either a string or a list of column names
:order_by: the order by clause
"""
query_string, params = self.sql_writer.get_find_all_query(
table_name, constraints, columns=columns, order_by=order_by)
query_string += " limit 1;"
return self.execute(query_string, params).fetchone() | [
"def",
"find",
"(",
"self",
",",
"table_name",
",",
"constraints",
"=",
"None",
",",
"*",
",",
"columns",
"=",
"None",
",",
"order_by",
"=",
"None",
")",
":",
"query_string",
",",
"params",
"=",
"self",
".",
"sql_writer",
".",
"get_find_all_query",
"(",
"table_name",
",",
"constraints",
",",
"columns",
"=",
"columns",
",",
"order_by",
"=",
"order_by",
")",
"query_string",
"+=",
"\" limit 1;\"",
"return",
"self",
".",
"execute",
"(",
"query_string",
",",
"params",
")",
".",
"fetchone",
"(",
")"
] | Returns the first record that matches the given criteria.
:table_name: the name of the table to search on
:constraints: is any construct that can be parsed by SqlWriter.parse_constraints.
:columns: either a string or a list of column names
:order_by: the order by clause | [
"Returns",
"the",
"first",
"record",
"that",
"matches",
"the",
"given",
"criteria",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L177-L188 |
246,722 | treycucco/bidon | bidon/db/access/data_access.py | DataAccess.find_all | def find_all(self, table_name, constraints=None, *, columns=None, order_by=None, limiting=None):
"""Returns all records that match a given criteria.
:table_name: the name of the table to search on
:constraints: is any construct that can be parsed by SqlWriter.parse_constraints.
:columns: either a string or a list of column names
:order_by: the order by clause
"""
query_string, params = self.sql_writer.get_find_all_query(
table_name, constraints, columns=columns, order_by=order_by, limiting=limiting)
query_string += ";"
return self.execute(query_string, params) | python | def find_all(self, table_name, constraints=None, *, columns=None, order_by=None, limiting=None):
"""Returns all records that match a given criteria.
:table_name: the name of the table to search on
:constraints: is any construct that can be parsed by SqlWriter.parse_constraints.
:columns: either a string or a list of column names
:order_by: the order by clause
"""
query_string, params = self.sql_writer.get_find_all_query(
table_name, constraints, columns=columns, order_by=order_by, limiting=limiting)
query_string += ";"
return self.execute(query_string, params) | [
"def",
"find_all",
"(",
"self",
",",
"table_name",
",",
"constraints",
"=",
"None",
",",
"*",
",",
"columns",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"limiting",
"=",
"None",
")",
":",
"query_string",
",",
"params",
"=",
"self",
".",
"sql_writer",
".",
"get_find_all_query",
"(",
"table_name",
",",
"constraints",
",",
"columns",
"=",
"columns",
",",
"order_by",
"=",
"order_by",
",",
"limiting",
"=",
"limiting",
")",
"query_string",
"+=",
"\";\"",
"return",
"self",
".",
"execute",
"(",
"query_string",
",",
"params",
")"
] | Returns all records that match a given criteria.
:table_name: the name of the table to search on
:constraints: is any construct that can be parsed by SqlWriter.parse_constraints.
:columns: either a string or a list of column names
:order_by: the order by clause | [
"Returns",
"all",
"records",
"that",
"match",
"a",
"given",
"criteria",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L190-L201 |
246,723 | treycucco/bidon | bidon/db/access/data_access.py | DataAccess.page | def page(self, table_name, paging, constraints=None, *, columns=None, order_by=None,
get_count=True):
"""Performs a find_all method with paging.
:param table_name: the name of the table to search on
:param paging: is a tuple containing (page, page_size).
:param constraints: is any construct that can be parsed by SqlWriter.parse_constraints.
:param columns: either a string or a list of column names
:param order_by: the order by clause
:param get_count: if True, the total number of records that would be included without paging are
returned. If False, None is returned for the count.
:return: a 2-tuple of (records, total_count)
"""
if get_count:
count = self.count(table_name, constraints)
else:
count = None
page, page_size = paging
limiting = None
if page_size > 0:
limiting = (page_size, page * page_size)
records = list(self.find_all(
table_name, constraints, columns=columns, order_by=order_by, limiting=limiting))
return (records, count) | python | def page(self, table_name, paging, constraints=None, *, columns=None, order_by=None,
get_count=True):
"""Performs a find_all method with paging.
:param table_name: the name of the table to search on
:param paging: is a tuple containing (page, page_size).
:param constraints: is any construct that can be parsed by SqlWriter.parse_constraints.
:param columns: either a string or a list of column names
:param order_by: the order by clause
:param get_count: if True, the total number of records that would be included without paging are
returned. If False, None is returned for the count.
:return: a 2-tuple of (records, total_count)
"""
if get_count:
count = self.count(table_name, constraints)
else:
count = None
page, page_size = paging
limiting = None
if page_size > 0:
limiting = (page_size, page * page_size)
records = list(self.find_all(
table_name, constraints, columns=columns, order_by=order_by, limiting=limiting))
return (records, count) | [
"def",
"page",
"(",
"self",
",",
"table_name",
",",
"paging",
",",
"constraints",
"=",
"None",
",",
"*",
",",
"columns",
"=",
"None",
",",
"order_by",
"=",
"None",
",",
"get_count",
"=",
"True",
")",
":",
"if",
"get_count",
":",
"count",
"=",
"self",
".",
"count",
"(",
"table_name",
",",
"constraints",
")",
"else",
":",
"count",
"=",
"None",
"page",
",",
"page_size",
"=",
"paging",
"limiting",
"=",
"None",
"if",
"page_size",
">",
"0",
":",
"limiting",
"=",
"(",
"page_size",
",",
"page",
"*",
"page_size",
")",
"records",
"=",
"list",
"(",
"self",
".",
"find_all",
"(",
"table_name",
",",
"constraints",
",",
"columns",
"=",
"columns",
",",
"order_by",
"=",
"order_by",
",",
"limiting",
"=",
"limiting",
")",
")",
"return",
"(",
"records",
",",
"count",
")"
] | Performs a find_all method with paging.
:param table_name: the name of the table to search on
:param paging: is a tuple containing (page, page_size).
:param constraints: is any construct that can be parsed by SqlWriter.parse_constraints.
:param columns: either a string or a list of column names
:param order_by: the order by clause
:param get_count: if True, the total number of records that would be included without paging are
returned. If False, None is returned for the count.
:return: a 2-tuple of (records, total_count) | [
"Performs",
"a",
"find_all",
"method",
"with",
"paging",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L203-L229 |
246,724 | treycucco/bidon | bidon/db/access/data_access.py | DataAccess.update | def update(self, table_name, values, constraints=None, *, returning=None):
"""Builds and executes and update statement.
:param table_name: the name of the table to update
:param values: can be either a dict or an enuerable of 2-tuples in the form (column, value).
:param constraints: can be any construct that can be parsed by SqlWriter.parse_constraints.
However, you cannot mix tuples and dicts between values and constraints.
:param returning: the columns to return after updating. Only works for cores that support the
returning syntax
:return: a cursor object
"""
if constraints is None:
constraints = "1=1"
assignments, assignment_params = self.sql_writer.parse_constraints(
values, ", ", is_assignment=True)
where, where_params = self.sql_writer.parse_constraints(constraints, " and ")
returns = ""
if returning and self.core.supports_returning_syntax:
returns = " returning {0}".format(returning)
sql = "update {0} set {1} where {2}{3};".format(table_name, assignments, where, returns)
params = assignment_params
if constraints is None or isinstance(constraints, str):
pass
elif isinstance(constraints, dict):
if isinstance(params, list):
raise ValueError("you cannot mix enumerable and dict values and constraints")
params = params or {}
params.update(where_params)
else:
if isinstance(params, dict):
raise ValueError("you cannot mix enumerable and dict values and constraints")
params = params or []
params.extend(where_params)
cr = self.execute(sql, params)
return cr | python | def update(self, table_name, values, constraints=None, *, returning=None):
"""Builds and executes and update statement.
:param table_name: the name of the table to update
:param values: can be either a dict or an enuerable of 2-tuples in the form (column, value).
:param constraints: can be any construct that can be parsed by SqlWriter.parse_constraints.
However, you cannot mix tuples and dicts between values and constraints.
:param returning: the columns to return after updating. Only works for cores that support the
returning syntax
:return: a cursor object
"""
if constraints is None:
constraints = "1=1"
assignments, assignment_params = self.sql_writer.parse_constraints(
values, ", ", is_assignment=True)
where, where_params = self.sql_writer.parse_constraints(constraints, " and ")
returns = ""
if returning and self.core.supports_returning_syntax:
returns = " returning {0}".format(returning)
sql = "update {0} set {1} where {2}{3};".format(table_name, assignments, where, returns)
params = assignment_params
if constraints is None or isinstance(constraints, str):
pass
elif isinstance(constraints, dict):
if isinstance(params, list):
raise ValueError("you cannot mix enumerable and dict values and constraints")
params = params or {}
params.update(where_params)
else:
if isinstance(params, dict):
raise ValueError("you cannot mix enumerable and dict values and constraints")
params = params or []
params.extend(where_params)
cr = self.execute(sql, params)
return cr | [
"def",
"update",
"(",
"self",
",",
"table_name",
",",
"values",
",",
"constraints",
"=",
"None",
",",
"*",
",",
"returning",
"=",
"None",
")",
":",
"if",
"constraints",
"is",
"None",
":",
"constraints",
"=",
"\"1=1\"",
"assignments",
",",
"assignment_params",
"=",
"self",
".",
"sql_writer",
".",
"parse_constraints",
"(",
"values",
",",
"\", \"",
",",
"is_assignment",
"=",
"True",
")",
"where",
",",
"where_params",
"=",
"self",
".",
"sql_writer",
".",
"parse_constraints",
"(",
"constraints",
",",
"\" and \"",
")",
"returns",
"=",
"\"\"",
"if",
"returning",
"and",
"self",
".",
"core",
".",
"supports_returning_syntax",
":",
"returns",
"=",
"\" returning {0}\"",
".",
"format",
"(",
"returning",
")",
"sql",
"=",
"\"update {0} set {1} where {2}{3};\"",
".",
"format",
"(",
"table_name",
",",
"assignments",
",",
"where",
",",
"returns",
")",
"params",
"=",
"assignment_params",
"if",
"constraints",
"is",
"None",
"or",
"isinstance",
"(",
"constraints",
",",
"str",
")",
":",
"pass",
"elif",
"isinstance",
"(",
"constraints",
",",
"dict",
")",
":",
"if",
"isinstance",
"(",
"params",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"you cannot mix enumerable and dict values and constraints\"",
")",
"params",
"=",
"params",
"or",
"{",
"}",
"params",
".",
"update",
"(",
"where_params",
")",
"else",
":",
"if",
"isinstance",
"(",
"params",
",",
"dict",
")",
":",
"raise",
"ValueError",
"(",
"\"you cannot mix enumerable and dict values and constraints\"",
")",
"params",
"=",
"params",
"or",
"[",
"]",
"params",
".",
"extend",
"(",
"where_params",
")",
"cr",
"=",
"self",
".",
"execute",
"(",
"sql",
",",
"params",
")",
"return",
"cr"
] | Builds and executes and update statement.
:param table_name: the name of the table to update
:param values: can be either a dict or an enuerable of 2-tuples in the form (column, value).
:param constraints: can be any construct that can be parsed by SqlWriter.parse_constraints.
However, you cannot mix tuples and dicts between values and constraints.
:param returning: the columns to return after updating. Only works for cores that support the
returning syntax
:return: a cursor object | [
"Builds",
"and",
"executes",
"and",
"update",
"statement",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L231-L267 |
246,725 | treycucco/bidon | bidon/db/access/data_access.py | DataAccess.delete | def delete(self, table_name, constraints=None):
"""Builds and executes an delete statement.
:param table_name: the name of the table to delete from
:param constraints: can be any construct that can be parsed by SqlWriter.parse_constraints.
:return: a cursor object
"""
if constraints is None:
constraints = "1=1"
where, params = self.sql_writer.parse_constraints(constraints)
sql = "delete from {0} where {1};".format(table_name, where)
self.execute(sql, params) | python | def delete(self, table_name, constraints=None):
"""Builds and executes an delete statement.
:param table_name: the name of the table to delete from
:param constraints: can be any construct that can be parsed by SqlWriter.parse_constraints.
:return: a cursor object
"""
if constraints is None:
constraints = "1=1"
where, params = self.sql_writer.parse_constraints(constraints)
sql = "delete from {0} where {1};".format(table_name, where)
self.execute(sql, params) | [
"def",
"delete",
"(",
"self",
",",
"table_name",
",",
"constraints",
"=",
"None",
")",
":",
"if",
"constraints",
"is",
"None",
":",
"constraints",
"=",
"\"1=1\"",
"where",
",",
"params",
"=",
"self",
".",
"sql_writer",
".",
"parse_constraints",
"(",
"constraints",
")",
"sql",
"=",
"\"delete from {0} where {1};\"",
".",
"format",
"(",
"table_name",
",",
"where",
")",
"self",
".",
"execute",
"(",
"sql",
",",
"params",
")"
] | Builds and executes an delete statement.
:param table_name: the name of the table to delete from
:param constraints: can be any construct that can be parsed by SqlWriter.parse_constraints.
:return: a cursor object | [
"Builds",
"and",
"executes",
"an",
"delete",
"statement",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L342-L353 |
246,726 | treycucco/bidon | bidon/db/access/data_access.py | DataAccess.count | def count(self, table_name, constraints=None, *, extract="index"):
"""Returns the count of records in a table.
If the default cursor is a tuple or named tuple, this method will work without specifying an
extract parameter. If it is a dict cursor, it is necessary to specify any value other than
'index' for extract. This method will not work with cursors that aren't like tuple, namedtuple
or dict cursors.
:param table_name: the name of the table to count records on
:param constraints: can be any construct that can be parsed by SqlWriter.parse_constraints.
:param extract: the property to pull the count value from the cursor
:return: the nuber of records matching the constraints
"""
where, params = self.sql_writer.parse_constraints(constraints)
sql = "select count(*) as count from {0} where {1};".format(table_name, where or "1 = 1")
# NOTE: Won't work right with dict cursor
return self.get_scalar(self.execute(sql, params), 0 if extract == "index" else "count") | python | def count(self, table_name, constraints=None, *, extract="index"):
"""Returns the count of records in a table.
If the default cursor is a tuple or named tuple, this method will work without specifying an
extract parameter. If it is a dict cursor, it is necessary to specify any value other than
'index' for extract. This method will not work with cursors that aren't like tuple, namedtuple
or dict cursors.
:param table_name: the name of the table to count records on
:param constraints: can be any construct that can be parsed by SqlWriter.parse_constraints.
:param extract: the property to pull the count value from the cursor
:return: the nuber of records matching the constraints
"""
where, params = self.sql_writer.parse_constraints(constraints)
sql = "select count(*) as count from {0} where {1};".format(table_name, where or "1 = 1")
# NOTE: Won't work right with dict cursor
return self.get_scalar(self.execute(sql, params), 0 if extract == "index" else "count") | [
"def",
"count",
"(",
"self",
",",
"table_name",
",",
"constraints",
"=",
"None",
",",
"*",
",",
"extract",
"=",
"\"index\"",
")",
":",
"where",
",",
"params",
"=",
"self",
".",
"sql_writer",
".",
"parse_constraints",
"(",
"constraints",
")",
"sql",
"=",
"\"select count(*) as count from {0} where {1};\"",
".",
"format",
"(",
"table_name",
",",
"where",
"or",
"\"1 = 1\"",
")",
"# NOTE: Won't work right with dict cursor",
"return",
"self",
".",
"get_scalar",
"(",
"self",
".",
"execute",
"(",
"sql",
",",
"params",
")",
",",
"0",
"if",
"extract",
"==",
"\"index\"",
"else",
"\"count\"",
")"
] | Returns the count of records in a table.
If the default cursor is a tuple or named tuple, this method will work without specifying an
extract parameter. If it is a dict cursor, it is necessary to specify any value other than
'index' for extract. This method will not work with cursors that aren't like tuple, namedtuple
or dict cursors.
:param table_name: the name of the table to count records on
:param constraints: can be any construct that can be parsed by SqlWriter.parse_constraints.
:param extract: the property to pull the count value from the cursor
:return: the nuber of records matching the constraints | [
"Returns",
"the",
"count",
"of",
"records",
"in",
"a",
"table",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L355-L371 |
246,727 | treycucco/bidon | bidon/db/access/data_access.py | DataAccess.get_scalar | def get_scalar(self, cursor, index=0):
"""Returns a single value from the first returned record from a cursor.
By default it will get cursor.fecthone()[0] which works with tuples and namedtuples. For dict
cursor it is necessary to specify index. This method will not work with cursors that aren't
indexable.
:param cursor: a cursor object
:param index: the index of the cursor to return the value from
"""
if isinstance(index, int):
return cursor.fetchone()[index]
else:
return get_value(cursor.fetchone(), index) | python | def get_scalar(self, cursor, index=0):
"""Returns a single value from the first returned record from a cursor.
By default it will get cursor.fecthone()[0] which works with tuples and namedtuples. For dict
cursor it is necessary to specify index. This method will not work with cursors that aren't
indexable.
:param cursor: a cursor object
:param index: the index of the cursor to return the value from
"""
if isinstance(index, int):
return cursor.fetchone()[index]
else:
return get_value(cursor.fetchone(), index) | [
"def",
"get_scalar",
"(",
"self",
",",
"cursor",
",",
"index",
"=",
"0",
")",
":",
"if",
"isinstance",
"(",
"index",
",",
"int",
")",
":",
"return",
"cursor",
".",
"fetchone",
"(",
")",
"[",
"index",
"]",
"else",
":",
"return",
"get_value",
"(",
"cursor",
".",
"fetchone",
"(",
")",
",",
"index",
")"
] | Returns a single value from the first returned record from a cursor.
By default it will get cursor.fecthone()[0] which works with tuples and namedtuples. For dict
cursor it is necessary to specify index. This method will not work with cursors that aren't
indexable.
:param cursor: a cursor object
:param index: the index of the cursor to return the value from | [
"Returns",
"a",
"single",
"value",
"from",
"the",
"first",
"returned",
"record",
"from",
"a",
"cursor",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L373-L386 |
246,728 | treycucco/bidon | bidon/db/access/data_access.py | Upsert.target_str | def target_str(self):
"""Returns the string representation of the target property."""
if isinstance(self.target, tuple):
return "({})".format(", ".join(self.target))
else:
return self.target | python | def target_str(self):
"""Returns the string representation of the target property."""
if isinstance(self.target, tuple):
return "({})".format(", ".join(self.target))
else:
return self.target | [
"def",
"target_str",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"target",
",",
"tuple",
")",
":",
"return",
"\"({})\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"self",
".",
"target",
")",
")",
"else",
":",
"return",
"self",
".",
"target"
] | Returns the string representation of the target property. | [
"Returns",
"the",
"string",
"representation",
"of",
"the",
"target",
"property",
"."
] | d9f24596841d0e69e8ac70a1d1a1deecea95e340 | https://github.com/treycucco/bidon/blob/d9f24596841d0e69e8ac70a1d1a1deecea95e340/bidon/db/access/data_access.py#L409-L414 |
246,729 | sys-git/certifiable | certifiable/cli_impl/core/certify_number.py | cli_certify_core_number | def cli_certify_core_number(
config, min_value, max_value, value,
):
"""Console script for certify_number"""
verbose = config['verbose']
if verbose:
click.echo(Back.GREEN + Fore.BLACK + "ACTION: certify-int")
def parser(v):
# Attempt a json/pickle decode:
try:
v = load_json_pickle(v, config)
except Exception:
pass
# Attempt a straight conversion to float or integer:
try:
if v.find('.') != -1:
# Assume is float:
v = float(v)
else:
# Assume is int:
v = int(v)
return v
except Exception as err:
six.raise_from(
CertifierTypeError(
message='Not integer or float: {v}'.format(
v=v,
),
value=v,
),
err,
)
execute_cli_command(
'number',
config,
parser,
certify_number,
value[0] if value else None,
min_value=min_value,
max_value=max_value,
required=config['required'],
) | python | def cli_certify_core_number(
config, min_value, max_value, value,
):
"""Console script for certify_number"""
verbose = config['verbose']
if verbose:
click.echo(Back.GREEN + Fore.BLACK + "ACTION: certify-int")
def parser(v):
# Attempt a json/pickle decode:
try:
v = load_json_pickle(v, config)
except Exception:
pass
# Attempt a straight conversion to float or integer:
try:
if v.find('.') != -1:
# Assume is float:
v = float(v)
else:
# Assume is int:
v = int(v)
return v
except Exception as err:
six.raise_from(
CertifierTypeError(
message='Not integer or float: {v}'.format(
v=v,
),
value=v,
),
err,
)
execute_cli_command(
'number',
config,
parser,
certify_number,
value[0] if value else None,
min_value=min_value,
max_value=max_value,
required=config['required'],
) | [
"def",
"cli_certify_core_number",
"(",
"config",
",",
"min_value",
",",
"max_value",
",",
"value",
",",
")",
":",
"verbose",
"=",
"config",
"[",
"'verbose'",
"]",
"if",
"verbose",
":",
"click",
".",
"echo",
"(",
"Back",
".",
"GREEN",
"+",
"Fore",
".",
"BLACK",
"+",
"\"ACTION: certify-int\"",
")",
"def",
"parser",
"(",
"v",
")",
":",
"# Attempt a json/pickle decode:",
"try",
":",
"v",
"=",
"load_json_pickle",
"(",
"v",
",",
"config",
")",
"except",
"Exception",
":",
"pass",
"# Attempt a straight conversion to float or integer:",
"try",
":",
"if",
"v",
".",
"find",
"(",
"'.'",
")",
"!=",
"-",
"1",
":",
"# Assume is float:",
"v",
"=",
"float",
"(",
"v",
")",
"else",
":",
"# Assume is int:",
"v",
"=",
"int",
"(",
"v",
")",
"return",
"v",
"except",
"Exception",
"as",
"err",
":",
"six",
".",
"raise_from",
"(",
"CertifierTypeError",
"(",
"message",
"=",
"'Not integer or float: {v}'",
".",
"format",
"(",
"v",
"=",
"v",
",",
")",
",",
"value",
"=",
"v",
",",
")",
",",
"err",
",",
")",
"execute_cli_command",
"(",
"'number'",
",",
"config",
",",
"parser",
",",
"certify_number",
",",
"value",
"[",
"0",
"]",
"if",
"value",
"else",
"None",
",",
"min_value",
"=",
"min_value",
",",
"max_value",
"=",
"max_value",
",",
"required",
"=",
"config",
"[",
"'required'",
"]",
",",
")"
] | Console script for certify_number | [
"Console",
"script",
"for",
"certify_number"
] | a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8 | https://github.com/sys-git/certifiable/blob/a3c33c0d4f3ac2c53be9eded3fae633fa5f697f8/certifiable/cli_impl/core/certify_number.py#L24-L68 |
246,730 | alexhayes/django-toolkit | django_toolkit/url/resolve.py | resolve_url | def resolve_url(url, desktop_user_agent=None, mobile_user_agent=None):
"""
Url Resolver
Given a url a list of resolved urls is returned for desktop and mobile user agents
"""
if not desktop_user_agent:
desktop_user_agent = DESKTOP_USER_AGENT
if not mobile_user_agent:
mobile_user_agent = MOBILE_USER_AGENT
input_urls = set()
parsed = urlparse(url_with_protocol(url))
netloc = parsed.netloc
if netloc.startswith('www.'):
netloc = netloc[4:]
input_urls.add('http://%s%s' % (netloc, parsed.path if parsed.path else '/'))
input_urls.add('http://www.%s%s' % (netloc, parsed.path if parsed.path else '/'))
resolved_urls = set()
for input_url in input_urls:
desktop_request = requests.get(input_url, headers={'User-Agent': desktop_user_agent})
resolved_urls.add(desktop_request.url)
mobile_request = requests.get(input_url, headers={'User-Agent': mobile_user_agent})
resolved_urls.add(mobile_request.url)
return list(resolved_urls) | python | def resolve_url(url, desktop_user_agent=None, mobile_user_agent=None):
"""
Url Resolver
Given a url a list of resolved urls is returned for desktop and mobile user agents
"""
if not desktop_user_agent:
desktop_user_agent = DESKTOP_USER_AGENT
if not mobile_user_agent:
mobile_user_agent = MOBILE_USER_AGENT
input_urls = set()
parsed = urlparse(url_with_protocol(url))
netloc = parsed.netloc
if netloc.startswith('www.'):
netloc = netloc[4:]
input_urls.add('http://%s%s' % (netloc, parsed.path if parsed.path else '/'))
input_urls.add('http://www.%s%s' % (netloc, parsed.path if parsed.path else '/'))
resolved_urls = set()
for input_url in input_urls:
desktop_request = requests.get(input_url, headers={'User-Agent': desktop_user_agent})
resolved_urls.add(desktop_request.url)
mobile_request = requests.get(input_url, headers={'User-Agent': mobile_user_agent})
resolved_urls.add(mobile_request.url)
return list(resolved_urls) | [
"def",
"resolve_url",
"(",
"url",
",",
"desktop_user_agent",
"=",
"None",
",",
"mobile_user_agent",
"=",
"None",
")",
":",
"if",
"not",
"desktop_user_agent",
":",
"desktop_user_agent",
"=",
"DESKTOP_USER_AGENT",
"if",
"not",
"mobile_user_agent",
":",
"mobile_user_agent",
"=",
"MOBILE_USER_AGENT",
"input_urls",
"=",
"set",
"(",
")",
"parsed",
"=",
"urlparse",
"(",
"url_with_protocol",
"(",
"url",
")",
")",
"netloc",
"=",
"parsed",
".",
"netloc",
"if",
"netloc",
".",
"startswith",
"(",
"'www.'",
")",
":",
"netloc",
"=",
"netloc",
"[",
"4",
":",
"]",
"input_urls",
".",
"add",
"(",
"'http://%s%s'",
"%",
"(",
"netloc",
",",
"parsed",
".",
"path",
"if",
"parsed",
".",
"path",
"else",
"'/'",
")",
")",
"input_urls",
".",
"add",
"(",
"'http://www.%s%s'",
"%",
"(",
"netloc",
",",
"parsed",
".",
"path",
"if",
"parsed",
".",
"path",
"else",
"'/'",
")",
")",
"resolved_urls",
"=",
"set",
"(",
")",
"for",
"input_url",
"in",
"input_urls",
":",
"desktop_request",
"=",
"requests",
".",
"get",
"(",
"input_url",
",",
"headers",
"=",
"{",
"'User-Agent'",
":",
"desktop_user_agent",
"}",
")",
"resolved_urls",
".",
"add",
"(",
"desktop_request",
".",
"url",
")",
"mobile_request",
"=",
"requests",
".",
"get",
"(",
"input_url",
",",
"headers",
"=",
"{",
"'User-Agent'",
":",
"mobile_user_agent",
"}",
")",
"resolved_urls",
".",
"add",
"(",
"mobile_request",
".",
"url",
")",
"return",
"list",
"(",
"resolved_urls",
")"
] | Url Resolver
Given a url a list of resolved urls is returned for desktop and mobile user agents | [
"Url",
"Resolver",
"Given",
"a",
"url",
"a",
"list",
"of",
"resolved",
"urls",
"is",
"returned",
"for",
"desktop",
"and",
"mobile",
"user",
"agents"
] | b64106392fad596defc915b8235fe6e1d0013b5b | https://github.com/alexhayes/django-toolkit/blob/b64106392fad596defc915b8235fe6e1d0013b5b/django_toolkit/url/resolve.py#L22-L51 |
246,731 | jorgeecardona/dynect | dynect/__init__.py | DynectAuth.token | def token(self):
" Get token when needed."
if hasattr(self, '_token'):
return getattr(self, '_token')
# Json formatted auth.
data = json.dumps({'customer_name': self.customer,
'user_name': self.username,
'password': self.password})
# Start session.
response = requests.post(
'https://api2.dynect.net/REST/Session/', data=data,
headers={'Content-Type': 'application/json'})
# convert to data.
content = json.loads(response.content)
if response.status_code != 200:
# Check for errors.
if self.check_error(content, 'failure', 'INVALID_DATA'):
raise self.CredentialsError(
self.response_message(content, 'ERROR'))
raise self.Failure(self.response_message(content, 'ERROR'),
'Unhandled failure')
# Extract token from content
if 'data' in content and 'token' in content['data']:
token = content['data']['token']
else:
raise self.AuthenticationError(response)
setattr(self, '_token', token)
return token | python | def token(self):
" Get token when needed."
if hasattr(self, '_token'):
return getattr(self, '_token')
# Json formatted auth.
data = json.dumps({'customer_name': self.customer,
'user_name': self.username,
'password': self.password})
# Start session.
response = requests.post(
'https://api2.dynect.net/REST/Session/', data=data,
headers={'Content-Type': 'application/json'})
# convert to data.
content = json.loads(response.content)
if response.status_code != 200:
# Check for errors.
if self.check_error(content, 'failure', 'INVALID_DATA'):
raise self.CredentialsError(
self.response_message(content, 'ERROR'))
raise self.Failure(self.response_message(content, 'ERROR'),
'Unhandled failure')
# Extract token from content
if 'data' in content and 'token' in content['data']:
token = content['data']['token']
else:
raise self.AuthenticationError(response)
setattr(self, '_token', token)
return token | [
"def",
"token",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'_token'",
")",
":",
"return",
"getattr",
"(",
"self",
",",
"'_token'",
")",
"# Json formatted auth.",
"data",
"=",
"json",
".",
"dumps",
"(",
"{",
"'customer_name'",
":",
"self",
".",
"customer",
",",
"'user_name'",
":",
"self",
".",
"username",
",",
"'password'",
":",
"self",
".",
"password",
"}",
")",
"# Start session.",
"response",
"=",
"requests",
".",
"post",
"(",
"'https://api2.dynect.net/REST/Session/'",
",",
"data",
"=",
"data",
",",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
")",
"# convert to data.",
"content",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"content",
")",
"if",
"response",
".",
"status_code",
"!=",
"200",
":",
"# Check for errors.",
"if",
"self",
".",
"check_error",
"(",
"content",
",",
"'failure'",
",",
"'INVALID_DATA'",
")",
":",
"raise",
"self",
".",
"CredentialsError",
"(",
"self",
".",
"response_message",
"(",
"content",
",",
"'ERROR'",
")",
")",
"raise",
"self",
".",
"Failure",
"(",
"self",
".",
"response_message",
"(",
"content",
",",
"'ERROR'",
")",
",",
"'Unhandled failure'",
")",
"# Extract token from content",
"if",
"'data'",
"in",
"content",
"and",
"'token'",
"in",
"content",
"[",
"'data'",
"]",
":",
"token",
"=",
"content",
"[",
"'data'",
"]",
"[",
"'token'",
"]",
"else",
":",
"raise",
"self",
".",
"AuthenticationError",
"(",
"response",
")",
"setattr",
"(",
"self",
",",
"'_token'",
",",
"token",
")",
"return",
"token"
] | Get token when needed. | [
"Get",
"token",
"when",
"needed",
"."
] | d2cd85bc510f00108a3a5bfe515f45daae15a482 | https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L27-L62 |
246,732 | jorgeecardona/dynect | dynect/__init__.py | DynectAuth.parse_error | def parse_error(self, response):
" Parse authentication errors."
# Check invalid credentials.
if self.check_error(response, 'failure', 'INVALID_DATA'):
raise self.CredentialsError(
self.response_message(response, 'ERROR')) | python | def parse_error(self, response):
" Parse authentication errors."
# Check invalid credentials.
if self.check_error(response, 'failure', 'INVALID_DATA'):
raise self.CredentialsError(
self.response_message(response, 'ERROR')) | [
"def",
"parse_error",
"(",
"self",
",",
"response",
")",
":",
"# Check invalid credentials.",
"if",
"self",
".",
"check_error",
"(",
"response",
",",
"'failure'",
",",
"'INVALID_DATA'",
")",
":",
"raise",
"self",
".",
"CredentialsError",
"(",
"self",
".",
"response_message",
"(",
"response",
",",
"'ERROR'",
")",
")"
] | Parse authentication errors. | [
"Parse",
"authentication",
"errors",
"."
] | d2cd85bc510f00108a3a5bfe515f45daae15a482 | https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L64-L70 |
246,733 | jorgeecardona/dynect | dynect/__init__.py | DynectAuth.check_error | def check_error(self, response, status, err_cd):
" Check an error in the response."
if 'status' not in response:
return False
if response['status'] != status:
return False
if 'msgs' not in response:
return False
if not isinstance(response['msgs'], list):
return False
for msg in response['msgs']:
if 'LVL' in msg and msg['LVL'] != 'ERROR':
continue
if 'ERR_CD' in msg and msg['ERR_CD'] == err_cd:
return True
return False | python | def check_error(self, response, status, err_cd):
" Check an error in the response."
if 'status' not in response:
return False
if response['status'] != status:
return False
if 'msgs' not in response:
return False
if not isinstance(response['msgs'], list):
return False
for msg in response['msgs']:
if 'LVL' in msg and msg['LVL'] != 'ERROR':
continue
if 'ERR_CD' in msg and msg['ERR_CD'] == err_cd:
return True
return False | [
"def",
"check_error",
"(",
"self",
",",
"response",
",",
"status",
",",
"err_cd",
")",
":",
"if",
"'status'",
"not",
"in",
"response",
":",
"return",
"False",
"if",
"response",
"[",
"'status'",
"]",
"!=",
"status",
":",
"return",
"False",
"if",
"'msgs'",
"not",
"in",
"response",
":",
"return",
"False",
"if",
"not",
"isinstance",
"(",
"response",
"[",
"'msgs'",
"]",
",",
"list",
")",
":",
"return",
"False",
"for",
"msg",
"in",
"response",
"[",
"'msgs'",
"]",
":",
"if",
"'LVL'",
"in",
"msg",
"and",
"msg",
"[",
"'LVL'",
"]",
"!=",
"'ERROR'",
":",
"continue",
"if",
"'ERR_CD'",
"in",
"msg",
"and",
"msg",
"[",
"'ERR_CD'",
"]",
"==",
"err_cd",
":",
"return",
"True",
"return",
"False"
] | Check an error in the response. | [
"Check",
"an",
"error",
"in",
"the",
"response",
"."
] | d2cd85bc510f00108a3a5bfe515f45daae15a482 | https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L72-L95 |
246,734 | jorgeecardona/dynect | dynect/__init__.py | Dynect.hook_response | def hook_response(self, response):
" Detect any failure."
# Decode content with json.
response._content = json.loads(response.content)
return response | python | def hook_response(self, response):
" Detect any failure."
# Decode content with json.
response._content = json.loads(response.content)
return response | [
"def",
"hook_response",
"(",
"self",
",",
"response",
")",
":",
"# Decode content with json.",
"response",
".",
"_content",
"=",
"json",
".",
"loads",
"(",
"response",
".",
"content",
")",
"return",
"response"
] | Detect any failure. | [
"Detect",
"any",
"failure",
"."
] | d2cd85bc510f00108a3a5bfe515f45daae15a482 | https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L173-L177 |
246,735 | jorgeecardona/dynect | dynect/__init__.py | Dynect.check_errors | def check_errors(self, response):
" Check some common errors."
# Read content.
content = response.content
if 'status' not in content:
raise self.GeneralError('We expect a status field.')
# Return the decoded content if status is success.
if content['status'] == 'success':
response._content = content
return
# Expect messages if some kind of error.
if 'msgs' not in content:
raise self.GeneralError('We expcet messages in case of error.')
try:
messages = list(content['msgs'])
except:
raise self.GeneralError("Messages must be a list.")
# Try to found common errors in the response.
for msg in messages:
if 'LVL' in msg and msg['LVL'] == 'ERROR':
# Check if is a not found error.
if msg['ERR_CD'] == 'NOT_FOUND':
raise self.NotFoundError(msg['INFO'])
# Duplicated target.
elif msg['ERR_CD'] == 'TARGET_EXISTS':
raise self.TargetExistsError(msg['INFO'])
# Some other error.
else:
raise self.DynectError(msg['INFO'])
raise self.GeneralError("We need at least one error message.") | python | def check_errors(self, response):
" Check some common errors."
# Read content.
content = response.content
if 'status' not in content:
raise self.GeneralError('We expect a status field.')
# Return the decoded content if status is success.
if content['status'] == 'success':
response._content = content
return
# Expect messages if some kind of error.
if 'msgs' not in content:
raise self.GeneralError('We expcet messages in case of error.')
try:
messages = list(content['msgs'])
except:
raise self.GeneralError("Messages must be a list.")
# Try to found common errors in the response.
for msg in messages:
if 'LVL' in msg and msg['LVL'] == 'ERROR':
# Check if is a not found error.
if msg['ERR_CD'] == 'NOT_FOUND':
raise self.NotFoundError(msg['INFO'])
# Duplicated target.
elif msg['ERR_CD'] == 'TARGET_EXISTS':
raise self.TargetExistsError(msg['INFO'])
# Some other error.
else:
raise self.DynectError(msg['INFO'])
raise self.GeneralError("We need at least one error message.") | [
"def",
"check_errors",
"(",
"self",
",",
"response",
")",
":",
"# Read content.",
"content",
"=",
"response",
".",
"content",
"if",
"'status'",
"not",
"in",
"content",
":",
"raise",
"self",
".",
"GeneralError",
"(",
"'We expect a status field.'",
")",
"# Return the decoded content if status is success.",
"if",
"content",
"[",
"'status'",
"]",
"==",
"'success'",
":",
"response",
".",
"_content",
"=",
"content",
"return",
"# Expect messages if some kind of error.",
"if",
"'msgs'",
"not",
"in",
"content",
":",
"raise",
"self",
".",
"GeneralError",
"(",
"'We expcet messages in case of error.'",
")",
"try",
":",
"messages",
"=",
"list",
"(",
"content",
"[",
"'msgs'",
"]",
")",
"except",
":",
"raise",
"self",
".",
"GeneralError",
"(",
"\"Messages must be a list.\"",
")",
"# Try to found common errors in the response.",
"for",
"msg",
"in",
"messages",
":",
"if",
"'LVL'",
"in",
"msg",
"and",
"msg",
"[",
"'LVL'",
"]",
"==",
"'ERROR'",
":",
"# Check if is a not found error.",
"if",
"msg",
"[",
"'ERR_CD'",
"]",
"==",
"'NOT_FOUND'",
":",
"raise",
"self",
".",
"NotFoundError",
"(",
"msg",
"[",
"'INFO'",
"]",
")",
"# Duplicated target.",
"elif",
"msg",
"[",
"'ERR_CD'",
"]",
"==",
"'TARGET_EXISTS'",
":",
"raise",
"self",
".",
"TargetExistsError",
"(",
"msg",
"[",
"'INFO'",
"]",
")",
"# Some other error.",
"else",
":",
"raise",
"self",
".",
"DynectError",
"(",
"msg",
"[",
"'INFO'",
"]",
")",
"raise",
"self",
".",
"GeneralError",
"(",
"\"We need at least one error message.\"",
")"
] | Check some common errors. | [
"Check",
"some",
"common",
"errors",
"."
] | d2cd85bc510f00108a3a5bfe515f45daae15a482 | https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L199-L239 |
246,736 | jorgeecardona/dynect | dynect/__init__.py | Dynect.add_address | def add_address(self, fqdn, address, ttl=0):
" Add a new address to a domain."
data = {'rdata': {'address': address}, 'ttl': str(ttl)}
# Make request.
response = self.post('/REST/ARecord/%s/%s' % (
self.zone, fqdn), data=data)
return Address(self, data=response.content['data']) | python | def add_address(self, fqdn, address, ttl=0):
" Add a new address to a domain."
data = {'rdata': {'address': address}, 'ttl': str(ttl)}
# Make request.
response = self.post('/REST/ARecord/%s/%s' % (
self.zone, fqdn), data=data)
return Address(self, data=response.content['data']) | [
"def",
"add_address",
"(",
"self",
",",
"fqdn",
",",
"address",
",",
"ttl",
"=",
"0",
")",
":",
"data",
"=",
"{",
"'rdata'",
":",
"{",
"'address'",
":",
"address",
"}",
",",
"'ttl'",
":",
"str",
"(",
"ttl",
")",
"}",
"# Make request.",
"response",
"=",
"self",
".",
"post",
"(",
"'/REST/ARecord/%s/%s'",
"%",
"(",
"self",
".",
"zone",
",",
"fqdn",
")",
",",
"data",
"=",
"data",
")",
"return",
"Address",
"(",
"self",
",",
"data",
"=",
"response",
".",
"content",
"[",
"'data'",
"]",
")"
] | Add a new address to a domain. | [
"Add",
"a",
"new",
"address",
"to",
"a",
"domain",
"."
] | d2cd85bc510f00108a3a5bfe515f45daae15a482 | https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L242-L251 |
246,737 | jorgeecardona/dynect | dynect/__init__.py | Dynect.publish | def publish(self):
" Publish last changes."
# Publish changes.
response = self.put('/REST/Zone/%s' % (
self.zone, ), data={'publish': True})
return response.content['data']['serial'] | python | def publish(self):
" Publish last changes."
# Publish changes.
response = self.put('/REST/Zone/%s' % (
self.zone, ), data={'publish': True})
return response.content['data']['serial'] | [
"def",
"publish",
"(",
"self",
")",
":",
"# Publish changes.",
"response",
"=",
"self",
".",
"put",
"(",
"'/REST/Zone/%s'",
"%",
"(",
"self",
".",
"zone",
",",
")",
",",
"data",
"=",
"{",
"'publish'",
":",
"True",
"}",
")",
"return",
"response",
".",
"content",
"[",
"'data'",
"]",
"[",
"'serial'",
"]"
] | Publish last changes. | [
"Publish",
"last",
"changes",
"."
] | d2cd85bc510f00108a3a5bfe515f45daae15a482 | https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L254-L261 |
246,738 | jorgeecardona/dynect | dynect/__init__.py | Dynect.list_address | def list_address(self, domain):
" Get the list of addresses of a single domain."
try:
response = self.get('/REST/ARecord/%s/%s' % (
self.zone, domain))
except self.NotFoundError:
return []
# Return a generator with the addresses.
addresses = response.content['data']
return [Address.from_url(self, uri) for uri in addresses] | python | def list_address(self, domain):
" Get the list of addresses of a single domain."
try:
response = self.get('/REST/ARecord/%s/%s' % (
self.zone, domain))
except self.NotFoundError:
return []
# Return a generator with the addresses.
addresses = response.content['data']
return [Address.from_url(self, uri) for uri in addresses] | [
"def",
"list_address",
"(",
"self",
",",
"domain",
")",
":",
"try",
":",
"response",
"=",
"self",
".",
"get",
"(",
"'/REST/ARecord/%s/%s'",
"%",
"(",
"self",
".",
"zone",
",",
"domain",
")",
")",
"except",
"self",
".",
"NotFoundError",
":",
"return",
"[",
"]",
"# Return a generator with the addresses.",
"addresses",
"=",
"response",
".",
"content",
"[",
"'data'",
"]",
"return",
"[",
"Address",
".",
"from_url",
"(",
"self",
",",
"uri",
")",
"for",
"uri",
"in",
"addresses",
"]"
] | Get the list of addresses of a single domain. | [
"Get",
"the",
"list",
"of",
"addresses",
"of",
"a",
"single",
"domain",
"."
] | d2cd85bc510f00108a3a5bfe515f45daae15a482 | https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L264-L275 |
246,739 | jorgeecardona/dynect | dynect/__init__.py | Dynect.remove_address | def remove_address(self, fqdn, address):
" Remove an address of a domain."
# Get a list of addresses.
for record in self.list_address(fqdn):
if record.address == address:
record.delete()
break | python | def remove_address(self, fqdn, address):
" Remove an address of a domain."
# Get a list of addresses.
for record in self.list_address(fqdn):
if record.address == address:
record.delete()
break | [
"def",
"remove_address",
"(",
"self",
",",
"fqdn",
",",
"address",
")",
":",
"# Get a list of addresses.",
"for",
"record",
"in",
"self",
".",
"list_address",
"(",
"fqdn",
")",
":",
"if",
"record",
".",
"address",
"==",
"address",
":",
"record",
".",
"delete",
"(",
")",
"break"
] | Remove an address of a domain. | [
"Remove",
"an",
"address",
"of",
"a",
"domain",
"."
] | d2cd85bc510f00108a3a5bfe515f45daae15a482 | https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L277-L284 |
246,740 | jorgeecardona/dynect | dynect/__init__.py | Node.delete | def delete(self):
" Delete the address."
response = self.dyn.delete(self.delete_url)
return response.content['job_id'] | python | def delete(self):
" Delete the address."
response = self.dyn.delete(self.delete_url)
return response.content['job_id'] | [
"def",
"delete",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"dyn",
".",
"delete",
"(",
"self",
".",
"delete_url",
")",
"return",
"response",
".",
"content",
"[",
"'job_id'",
"]"
] | Delete the address. | [
"Delete",
"the",
"address",
"."
] | d2cd85bc510f00108a3a5bfe515f45daae15a482 | https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L314-L317 |
246,741 | jorgeecardona/dynect | dynect/__init__.py | DynectRecord.delete | def delete(self):
" Delete the record."
response = self.dyn.delete(self.url)
return response.content['job_id'] | python | def delete(self):
" Delete the record."
response = self.dyn.delete(self.url)
return response.content['job_id'] | [
"def",
"delete",
"(",
"self",
")",
":",
"response",
"=",
"self",
".",
"dyn",
".",
"delete",
"(",
"self",
".",
"url",
")",
"return",
"response",
".",
"content",
"[",
"'job_id'",
"]"
] | Delete the record. | [
"Delete",
"the",
"record",
"."
] | d2cd85bc510f00108a3a5bfe515f45daae15a482 | https://github.com/jorgeecardona/dynect/blob/d2cd85bc510f00108a3a5bfe515f45daae15a482/dynect/__init__.py#L348-L352 |
246,742 | KnowledgeLinks/rdfframework | rdfframework/connections/connmanager.py | make_tstore_conn | def make_tstore_conn(params, **kwargs):
""" Returns a triplestore connection
args:
attr_name: The name the connection will be assigned in the
config manager
params: The paramaters of the connection
kwargs:
log_level: logging level to use
"""
log.setLevel(params.get('log_level', __LOG_LEVEL__))
log.debug("\n%s", params)
params.update(kwargs)
try:
vendor = RdfwConnections['triplestore'][params.get('vendor')]
except KeyError:
vendor = RdfwConnections['triplestore']['blazegraph']
conn = vendor(**params)
return conn | python | def make_tstore_conn(params, **kwargs):
""" Returns a triplestore connection
args:
attr_name: The name the connection will be assigned in the
config manager
params: The paramaters of the connection
kwargs:
log_level: logging level to use
"""
log.setLevel(params.get('log_level', __LOG_LEVEL__))
log.debug("\n%s", params)
params.update(kwargs)
try:
vendor = RdfwConnections['triplestore'][params.get('vendor')]
except KeyError:
vendor = RdfwConnections['triplestore']['blazegraph']
conn = vendor(**params)
return conn | [
"def",
"make_tstore_conn",
"(",
"params",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"setLevel",
"(",
"params",
".",
"get",
"(",
"'log_level'",
",",
"__LOG_LEVEL__",
")",
")",
"log",
".",
"debug",
"(",
"\"\\n%s\"",
",",
"params",
")",
"params",
".",
"update",
"(",
"kwargs",
")",
"try",
":",
"vendor",
"=",
"RdfwConnections",
"[",
"'triplestore'",
"]",
"[",
"params",
".",
"get",
"(",
"'vendor'",
")",
"]",
"except",
"KeyError",
":",
"vendor",
"=",
"RdfwConnections",
"[",
"'triplestore'",
"]",
"[",
"'blazegraph'",
"]",
"conn",
"=",
"vendor",
"(",
"*",
"*",
"params",
")",
"return",
"conn"
] | Returns a triplestore connection
args:
attr_name: The name the connection will be assigned in the
config manager
params: The paramaters of the connection
kwargs:
log_level: logging level to use | [
"Returns",
"a",
"triplestore",
"connection"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L264-L283 |
246,743 | KnowledgeLinks/rdfframework | rdfframework/connections/connmanager.py | ConnManager.set_conn | def set_conn(self, **kwargs):
""" takes a connection and creates the connection """
# log = logging.getLogger("%s.%s" % (self.log, inspect.stack()[0][3]))
log.setLevel(kwargs.get('log_level',self.log_level))
conn_name = kwargs.get("name")
if not conn_name:
raise NameError("a connection requires a 'name': %s" % kwargs)
elif self.conns.get(conn_name):
raise KeyError("connection '%s' has already been set" % conn_name)
if not kwargs.get("active", True):
log.warning("Connection '%s' is set as inactive" % conn_name)
return
conn_type = kwargs.get("conn_type")
if not conn_type or conn_type not in self.conn_mapping.nested:
err_msg = ["a connection requires a valid 'conn_type':\n",
"%s"]
raise NameError("".join(err_msg) % (list(self.conn_mapping.nested)))
log.info("Setting '%s' connection", conn_name)
if conn_type == "triplestore":
conn = make_tstore_conn(kwargs)
else:
conn = RdfwConnections[conn_type][kwargs['vendor']](**kwargs)
self.conns[conn_name] = conn
self.__is_initialized__ = True | python | def set_conn(self, **kwargs):
""" takes a connection and creates the connection """
# log = logging.getLogger("%s.%s" % (self.log, inspect.stack()[0][3]))
log.setLevel(kwargs.get('log_level',self.log_level))
conn_name = kwargs.get("name")
if not conn_name:
raise NameError("a connection requires a 'name': %s" % kwargs)
elif self.conns.get(conn_name):
raise KeyError("connection '%s' has already been set" % conn_name)
if not kwargs.get("active", True):
log.warning("Connection '%s' is set as inactive" % conn_name)
return
conn_type = kwargs.get("conn_type")
if not conn_type or conn_type not in self.conn_mapping.nested:
err_msg = ["a connection requires a valid 'conn_type':\n",
"%s"]
raise NameError("".join(err_msg) % (list(self.conn_mapping.nested)))
log.info("Setting '%s' connection", conn_name)
if conn_type == "triplestore":
conn = make_tstore_conn(kwargs)
else:
conn = RdfwConnections[conn_type][kwargs['vendor']](**kwargs)
self.conns[conn_name] = conn
self.__is_initialized__ = True | [
"def",
"set_conn",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# log = logging.getLogger(\"%s.%s\" % (self.log, inspect.stack()[0][3]))",
"log",
".",
"setLevel",
"(",
"kwargs",
".",
"get",
"(",
"'log_level'",
",",
"self",
".",
"log_level",
")",
")",
"conn_name",
"=",
"kwargs",
".",
"get",
"(",
"\"name\"",
")",
"if",
"not",
"conn_name",
":",
"raise",
"NameError",
"(",
"\"a connection requires a 'name': %s\"",
"%",
"kwargs",
")",
"elif",
"self",
".",
"conns",
".",
"get",
"(",
"conn_name",
")",
":",
"raise",
"KeyError",
"(",
"\"connection '%s' has already been set\"",
"%",
"conn_name",
")",
"if",
"not",
"kwargs",
".",
"get",
"(",
"\"active\"",
",",
"True",
")",
":",
"log",
".",
"warning",
"(",
"\"Connection '%s' is set as inactive\"",
"%",
"conn_name",
")",
"return",
"conn_type",
"=",
"kwargs",
".",
"get",
"(",
"\"conn_type\"",
")",
"if",
"not",
"conn_type",
"or",
"conn_type",
"not",
"in",
"self",
".",
"conn_mapping",
".",
"nested",
":",
"err_msg",
"=",
"[",
"\"a connection requires a valid 'conn_type':\\n\"",
",",
"\"%s\"",
"]",
"raise",
"NameError",
"(",
"\"\"",
".",
"join",
"(",
"err_msg",
")",
"%",
"(",
"list",
"(",
"self",
".",
"conn_mapping",
".",
"nested",
")",
")",
")",
"log",
".",
"info",
"(",
"\"Setting '%s' connection\"",
",",
"conn_name",
")",
"if",
"conn_type",
"==",
"\"triplestore\"",
":",
"conn",
"=",
"make_tstore_conn",
"(",
"kwargs",
")",
"else",
":",
"conn",
"=",
"RdfwConnections",
"[",
"conn_type",
"]",
"[",
"kwargs",
"[",
"'vendor'",
"]",
"]",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"conns",
"[",
"conn_name",
"]",
"=",
"conn",
"self",
".",
"__is_initialized__",
"=",
"True"
] | takes a connection and creates the connection | [
"takes",
"a",
"connection",
"and",
"creates",
"the",
"connection"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L106-L132 |
246,744 | KnowledgeLinks/rdfframework | rdfframework/connections/connmanager.py | ConnManager.get | def get(self, conn_name, default=None, **kwargs):
""" returns the specified connection
args:
conn_name: the name of the connection
"""
if isinstance(conn_name, RdfwConnections):
return conn_name
try:
return self.conns[conn_name]
except KeyError:
if default:
return self.get(default, **kwargs)
raise LookupError("'%s' connection has not been set" % conn_name) | python | def get(self, conn_name, default=None, **kwargs):
""" returns the specified connection
args:
conn_name: the name of the connection
"""
if isinstance(conn_name, RdfwConnections):
return conn_name
try:
return self.conns[conn_name]
except KeyError:
if default:
return self.get(default, **kwargs)
raise LookupError("'%s' connection has not been set" % conn_name) | [
"def",
"get",
"(",
"self",
",",
"conn_name",
",",
"default",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"conn_name",
",",
"RdfwConnections",
")",
":",
"return",
"conn_name",
"try",
":",
"return",
"self",
".",
"conns",
"[",
"conn_name",
"]",
"except",
"KeyError",
":",
"if",
"default",
":",
"return",
"self",
".",
"get",
"(",
"default",
",",
"*",
"*",
"kwargs",
")",
"raise",
"LookupError",
"(",
"\"'%s' connection has not been set\"",
"%",
"conn_name",
")"
] | returns the specified connection
args:
conn_name: the name of the connection | [
"returns",
"the",
"specified",
"connection"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L135-L149 |
246,745 | KnowledgeLinks/rdfframework | rdfframework/connections/connmanager.py | ConnManager.load | def load(self, conn_list, **kwargs):
""" Takes a list of connections and sets them in the manager
args:
conn_list: list of connection defitions
"""
for conn in conn_list:
conn['delay_check'] = kwargs.get('delay_check', False)
self.set_conn(**conn)
if kwargs.get('delay_check'):
test = self.wait_for_conns(**kwargs)
if not test:
log.critical("\n\nEXITING:Unable to establish connections \n"
"%s", test) | python | def load(self, conn_list, **kwargs):
""" Takes a list of connections and sets them in the manager
args:
conn_list: list of connection defitions
"""
for conn in conn_list:
conn['delay_check'] = kwargs.get('delay_check', False)
self.set_conn(**conn)
if kwargs.get('delay_check'):
test = self.wait_for_conns(**kwargs)
if not test:
log.critical("\n\nEXITING:Unable to establish connections \n"
"%s", test) | [
"def",
"load",
"(",
"self",
",",
"conn_list",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"conn",
"in",
"conn_list",
":",
"conn",
"[",
"'delay_check'",
"]",
"=",
"kwargs",
".",
"get",
"(",
"'delay_check'",
",",
"False",
")",
"self",
".",
"set_conn",
"(",
"*",
"*",
"conn",
")",
"if",
"kwargs",
".",
"get",
"(",
"'delay_check'",
")",
":",
"test",
"=",
"self",
".",
"wait_for_conns",
"(",
"*",
"*",
"kwargs",
")",
"if",
"not",
"test",
":",
"log",
".",
"critical",
"(",
"\"\\n\\nEXITING:Unable to establish connections \\n\"",
"\"%s\"",
",",
"test",
")"
] | Takes a list of connections and sets them in the manager
args:
conn_list: list of connection defitions | [
"Takes",
"a",
"list",
"of",
"connections",
"and",
"sets",
"them",
"in",
"the",
"manager"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L151-L164 |
246,746 | KnowledgeLinks/rdfframework | rdfframework/connections/connmanager.py | ConnManager.failing | def failing(self):
""" Tests to see if all connections are working
returns:
dictionary of all failing connections
"""
log_levels = {key: conn.log_level for key, conn in self.conns.items()
if hasattr(conn, 'log_level')}
for key in log_levels:
self.conns[key].log_level = logging.CRITICAL
failing_conns = {key: conn for key, conn in self.active.items()
if not conn.check_status}
for key, level in log_levels.items():
self.conns[key].log_level = level
return failing_conns | python | def failing(self):
""" Tests to see if all connections are working
returns:
dictionary of all failing connections
"""
log_levels = {key: conn.log_level for key, conn in self.conns.items()
if hasattr(conn, 'log_level')}
for key in log_levels:
self.conns[key].log_level = logging.CRITICAL
failing_conns = {key: conn for key, conn in self.active.items()
if not conn.check_status}
for key, level in log_levels.items():
self.conns[key].log_level = level
return failing_conns | [
"def",
"failing",
"(",
"self",
")",
":",
"log_levels",
"=",
"{",
"key",
":",
"conn",
".",
"log_level",
"for",
"key",
",",
"conn",
"in",
"self",
".",
"conns",
".",
"items",
"(",
")",
"if",
"hasattr",
"(",
"conn",
",",
"'log_level'",
")",
"}",
"for",
"key",
"in",
"log_levels",
":",
"self",
".",
"conns",
"[",
"key",
"]",
".",
"log_level",
"=",
"logging",
".",
"CRITICAL",
"failing_conns",
"=",
"{",
"key",
":",
"conn",
"for",
"key",
",",
"conn",
"in",
"self",
".",
"active",
".",
"items",
"(",
")",
"if",
"not",
"conn",
".",
"check_status",
"}",
"for",
"key",
",",
"level",
"in",
"log_levels",
".",
"items",
"(",
")",
":",
"self",
".",
"conns",
"[",
"key",
"]",
".",
"log_level",
"=",
"level",
"return",
"failing_conns"
] | Tests to see if all connections are working
returns:
dictionary of all failing connections | [
"Tests",
"to",
"see",
"if",
"all",
"connections",
"are",
"working"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L167-L181 |
246,747 | KnowledgeLinks/rdfframework | rdfframework/connections/connmanager.py | ConnManager.wait_for_conns | def wait_for_conns(self, timeout=60, start_delay=0, interval=5, **kwargs):
''' delays unitil all connections are working
args:
timeout: number of seconds to try to connecting. Error out when
timeout is reached
start_delay: number of seconds to wait before checking status
interval: number of seconds to wait between checks
'''
log.setLevel(kwargs.get('log_level',self.log_level))
timestamp = time.time()
last_check = time.time() + start_delay - interval
last_delay_notification = time.time() - interval
timeout += 1
failing = True
up_conns = {}
# loop until the server is up or the timeout is reached
while((time.time()-timestamp) < timeout) and failing:
# if delaying, the start of the check, print waiting to start
if start_delay > 0 and time.time() - timestamp < start_delay \
and (time.time()-last_delay_notification) > 5:
print("Delaying server status check until %ss. Current time: %ss" \
% (start_delay, int(time.time() - timestamp)))
last_delay_notification = time.time()
# check status at the specified 'interval' until the server is up
first_check = True
while ((time.time()-last_check) > interval) and failing:
msg = ["\tChecked status of servers at %ss" % \
int((time.time()-timestamp)),
"\t** CONNECTION STATUS:"]
last_check = time.time()
failing = self.failing
new_up = (self.active.keys() - failing.keys()) - \
up_conns.keys()
msg += ["\t\t UP - %s: %s" % (key, self.conns[key])
for key in new_up]
up_conns.update({key: self.conns[key] for key in new_up})
msg.append("\t*** '%s' connection(s) up" % len(up_conns))
msg += ["\t\t FAILING - %s: %s" % (key, self.conns[key])
for key in failing]
log.info("** CONNECTION STATUS:\n%s", "\n".join(msg))
if not failing:
log.info("**** Servers up at %ss" % \
int((time.time()-timestamp)))
break
if failing:
raise RuntimeError("Unable to establish connection(s): ",
failing)
for conn in up_conns.values():
conn.delay_check_pass()
return not failing | python | def wait_for_conns(self, timeout=60, start_delay=0, interval=5, **kwargs):
''' delays unitil all connections are working
args:
timeout: number of seconds to try to connecting. Error out when
timeout is reached
start_delay: number of seconds to wait before checking status
interval: number of seconds to wait between checks
'''
log.setLevel(kwargs.get('log_level',self.log_level))
timestamp = time.time()
last_check = time.time() + start_delay - interval
last_delay_notification = time.time() - interval
timeout += 1
failing = True
up_conns = {}
# loop until the server is up or the timeout is reached
while((time.time()-timestamp) < timeout) and failing:
# if delaying, the start of the check, print waiting to start
if start_delay > 0 and time.time() - timestamp < start_delay \
and (time.time()-last_delay_notification) > 5:
print("Delaying server status check until %ss. Current time: %ss" \
% (start_delay, int(time.time() - timestamp)))
last_delay_notification = time.time()
# check status at the specified 'interval' until the server is up
first_check = True
while ((time.time()-last_check) > interval) and failing:
msg = ["\tChecked status of servers at %ss" % \
int((time.time()-timestamp)),
"\t** CONNECTION STATUS:"]
last_check = time.time()
failing = self.failing
new_up = (self.active.keys() - failing.keys()) - \
up_conns.keys()
msg += ["\t\t UP - %s: %s" % (key, self.conns[key])
for key in new_up]
up_conns.update({key: self.conns[key] for key in new_up})
msg.append("\t*** '%s' connection(s) up" % len(up_conns))
msg += ["\t\t FAILING - %s: %s" % (key, self.conns[key])
for key in failing]
log.info("** CONNECTION STATUS:\n%s", "\n".join(msg))
if not failing:
log.info("**** Servers up at %ss" % \
int((time.time()-timestamp)))
break
if failing:
raise RuntimeError("Unable to establish connection(s): ",
failing)
for conn in up_conns.values():
conn.delay_check_pass()
return not failing | [
"def",
"wait_for_conns",
"(",
"self",
",",
"timeout",
"=",
"60",
",",
"start_delay",
"=",
"0",
",",
"interval",
"=",
"5",
",",
"*",
"*",
"kwargs",
")",
":",
"log",
".",
"setLevel",
"(",
"kwargs",
".",
"get",
"(",
"'log_level'",
",",
"self",
".",
"log_level",
")",
")",
"timestamp",
"=",
"time",
".",
"time",
"(",
")",
"last_check",
"=",
"time",
".",
"time",
"(",
")",
"+",
"start_delay",
"-",
"interval",
"last_delay_notification",
"=",
"time",
".",
"time",
"(",
")",
"-",
"interval",
"timeout",
"+=",
"1",
"failing",
"=",
"True",
"up_conns",
"=",
"{",
"}",
"# loop until the server is up or the timeout is reached",
"while",
"(",
"(",
"time",
".",
"time",
"(",
")",
"-",
"timestamp",
")",
"<",
"timeout",
")",
"and",
"failing",
":",
"# if delaying, the start of the check, print waiting to start",
"if",
"start_delay",
">",
"0",
"and",
"time",
".",
"time",
"(",
")",
"-",
"timestamp",
"<",
"start_delay",
"and",
"(",
"time",
".",
"time",
"(",
")",
"-",
"last_delay_notification",
")",
">",
"5",
":",
"print",
"(",
"\"Delaying server status check until %ss. Current time: %ss\"",
"%",
"(",
"start_delay",
",",
"int",
"(",
"time",
".",
"time",
"(",
")",
"-",
"timestamp",
")",
")",
")",
"last_delay_notification",
"=",
"time",
".",
"time",
"(",
")",
"# check status at the specified 'interval' until the server is up",
"first_check",
"=",
"True",
"while",
"(",
"(",
"time",
".",
"time",
"(",
")",
"-",
"last_check",
")",
">",
"interval",
")",
"and",
"failing",
":",
"msg",
"=",
"[",
"\"\\tChecked status of servers at %ss\"",
"%",
"int",
"(",
"(",
"time",
".",
"time",
"(",
")",
"-",
"timestamp",
")",
")",
",",
"\"\\t** CONNECTION STATUS:\"",
"]",
"last_check",
"=",
"time",
".",
"time",
"(",
")",
"failing",
"=",
"self",
".",
"failing",
"new_up",
"=",
"(",
"self",
".",
"active",
".",
"keys",
"(",
")",
"-",
"failing",
".",
"keys",
"(",
")",
")",
"-",
"up_conns",
".",
"keys",
"(",
")",
"msg",
"+=",
"[",
"\"\\t\\t UP - %s: %s\"",
"%",
"(",
"key",
",",
"self",
".",
"conns",
"[",
"key",
"]",
")",
"for",
"key",
"in",
"new_up",
"]",
"up_conns",
".",
"update",
"(",
"{",
"key",
":",
"self",
".",
"conns",
"[",
"key",
"]",
"for",
"key",
"in",
"new_up",
"}",
")",
"msg",
".",
"append",
"(",
"\"\\t*** '%s' connection(s) up\"",
"%",
"len",
"(",
"up_conns",
")",
")",
"msg",
"+=",
"[",
"\"\\t\\t FAILING - %s: %s\"",
"%",
"(",
"key",
",",
"self",
".",
"conns",
"[",
"key",
"]",
")",
"for",
"key",
"in",
"failing",
"]",
"log",
".",
"info",
"(",
"\"** CONNECTION STATUS:\\n%s\"",
",",
"\"\\n\"",
".",
"join",
"(",
"msg",
")",
")",
"if",
"not",
"failing",
":",
"log",
".",
"info",
"(",
"\"**** Servers up at %ss\"",
"%",
"int",
"(",
"(",
"time",
".",
"time",
"(",
")",
"-",
"timestamp",
")",
")",
")",
"break",
"if",
"failing",
":",
"raise",
"RuntimeError",
"(",
"\"Unable to establish connection(s): \"",
",",
"failing",
")",
"for",
"conn",
"in",
"up_conns",
".",
"values",
"(",
")",
":",
"conn",
".",
"delay_check_pass",
"(",
")",
"return",
"not",
"failing"
] | delays unitil all connections are working
args:
timeout: number of seconds to try to connecting. Error out when
timeout is reached
start_delay: number of seconds to wait before checking status
interval: number of seconds to wait between checks | [
"delays",
"unitil",
"all",
"connections",
"are",
"working"
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L183-L233 |
246,748 | KnowledgeLinks/rdfframework | rdfframework/connections/connmanager.py | ConnManager.active | def active(self):
""" returns a dictionary of connections set as active.
"""
return {key: value for key, value in self.conns.items()
if value.active} | python | def active(self):
""" returns a dictionary of connections set as active.
"""
return {key: value for key, value in self.conns.items()
if value.active} | [
"def",
"active",
"(",
"self",
")",
":",
"return",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"self",
".",
"conns",
".",
"items",
"(",
")",
"if",
"value",
".",
"active",
"}"
] | returns a dictionary of connections set as active. | [
"returns",
"a",
"dictionary",
"of",
"connections",
"set",
"as",
"active",
"."
] | 9ec32dcc4bed51650a4b392cc5c15100fef7923a | https://github.com/KnowledgeLinks/rdfframework/blob/9ec32dcc4bed51650a4b392cc5c15100fef7923a/rdfframework/connections/connmanager.py#L258-L262 |
246,749 | UT-ET/offer | offer/offerCLI.py | main | def main():
"""Host a file."""
description = """Host a file on the LAN."""
argParser = _argparse.ArgumentParser(description=description)
argParser.add_argument('file',
help='File to host')
argParser.add_argument('-p', '--port',
help='Port to use. (default: 80/8000)',
type=int, default=0)
args = argParser.parse_args()
absFilePath = _path.abspath(_path.expandvars(_path.expanduser(args.file)))
if not _path.isfile(absFilePath):
_sys.stdout.write(u"Couldn't find/access file: " + args.file + "\n")
_sys.exit(-1)
tryDefaultPorts = args.port == 0
# Code from http.server in Python3
handler = FileHTTPServerHandler
handler.protocol_version = "HTTP/1.0"
handler.absFilePath = absFilePath
port = 80 if tryDefaultPorts else args.port
try:
server_address = ("", port)
httpd = _B.HTTPServer(server_address, handler)
except IOError as e:
# If it is a permission denied error, and we had been ambitiously
# trying port, 80, let's try port 8000 instead
if e.errno == 13 and tryDefaultPorts:
port = 8000
server_address = ("", port)
httpd = _B.HTTPServer(server_address, handler)
else:
raise
sa = httpd.socket.getsockname()
_sys.stderr.write("Serving file {} on {}:{} ...\n"
.format(absFilePath, sa[0], sa[1]))
possibleIps = getValidIPs()
if len(possibleIps) == 0:
_sys.stderr.write(u'No IPs for localhost found. ' +
u'Are you connected to LAN?\n')
else:
_sys.stderr.write(u'Download the file by pointing the browser ' +
u'on the remote machine to:\n')
portStr = '' if port == 80 else ':' + str(port)
for ip in possibleIps:
_sys.stderr.write(u'\t' + ip + portStr + '\n')
_sys.stderr.write('Press Ctrl-C to stop hosting.\n')
try:
httpd.serve_forever()
except KeyboardInterrupt:
_sys.stderr.write("\nKeyboard interrupt received, exiting.\n")
httpd.server_close()
_sys.exit(0) | python | def main():
"""Host a file."""
description = """Host a file on the LAN."""
argParser = _argparse.ArgumentParser(description=description)
argParser.add_argument('file',
help='File to host')
argParser.add_argument('-p', '--port',
help='Port to use. (default: 80/8000)',
type=int, default=0)
args = argParser.parse_args()
absFilePath = _path.abspath(_path.expandvars(_path.expanduser(args.file)))
if not _path.isfile(absFilePath):
_sys.stdout.write(u"Couldn't find/access file: " + args.file + "\n")
_sys.exit(-1)
tryDefaultPorts = args.port == 0
# Code from http.server in Python3
handler = FileHTTPServerHandler
handler.protocol_version = "HTTP/1.0"
handler.absFilePath = absFilePath
port = 80 if tryDefaultPorts else args.port
try:
server_address = ("", port)
httpd = _B.HTTPServer(server_address, handler)
except IOError as e:
# If it is a permission denied error, and we had been ambitiously
# trying port, 80, let's try port 8000 instead
if e.errno == 13 and tryDefaultPorts:
port = 8000
server_address = ("", port)
httpd = _B.HTTPServer(server_address, handler)
else:
raise
sa = httpd.socket.getsockname()
_sys.stderr.write("Serving file {} on {}:{} ...\n"
.format(absFilePath, sa[0], sa[1]))
possibleIps = getValidIPs()
if len(possibleIps) == 0:
_sys.stderr.write(u'No IPs for localhost found. ' +
u'Are you connected to LAN?\n')
else:
_sys.stderr.write(u'Download the file by pointing the browser ' +
u'on the remote machine to:\n')
portStr = '' if port == 80 else ':' + str(port)
for ip in possibleIps:
_sys.stderr.write(u'\t' + ip + portStr + '\n')
_sys.stderr.write('Press Ctrl-C to stop hosting.\n')
try:
httpd.serve_forever()
except KeyboardInterrupt:
_sys.stderr.write("\nKeyboard interrupt received, exiting.\n")
httpd.server_close()
_sys.exit(0) | [
"def",
"main",
"(",
")",
":",
"description",
"=",
"\"\"\"Host a file on the LAN.\"\"\"",
"argParser",
"=",
"_argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"description",
")",
"argParser",
".",
"add_argument",
"(",
"'file'",
",",
"help",
"=",
"'File to host'",
")",
"argParser",
".",
"add_argument",
"(",
"'-p'",
",",
"'--port'",
",",
"help",
"=",
"'Port to use. (default: 80/8000)'",
",",
"type",
"=",
"int",
",",
"default",
"=",
"0",
")",
"args",
"=",
"argParser",
".",
"parse_args",
"(",
")",
"absFilePath",
"=",
"_path",
".",
"abspath",
"(",
"_path",
".",
"expandvars",
"(",
"_path",
".",
"expanduser",
"(",
"args",
".",
"file",
")",
")",
")",
"if",
"not",
"_path",
".",
"isfile",
"(",
"absFilePath",
")",
":",
"_sys",
".",
"stdout",
".",
"write",
"(",
"u\"Couldn't find/access file: \"",
"+",
"args",
".",
"file",
"+",
"\"\\n\"",
")",
"_sys",
".",
"exit",
"(",
"-",
"1",
")",
"tryDefaultPorts",
"=",
"args",
".",
"port",
"==",
"0",
"# Code from http.server in Python3",
"handler",
"=",
"FileHTTPServerHandler",
"handler",
".",
"protocol_version",
"=",
"\"HTTP/1.0\"",
"handler",
".",
"absFilePath",
"=",
"absFilePath",
"port",
"=",
"80",
"if",
"tryDefaultPorts",
"else",
"args",
".",
"port",
"try",
":",
"server_address",
"=",
"(",
"\"\"",
",",
"port",
")",
"httpd",
"=",
"_B",
".",
"HTTPServer",
"(",
"server_address",
",",
"handler",
")",
"except",
"IOError",
"as",
"e",
":",
"# If it is a permission denied error, and we had been ambitiously",
"# trying port, 80, let's try port 8000 instead",
"if",
"e",
".",
"errno",
"==",
"13",
"and",
"tryDefaultPorts",
":",
"port",
"=",
"8000",
"server_address",
"=",
"(",
"\"\"",
",",
"port",
")",
"httpd",
"=",
"_B",
".",
"HTTPServer",
"(",
"server_address",
",",
"handler",
")",
"else",
":",
"raise",
"sa",
"=",
"httpd",
".",
"socket",
".",
"getsockname",
"(",
")",
"_sys",
".",
"stderr",
".",
"write",
"(",
"\"Serving file {} on {}:{} ...\\n\"",
".",
"format",
"(",
"absFilePath",
",",
"sa",
"[",
"0",
"]",
",",
"sa",
"[",
"1",
"]",
")",
")",
"possibleIps",
"=",
"getValidIPs",
"(",
")",
"if",
"len",
"(",
"possibleIps",
")",
"==",
"0",
":",
"_sys",
".",
"stderr",
".",
"write",
"(",
"u'No IPs for localhost found. '",
"+",
"u'Are you connected to LAN?\\n'",
")",
"else",
":",
"_sys",
".",
"stderr",
".",
"write",
"(",
"u'Download the file by pointing the browser '",
"+",
"u'on the remote machine to:\\n'",
")",
"portStr",
"=",
"''",
"if",
"port",
"==",
"80",
"else",
"':'",
"+",
"str",
"(",
"port",
")",
"for",
"ip",
"in",
"possibleIps",
":",
"_sys",
".",
"stderr",
".",
"write",
"(",
"u'\\t'",
"+",
"ip",
"+",
"portStr",
"+",
"'\\n'",
")",
"_sys",
".",
"stderr",
".",
"write",
"(",
"'Press Ctrl-C to stop hosting.\\n'",
")",
"try",
":",
"httpd",
".",
"serve_forever",
"(",
")",
"except",
"KeyboardInterrupt",
":",
"_sys",
".",
"stderr",
".",
"write",
"(",
"\"\\nKeyboard interrupt received, exiting.\\n\"",
")",
"httpd",
".",
"server_close",
"(",
")",
"_sys",
".",
"exit",
"(",
"0",
")"
] | Host a file. | [
"Host",
"a",
"file",
"."
] | 8dee15337b60999040feb3529333b871fb5e258f | https://github.com/UT-ET/offer/blob/8dee15337b60999040feb3529333b871fb5e258f/offer/offerCLI.py#L88-L151 |
246,750 | daknuett/py_register_machine2 | machines/small.py | small_register_machine | def small_register_machine(rom_size = 50, ram_size = 200, flash_size = 500):
"""
An unprogrammend Register Machine with
* one OutputRegister to ``sys.stdout`` (``out0``)
* 15 General Purpose Register (``r0 - r14``)
returns : ``(Processor, ROM, RAM, Flash)``
"""
rom = memory.ROM(rom_size)
ram = memory.RAM(ram_size)
flash = device.Flash(flash_size)
proc = processor.Processor()
proc.register_memory_device(rom)
proc.register_memory_device(ram)
proc.register_device(flash)
registers = [register.OutputRegister("out0", sys.stdout),
register.Register("r0"),
register.Register("r1"),
register.Register("r2"),
register.Register("r3"),
register.Register("r4"),
register.Register("r5"),
register.Register("r6"),
register.Register("r7"),
register.Register("r8"),
register.Register("r9"),
register.Register("r10"),
register.Register("r11"),
register.Register("r12"),
register.Register("r13"),
register.Register("r14")]
for r in registers:
proc.add_register(r)
for command in basic_commands:
proc.register_command(command)
return (proc, rom, ram, flash) | python | def small_register_machine(rom_size = 50, ram_size = 200, flash_size = 500):
"""
An unprogrammend Register Machine with
* one OutputRegister to ``sys.stdout`` (``out0``)
* 15 General Purpose Register (``r0 - r14``)
returns : ``(Processor, ROM, RAM, Flash)``
"""
rom = memory.ROM(rom_size)
ram = memory.RAM(ram_size)
flash = device.Flash(flash_size)
proc = processor.Processor()
proc.register_memory_device(rom)
proc.register_memory_device(ram)
proc.register_device(flash)
registers = [register.OutputRegister("out0", sys.stdout),
register.Register("r0"),
register.Register("r1"),
register.Register("r2"),
register.Register("r3"),
register.Register("r4"),
register.Register("r5"),
register.Register("r6"),
register.Register("r7"),
register.Register("r8"),
register.Register("r9"),
register.Register("r10"),
register.Register("r11"),
register.Register("r12"),
register.Register("r13"),
register.Register("r14")]
for r in registers:
proc.add_register(r)
for command in basic_commands:
proc.register_command(command)
return (proc, rom, ram, flash) | [
"def",
"small_register_machine",
"(",
"rom_size",
"=",
"50",
",",
"ram_size",
"=",
"200",
",",
"flash_size",
"=",
"500",
")",
":",
"rom",
"=",
"memory",
".",
"ROM",
"(",
"rom_size",
")",
"ram",
"=",
"memory",
".",
"RAM",
"(",
"ram_size",
")",
"flash",
"=",
"device",
".",
"Flash",
"(",
"flash_size",
")",
"proc",
"=",
"processor",
".",
"Processor",
"(",
")",
"proc",
".",
"register_memory_device",
"(",
"rom",
")",
"proc",
".",
"register_memory_device",
"(",
"ram",
")",
"proc",
".",
"register_device",
"(",
"flash",
")",
"registers",
"=",
"[",
"register",
".",
"OutputRegister",
"(",
"\"out0\"",
",",
"sys",
".",
"stdout",
")",
",",
"register",
".",
"Register",
"(",
"\"r0\"",
")",
",",
"register",
".",
"Register",
"(",
"\"r1\"",
")",
",",
"register",
".",
"Register",
"(",
"\"r2\"",
")",
",",
"register",
".",
"Register",
"(",
"\"r3\"",
")",
",",
"register",
".",
"Register",
"(",
"\"r4\"",
")",
",",
"register",
".",
"Register",
"(",
"\"r5\"",
")",
",",
"register",
".",
"Register",
"(",
"\"r6\"",
")",
",",
"register",
".",
"Register",
"(",
"\"r7\"",
")",
",",
"register",
".",
"Register",
"(",
"\"r8\"",
")",
",",
"register",
".",
"Register",
"(",
"\"r9\"",
")",
",",
"register",
".",
"Register",
"(",
"\"r10\"",
")",
",",
"register",
".",
"Register",
"(",
"\"r11\"",
")",
",",
"register",
".",
"Register",
"(",
"\"r12\"",
")",
",",
"register",
".",
"Register",
"(",
"\"r13\"",
")",
",",
"register",
".",
"Register",
"(",
"\"r14\"",
")",
"]",
"for",
"r",
"in",
"registers",
":",
"proc",
".",
"add_register",
"(",
"r",
")",
"for",
"command",
"in",
"basic_commands",
":",
"proc",
".",
"register_command",
"(",
"command",
")",
"return",
"(",
"proc",
",",
"rom",
",",
"ram",
",",
"flash",
")"
] | An unprogrammend Register Machine with
* one OutputRegister to ``sys.stdout`` (``out0``)
* 15 General Purpose Register (``r0 - r14``)
returns : ``(Processor, ROM, RAM, Flash)`` | [
"An",
"unprogrammend",
"Register",
"Machine",
"with"
] | 599c53cd7576297d0d7a53344ed5d9aa98acc751 | https://github.com/daknuett/py_register_machine2/blob/599c53cd7576297d0d7a53344ed5d9aa98acc751/machines/small.py#L12-L54 |
246,751 | svasilev94/GraphLibrary | graphlibrary/digraph.py | DiGraph.add_edge | def add_edge(self, u, v, **attr):
"""
Add an edge from u to v and update edge attributes
"""
if u not in self.vertices:
self.vertices[u] = []
self.pred[u] = []
self.succ[u] = []
if v not in self.vertices:
self.vertices[v] = []
self.pred[v] = []
self.succ[v] = []
vertex = (u, v)
self.edges[vertex] = {}
self.edges[vertex].update(attr)
self.vertices[u].append(v)
self.pred[v].append(u)
self.succ[u].append(v) | python | def add_edge(self, u, v, **attr):
"""
Add an edge from u to v and update edge attributes
"""
if u not in self.vertices:
self.vertices[u] = []
self.pred[u] = []
self.succ[u] = []
if v not in self.vertices:
self.vertices[v] = []
self.pred[v] = []
self.succ[v] = []
vertex = (u, v)
self.edges[vertex] = {}
self.edges[vertex].update(attr)
self.vertices[u].append(v)
self.pred[v].append(u)
self.succ[u].append(v) | [
"def",
"add_edge",
"(",
"self",
",",
"u",
",",
"v",
",",
"*",
"*",
"attr",
")",
":",
"if",
"u",
"not",
"in",
"self",
".",
"vertices",
":",
"self",
".",
"vertices",
"[",
"u",
"]",
"=",
"[",
"]",
"self",
".",
"pred",
"[",
"u",
"]",
"=",
"[",
"]",
"self",
".",
"succ",
"[",
"u",
"]",
"=",
"[",
"]",
"if",
"v",
"not",
"in",
"self",
".",
"vertices",
":",
"self",
".",
"vertices",
"[",
"v",
"]",
"=",
"[",
"]",
"self",
".",
"pred",
"[",
"v",
"]",
"=",
"[",
"]",
"self",
".",
"succ",
"[",
"v",
"]",
"=",
"[",
"]",
"vertex",
"=",
"(",
"u",
",",
"v",
")",
"self",
".",
"edges",
"[",
"vertex",
"]",
"=",
"{",
"}",
"self",
".",
"edges",
"[",
"vertex",
"]",
".",
"update",
"(",
"attr",
")",
"self",
".",
"vertices",
"[",
"u",
"]",
".",
"append",
"(",
"v",
")",
"self",
".",
"pred",
"[",
"v",
"]",
".",
"append",
"(",
"u",
")",
"self",
".",
"succ",
"[",
"u",
"]",
".",
"append",
"(",
"v",
")"
] | Add an edge from u to v and update edge attributes | [
"Add",
"an",
"edge",
"from",
"u",
"to",
"v",
"and",
"update",
"edge",
"attributes"
] | bf979a80bdea17eeb25955f0c119ca8f711ef62b | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/digraph.py#L35-L52 |
246,752 | svasilev94/GraphLibrary | graphlibrary/digraph.py | DiGraph.has_successor | def has_successor(self, u, v):
"""
Check if vertex u has successor v
"""
if u not in self.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (u,))
return (u in self.succ and v in self.succ[u]) | python | def has_successor(self, u, v):
"""
Check if vertex u has successor v
"""
if u not in self.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (u,))
return (u in self.succ and v in self.succ[u]) | [
"def",
"has_successor",
"(",
"self",
",",
"u",
",",
"v",
")",
":",
"if",
"u",
"not",
"in",
"self",
".",
"vertices",
":",
"raise",
"GraphInsertError",
"(",
"\"Vertex %s doesn't exist.\"",
"%",
"(",
"u",
",",
")",
")",
"return",
"(",
"u",
"in",
"self",
".",
"succ",
"and",
"v",
"in",
"self",
".",
"succ",
"[",
"u",
"]",
")"
] | Check if vertex u has successor v | [
"Check",
"if",
"vertex",
"u",
"has",
"successor",
"v"
] | bf979a80bdea17eeb25955f0c119ca8f711ef62b | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/digraph.py#L99-L105 |
246,753 | svasilev94/GraphLibrary | graphlibrary/digraph.py | DiGraph.has_predecessor | def has_predecessor(self, u, v):
"""
Check if vertex u has predecessor v
"""
if u not in self.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (u,))
return(u in self.pred and v in self.pred[u]) | python | def has_predecessor(self, u, v):
"""
Check if vertex u has predecessor v
"""
if u not in self.vertices:
raise GraphInsertError("Vertex %s doesn't exist." % (u,))
return(u in self.pred and v in self.pred[u]) | [
"def",
"has_predecessor",
"(",
"self",
",",
"u",
",",
"v",
")",
":",
"if",
"u",
"not",
"in",
"self",
".",
"vertices",
":",
"raise",
"GraphInsertError",
"(",
"\"Vertex %s doesn't exist.\"",
"%",
"(",
"u",
",",
")",
")",
"return",
"(",
"u",
"in",
"self",
".",
"pred",
"and",
"v",
"in",
"self",
".",
"pred",
"[",
"u",
"]",
")"
] | Check if vertex u has predecessor v | [
"Check",
"if",
"vertex",
"u",
"has",
"predecessor",
"v"
] | bf979a80bdea17eeb25955f0c119ca8f711ef62b | https://github.com/svasilev94/GraphLibrary/blob/bf979a80bdea17eeb25955f0c119ca8f711ef62b/graphlibrary/digraph.py#L107-L113 |
246,754 | nickmilon/Hellas | Hellas/Thebes.py | format_header | def format_header(frmt, return_len=False):
"""creates a header string from a new style format string useful when printing dictionaries
:param str frmt: a new style format string
:returns: a table header string
assumptions for frmt specs:
- all have a separator = '|' and include a key size format directive i.e.: '{key:size}'
- no other character allowed in frmt except separator
:Example:
>>> frmt = '|{count:12,d}|{percent:7.2f}|{depth:5d}|'
>>> data_dict = {'count': 100, 'percent': 10.5, 'depth': 10}
>>> print(format_header(frmt)); print(frmt.format(**data_dict))
............................
| count |percent|depth|
............................
| 100| 10.50| 10|
"""
names = re.sub("{(.*?):.*?}", r"\1", frmt)
names = [i for i in names.split("|") if i]
frmt_clean = re.sub("\.\df", r"", frmt) # get read of floats i.e {:8.2f}
sizes = re.findall(r':(\d+)', frmt_clean)
frmt_header = "|{{:^{}}}" * len(sizes) + "|"
header_frmt = frmt_header.format(*sizes)
header = header_frmt.format(*names)
header_len = len(header)
header = "{}\n{}\n{}\n".format("." * header_len, header, "." * header_len)
return header.strip() if return_len is False else (header.strip(), header_len) | python | def format_header(frmt, return_len=False):
"""creates a header string from a new style format string useful when printing dictionaries
:param str frmt: a new style format string
:returns: a table header string
assumptions for frmt specs:
- all have a separator = '|' and include a key size format directive i.e.: '{key:size}'
- no other character allowed in frmt except separator
:Example:
>>> frmt = '|{count:12,d}|{percent:7.2f}|{depth:5d}|'
>>> data_dict = {'count': 100, 'percent': 10.5, 'depth': 10}
>>> print(format_header(frmt)); print(frmt.format(**data_dict))
............................
| count |percent|depth|
............................
| 100| 10.50| 10|
"""
names = re.sub("{(.*?):.*?}", r"\1", frmt)
names = [i for i in names.split("|") if i]
frmt_clean = re.sub("\.\df", r"", frmt) # get read of floats i.e {:8.2f}
sizes = re.findall(r':(\d+)', frmt_clean)
frmt_header = "|{{:^{}}}" * len(sizes) + "|"
header_frmt = frmt_header.format(*sizes)
header = header_frmt.format(*names)
header_len = len(header)
header = "{}\n{}\n{}\n".format("." * header_len, header, "." * header_len)
return header.strip() if return_len is False else (header.strip(), header_len) | [
"def",
"format_header",
"(",
"frmt",
",",
"return_len",
"=",
"False",
")",
":",
"names",
"=",
"re",
".",
"sub",
"(",
"\"{(.*?):.*?}\"",
",",
"r\"\\1\"",
",",
"frmt",
")",
"names",
"=",
"[",
"i",
"for",
"i",
"in",
"names",
".",
"split",
"(",
"\"|\"",
")",
"if",
"i",
"]",
"frmt_clean",
"=",
"re",
".",
"sub",
"(",
"\"\\.\\df\"",
",",
"r\"\"",
",",
"frmt",
")",
"# get read of floats i.e {:8.2f}",
"sizes",
"=",
"re",
".",
"findall",
"(",
"r':(\\d+)'",
",",
"frmt_clean",
")",
"frmt_header",
"=",
"\"|{{:^{}}}\"",
"*",
"len",
"(",
"sizes",
")",
"+",
"\"|\"",
"header_frmt",
"=",
"frmt_header",
".",
"format",
"(",
"*",
"sizes",
")",
"header",
"=",
"header_frmt",
".",
"format",
"(",
"*",
"names",
")",
"header_len",
"=",
"len",
"(",
"header",
")",
"header",
"=",
"\"{}\\n{}\\n{}\\n\"",
".",
"format",
"(",
"\".\"",
"*",
"header_len",
",",
"header",
",",
"\".\"",
"*",
"header_len",
")",
"return",
"header",
".",
"strip",
"(",
")",
"if",
"return_len",
"is",
"False",
"else",
"(",
"header",
".",
"strip",
"(",
")",
",",
"header_len",
")"
] | creates a header string from a new style format string useful when printing dictionaries
:param str frmt: a new style format string
:returns: a table header string
assumptions for frmt specs:
- all have a separator = '|' and include a key size format directive i.e.: '{key:size}'
- no other character allowed in frmt except separator
:Example:
>>> frmt = '|{count:12,d}|{percent:7.2f}|{depth:5d}|'
>>> data_dict = {'count': 100, 'percent': 10.5, 'depth': 10}
>>> print(format_header(frmt)); print(frmt.format(**data_dict))
............................
| count |percent|depth|
............................
| 100| 10.50| 10| | [
"creates",
"a",
"header",
"string",
"from",
"a",
"new",
"style",
"format",
"string",
"useful",
"when",
"printing",
"dictionaries"
] | 542e4778692fbec90753942946f20100412ec9ee | https://github.com/nickmilon/Hellas/blob/542e4778692fbec90753942946f20100412ec9ee/Hellas/Thebes.py#L11-L40 |
246,755 | Tinche/django-bower-cache | registry/admin.py | ClonedRepoAdmin.save_form | def save_form(self, request, form, change):
"""Here we pluck out the data to create a new cloned repo.
Form is an instance of NewRepoForm.
"""
name = form.cleaned_data['name']
origin_url = form.cleaned_data['origin_url']
res = ClonedRepo(name=name, origin=origin_url)
LOG.info("New repo form produced %s" % str(res))
form.save(commit=False)
return res | python | def save_form(self, request, form, change):
"""Here we pluck out the data to create a new cloned repo.
Form is an instance of NewRepoForm.
"""
name = form.cleaned_data['name']
origin_url = form.cleaned_data['origin_url']
res = ClonedRepo(name=name, origin=origin_url)
LOG.info("New repo form produced %s" % str(res))
form.save(commit=False)
return res | [
"def",
"save_form",
"(",
"self",
",",
"request",
",",
"form",
",",
"change",
")",
":",
"name",
"=",
"form",
".",
"cleaned_data",
"[",
"'name'",
"]",
"origin_url",
"=",
"form",
".",
"cleaned_data",
"[",
"'origin_url'",
"]",
"res",
"=",
"ClonedRepo",
"(",
"name",
"=",
"name",
",",
"origin",
"=",
"origin_url",
")",
"LOG",
".",
"info",
"(",
"\"New repo form produced %s\"",
"%",
"str",
"(",
"res",
")",
")",
"form",
".",
"save",
"(",
"commit",
"=",
"False",
")",
"return",
"res"
] | Here we pluck out the data to create a new cloned repo.
Form is an instance of NewRepoForm. | [
"Here",
"we",
"pluck",
"out",
"the",
"data",
"to",
"create",
"a",
"new",
"cloned",
"repo",
"."
] | 5245b2ee80c33c09d85ce0bf8f047825d9df2118 | https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/admin.py#L65-L76 |
246,756 | Tinche/django-bower-cache | registry/admin.py | ClonedRepoAdmin.add_view | def add_view(self, request, **kwargs):
"""A custom add_view, to catch exceptions from 'save_model'.
Just to be clear, this is very filthy.
"""
try:
return super(ClonedRepoAdmin, self).add_view(request, **kwargs)
except ValidationError:
# Rerender the form, having messaged the user.
return redirect(request.path) | python | def add_view(self, request, **kwargs):
"""A custom add_view, to catch exceptions from 'save_model'.
Just to be clear, this is very filthy.
"""
try:
return super(ClonedRepoAdmin, self).add_view(request, **kwargs)
except ValidationError:
# Rerender the form, having messaged the user.
return redirect(request.path) | [
"def",
"add_view",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"super",
"(",
"ClonedRepoAdmin",
",",
"self",
")",
".",
"add_view",
"(",
"request",
",",
"*",
"*",
"kwargs",
")",
"except",
"ValidationError",
":",
"# Rerender the form, having messaged the user.",
"return",
"redirect",
"(",
"request",
".",
"path",
")"
] | A custom add_view, to catch exceptions from 'save_model'.
Just to be clear, this is very filthy. | [
"A",
"custom",
"add_view",
"to",
"catch",
"exceptions",
"from",
"save_model",
"."
] | 5245b2ee80c33c09d85ce0bf8f047825d9df2118 | https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/admin.py#L82-L91 |
246,757 | Tinche/django-bower-cache | registry/admin.py | ClonedRepoAdmin.git_pull_view | def git_pull_view(self, request, repo_name):
"""Perform a git pull and redirect back to the repo."""
LOG.info("Pull requested for %s." % repo_name)
repo = get_object_or_404(self.model, name=repo_name)
repo.pull()
self.message_user(request, "Repo %s successfully updated." % repo_name,
level=messages.SUCCESS)
return redirect('admin:registry_clonedrepo_change', repo_name) | python | def git_pull_view(self, request, repo_name):
"""Perform a git pull and redirect back to the repo."""
LOG.info("Pull requested for %s." % repo_name)
repo = get_object_or_404(self.model, name=repo_name)
repo.pull()
self.message_user(request, "Repo %s successfully updated." % repo_name,
level=messages.SUCCESS)
return redirect('admin:registry_clonedrepo_change', repo_name) | [
"def",
"git_pull_view",
"(",
"self",
",",
"request",
",",
"repo_name",
")",
":",
"LOG",
".",
"info",
"(",
"\"Pull requested for %s.\"",
"%",
"repo_name",
")",
"repo",
"=",
"get_object_or_404",
"(",
"self",
".",
"model",
",",
"name",
"=",
"repo_name",
")",
"repo",
".",
"pull",
"(",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"\"Repo %s successfully updated.\"",
"%",
"repo_name",
",",
"level",
"=",
"messages",
".",
"SUCCESS",
")",
"return",
"redirect",
"(",
"'admin:registry_clonedrepo_change'",
",",
"repo_name",
")"
] | Perform a git pull and redirect back to the repo. | [
"Perform",
"a",
"git",
"pull",
"and",
"redirect",
"back",
"to",
"the",
"repo",
"."
] | 5245b2ee80c33c09d85ce0bf8f047825d9df2118 | https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/admin.py#L102-L109 |
246,758 | Tinche/django-bower-cache | registry/admin.py | ClonedRepoAdmin.update_all_view | def update_all_view(self, request):
"""Update all repositories and redirect back to the repo list."""
LOG.info("Total update requested.")
total_count = errors = 0
for repo in self.model.objects.all():
total_count += 1
try:
repo.pull()
except:
LOG.exception('While updating %s.' % repo)
errors += 1
msg = "{0} repos successfully updated, {1} failed.".format(total_count,
errors)
self.message_user(request, msg, level=messages.SUCCESS)
return redirect('admin:registry_clonedrepo_changelist') | python | def update_all_view(self, request):
"""Update all repositories and redirect back to the repo list."""
LOG.info("Total update requested.")
total_count = errors = 0
for repo in self.model.objects.all():
total_count += 1
try:
repo.pull()
except:
LOG.exception('While updating %s.' % repo)
errors += 1
msg = "{0} repos successfully updated, {1} failed.".format(total_count,
errors)
self.message_user(request, msg, level=messages.SUCCESS)
return redirect('admin:registry_clonedrepo_changelist') | [
"def",
"update_all_view",
"(",
"self",
",",
"request",
")",
":",
"LOG",
".",
"info",
"(",
"\"Total update requested.\"",
")",
"total_count",
"=",
"errors",
"=",
"0",
"for",
"repo",
"in",
"self",
".",
"model",
".",
"objects",
".",
"all",
"(",
")",
":",
"total_count",
"+=",
"1",
"try",
":",
"repo",
".",
"pull",
"(",
")",
"except",
":",
"LOG",
".",
"exception",
"(",
"'While updating %s.'",
"%",
"repo",
")",
"errors",
"+=",
"1",
"msg",
"=",
"\"{0} repos successfully updated, {1} failed.\"",
".",
"format",
"(",
"total_count",
",",
"errors",
")",
"self",
".",
"message_user",
"(",
"request",
",",
"msg",
",",
"level",
"=",
"messages",
".",
"SUCCESS",
")",
"return",
"redirect",
"(",
"'admin:registry_clonedrepo_changelist'",
")"
] | Update all repositories and redirect back to the repo list. | [
"Update",
"all",
"repositories",
"and",
"redirect",
"back",
"to",
"the",
"repo",
"list",
"."
] | 5245b2ee80c33c09d85ce0bf8f047825d9df2118 | https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/admin.py#L111-L125 |
246,759 | Tinche/django-bower-cache | registry/admin.py | NewRepoForm.clean | def clean(self):
"""Validate the new repo form.
Might perform a request to upstream Bower."""
cleaned_data = super(NewRepoForm, self).clean()
origin_url = cleaned_data['origin_url']
origin_source = cleaned_data['origin_source']
if origin_source == 'origin_url' and not origin_url:
msg = 'Please provide an origin URL.'
self._errors['origin_url'] = self.error_class([msg])
del cleaned_data['origin_url']
del cleaned_data['origin_source']
elif origin_source == 'upstream':
upstream = settings.UPSTREAM_BOWER_REGISTRY
name = cleaned_data['name']
try:
upstream_pkg = bowerlib.get_package(upstream, name)
except IOError as exc:
msg = str(exc)
self._errors['origin_source'] = self.error_class([msg])
else:
if not upstream_pkg:
msg = 'Upstream registry has no knowledge of %s.' % name
self._errors['name'] = self.error_class([msg])
del cleaned_data['name']
else:
upstream_origin_url = upstream_pkg['url']
cleaned_data['origin_url'] = upstream_origin_url
return cleaned_data | python | def clean(self):
"""Validate the new repo form.
Might perform a request to upstream Bower."""
cleaned_data = super(NewRepoForm, self).clean()
origin_url = cleaned_data['origin_url']
origin_source = cleaned_data['origin_source']
if origin_source == 'origin_url' and not origin_url:
msg = 'Please provide an origin URL.'
self._errors['origin_url'] = self.error_class([msg])
del cleaned_data['origin_url']
del cleaned_data['origin_source']
elif origin_source == 'upstream':
upstream = settings.UPSTREAM_BOWER_REGISTRY
name = cleaned_data['name']
try:
upstream_pkg = bowerlib.get_package(upstream, name)
except IOError as exc:
msg = str(exc)
self._errors['origin_source'] = self.error_class([msg])
else:
if not upstream_pkg:
msg = 'Upstream registry has no knowledge of %s.' % name
self._errors['name'] = self.error_class([msg])
del cleaned_data['name']
else:
upstream_origin_url = upstream_pkg['url']
cleaned_data['origin_url'] = upstream_origin_url
return cleaned_data | [
"def",
"clean",
"(",
"self",
")",
":",
"cleaned_data",
"=",
"super",
"(",
"NewRepoForm",
",",
"self",
")",
".",
"clean",
"(",
")",
"origin_url",
"=",
"cleaned_data",
"[",
"'origin_url'",
"]",
"origin_source",
"=",
"cleaned_data",
"[",
"'origin_source'",
"]",
"if",
"origin_source",
"==",
"'origin_url'",
"and",
"not",
"origin_url",
":",
"msg",
"=",
"'Please provide an origin URL.'",
"self",
".",
"_errors",
"[",
"'origin_url'",
"]",
"=",
"self",
".",
"error_class",
"(",
"[",
"msg",
"]",
")",
"del",
"cleaned_data",
"[",
"'origin_url'",
"]",
"del",
"cleaned_data",
"[",
"'origin_source'",
"]",
"elif",
"origin_source",
"==",
"'upstream'",
":",
"upstream",
"=",
"settings",
".",
"UPSTREAM_BOWER_REGISTRY",
"name",
"=",
"cleaned_data",
"[",
"'name'",
"]",
"try",
":",
"upstream_pkg",
"=",
"bowerlib",
".",
"get_package",
"(",
"upstream",
",",
"name",
")",
"except",
"IOError",
"as",
"exc",
":",
"msg",
"=",
"str",
"(",
"exc",
")",
"self",
".",
"_errors",
"[",
"'origin_source'",
"]",
"=",
"self",
".",
"error_class",
"(",
"[",
"msg",
"]",
")",
"else",
":",
"if",
"not",
"upstream_pkg",
":",
"msg",
"=",
"'Upstream registry has no knowledge of %s.'",
"%",
"name",
"self",
".",
"_errors",
"[",
"'name'",
"]",
"=",
"self",
".",
"error_class",
"(",
"[",
"msg",
"]",
")",
"del",
"cleaned_data",
"[",
"'name'",
"]",
"else",
":",
"upstream_origin_url",
"=",
"upstream_pkg",
"[",
"'url'",
"]",
"cleaned_data",
"[",
"'origin_url'",
"]",
"=",
"upstream_origin_url",
"return",
"cleaned_data"
] | Validate the new repo form.
Might perform a request to upstream Bower. | [
"Validate",
"the",
"new",
"repo",
"form",
"."
] | 5245b2ee80c33c09d85ce0bf8f047825d9df2118 | https://github.com/Tinche/django-bower-cache/blob/5245b2ee80c33c09d85ce0bf8f047825d9df2118/registry/admin.py#L137-L168 |
246,760 | s-ball/i18nparse | i18nparse/i18nparse.py | activate | def activate(lang=None):
"""Activate a translation for lang.
If lang is None, then the language of locale.getdefaultlocale() is used.
If the translation file does not exist, the original messages will be used.
"""
if lang is None:
lang = locale.getlocale()[0]
tr = gettext.translation("argparse", os.path.join(locpath, "locale"),
[lang], fallback=True)
argparse._ = tr.gettext
argparse.ngettext = tr.ngettext | python | def activate(lang=None):
"""Activate a translation for lang.
If lang is None, then the language of locale.getdefaultlocale() is used.
If the translation file does not exist, the original messages will be used.
"""
if lang is None:
lang = locale.getlocale()[0]
tr = gettext.translation("argparse", os.path.join(locpath, "locale"),
[lang], fallback=True)
argparse._ = tr.gettext
argparse.ngettext = tr.ngettext | [
"def",
"activate",
"(",
"lang",
"=",
"None",
")",
":",
"if",
"lang",
"is",
"None",
":",
"lang",
"=",
"locale",
".",
"getlocale",
"(",
")",
"[",
"0",
"]",
"tr",
"=",
"gettext",
".",
"translation",
"(",
"\"argparse\"",
",",
"os",
".",
"path",
".",
"join",
"(",
"locpath",
",",
"\"locale\"",
")",
",",
"[",
"lang",
"]",
",",
"fallback",
"=",
"True",
")",
"argparse",
".",
"_",
"=",
"tr",
".",
"gettext",
"argparse",
".",
"ngettext",
"=",
"tr",
".",
"ngettext"
] | Activate a translation for lang.
If lang is None, then the language of locale.getdefaultlocale() is used.
If the translation file does not exist, the original messages will be used. | [
"Activate",
"a",
"translation",
"for",
"lang",
"."
] | cc70cbf31903caf45ebfdcb62a57744b6fe9d0df | https://github.com/s-ball/i18nparse/blob/cc70cbf31903caf45ebfdcb62a57744b6fe9d0df/i18nparse/i18nparse.py#L11-L22 |
246,761 | geertj/looping | lib/looping/pyside.py | PySideEventLoop.run | def run(self):
"""Run until there are no more events.
This only looks at events scheduled through the event loop.
"""
self._stop = False
while not self._stop:
have_sources = self._timers or self._readers or self._writers
if not self._processor.pending and not have_sources:
break
events = QEventLoop.AllEvents
if not self._processor.pending:
events |= QEventLoop.WaitForMoreEvents
self._qapp.processEvents(events)
if self._processor.pending:
self._processor.run() | python | def run(self):
"""Run until there are no more events.
This only looks at events scheduled through the event loop.
"""
self._stop = False
while not self._stop:
have_sources = self._timers or self._readers or self._writers
if not self._processor.pending and not have_sources:
break
events = QEventLoop.AllEvents
if not self._processor.pending:
events |= QEventLoop.WaitForMoreEvents
self._qapp.processEvents(events)
if self._processor.pending:
self._processor.run() | [
"def",
"run",
"(",
"self",
")",
":",
"self",
".",
"_stop",
"=",
"False",
"while",
"not",
"self",
".",
"_stop",
":",
"have_sources",
"=",
"self",
".",
"_timers",
"or",
"self",
".",
"_readers",
"or",
"self",
".",
"_writers",
"if",
"not",
"self",
".",
"_processor",
".",
"pending",
"and",
"not",
"have_sources",
":",
"break",
"events",
"=",
"QEventLoop",
".",
"AllEvents",
"if",
"not",
"self",
".",
"_processor",
".",
"pending",
":",
"events",
"|=",
"QEventLoop",
".",
"WaitForMoreEvents",
"self",
".",
"_qapp",
".",
"processEvents",
"(",
"events",
")",
"if",
"self",
".",
"_processor",
".",
"pending",
":",
"self",
".",
"_processor",
".",
"run",
"(",
")"
] | Run until there are no more events.
This only looks at events scheduled through the event loop. | [
"Run",
"until",
"there",
"are",
"no",
"more",
"events",
".",
"This",
"only",
"looks",
"at",
"events",
"scheduled",
"through",
"the",
"event",
"loop",
"."
] | b60303714685aede18b37c0d80f8f55175ad7a65 | https://github.com/geertj/looping/blob/b60303714685aede18b37c0d80f8f55175ad7a65/lib/looping/pyside.py#L97-L111 |
246,762 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/structures.py | Author.to_namedtuple | def to_namedtuple(self):
"""
Convert class to namedtuple.
Note:
This method is neccessary for AMQP communication.
Returns:
namedtuple: Representation of the class as simple structure.
"""
keys = filter(lambda x: not x.startswith("_"), self.__dict__)
opt_nt = namedtuple(self.__class__.__name__, keys)
filtered_dict = dict(map(lambda x: (x, self.__dict__[x]), keys))
return opt_nt(**filtered_dict) | python | def to_namedtuple(self):
"""
Convert class to namedtuple.
Note:
This method is neccessary for AMQP communication.
Returns:
namedtuple: Representation of the class as simple structure.
"""
keys = filter(lambda x: not x.startswith("_"), self.__dict__)
opt_nt = namedtuple(self.__class__.__name__, keys)
filtered_dict = dict(map(lambda x: (x, self.__dict__[x]), keys))
return opt_nt(**filtered_dict) | [
"def",
"to_namedtuple",
"(",
"self",
")",
":",
"keys",
"=",
"filter",
"(",
"lambda",
"x",
":",
"not",
"x",
".",
"startswith",
"(",
"\"_\"",
")",
",",
"self",
".",
"__dict__",
")",
"opt_nt",
"=",
"namedtuple",
"(",
"self",
".",
"__class__",
".",
"__name__",
",",
"keys",
")",
"filtered_dict",
"=",
"dict",
"(",
"map",
"(",
"lambda",
"x",
":",
"(",
"x",
",",
"self",
".",
"__dict__",
"[",
"x",
"]",
")",
",",
"keys",
")",
")",
"return",
"opt_nt",
"(",
"*",
"*",
"filtered_dict",
")"
] | Convert class to namedtuple.
Note:
This method is neccessary for AMQP communication.
Returns:
namedtuple: Representation of the class as simple structure. | [
"Convert",
"class",
"to",
"namedtuple",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/structures.py#L26-L40 |
246,763 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/structures.py | Publication._get_hash | def _get_hash(self):
"""
Create hash of the class.
Hash should be unique for given ebook, so ISBN is main component of the
hash if provided.
Returns:
str: Hash.
"""
if self.optionals and self.optionals.ISBN:
isbn = self.optionals.ISBN.replace("-", "")
if len(isbn) <= 10:
return "97880" + isbn
return isbn
if self.optionals and self.optionals.EAN:
return self.optionals.EAN
return self.title + ",".join(map(lambda x: x.name, self.authors)) | python | def _get_hash(self):
"""
Create hash of the class.
Hash should be unique for given ebook, so ISBN is main component of the
hash if provided.
Returns:
str: Hash.
"""
if self.optionals and self.optionals.ISBN:
isbn = self.optionals.ISBN.replace("-", "")
if len(isbn) <= 10:
return "97880" + isbn
return isbn
if self.optionals and self.optionals.EAN:
return self.optionals.EAN
return self.title + ",".join(map(lambda x: x.name, self.authors)) | [
"def",
"_get_hash",
"(",
"self",
")",
":",
"if",
"self",
".",
"optionals",
"and",
"self",
".",
"optionals",
".",
"ISBN",
":",
"isbn",
"=",
"self",
".",
"optionals",
".",
"ISBN",
".",
"replace",
"(",
"\"-\"",
",",
"\"\"",
")",
"if",
"len",
"(",
"isbn",
")",
"<=",
"10",
":",
"return",
"\"97880\"",
"+",
"isbn",
"return",
"isbn",
"if",
"self",
".",
"optionals",
"and",
"self",
".",
"optionals",
".",
"EAN",
":",
"return",
"self",
".",
"optionals",
".",
"EAN",
"return",
"self",
".",
"title",
"+",
"\",\"",
".",
"join",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"name",
",",
"self",
".",
"authors",
")",
")"
] | Create hash of the class.
Hash should be unique for given ebook, so ISBN is main component of the
hash if provided.
Returns:
str: Hash. | [
"Create",
"hash",
"of",
"the",
"class",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/structures.py#L178-L199 |
246,764 | kmedian/luriegold | luriegold/luriegold_func.py | luriegold | def luriegold(R):
"""Lurie-Goldberg Algorithm to adjust a correlation
matrix to be semipositive definite
Philip M. Lurie and Matthew S. Goldberg (1998), An Approximate Method
for Sampling Correlated Random Variables from Partially-Specified
Distributions, Management Science, Vol 44, No. 2, February 1998, pp
203-218, URL: http://www.jstor.org/stable/2634496
"""
# subfunctions
def xtotril(x, idx, mat):
"""Create 'L' lower triangular matrix."""
mat[idx] = x
return mat
def xtocorr(x, idx, mat):
L = xtotril(x, idx, mat)
C = np.dot(L, L.T)
return C, L
def objectivefunc(x, R, idx, mat):
C, _ = xtocorr(x, idx, mat)
f = np.sum((R - C)**2)
return f
def nlcon_diagone(x, idx, mat):
C, _ = xtocorr(x, idx, mat)
return np.diag(C) - 1
# dimension of the correlation matrix
d = R.shape[0]
n = int((d**2 + d) / 2.)
# other arguments
mat = np.zeros((d, d)) # the lower triangular matrix without values
idx = np.tril(np.ones((d, d)), k=0) > 0 # boolean matrix
# idx = np.tril_indices(d,k=0); #row/col ids (same result)
# start values of the optimization are Ones
x0 = np.ones(shape=(n, )) / n
# for each of the k factors, the sum of its d absolute params
# values has to be less than 1
condiag = {'type': 'eq', 'args': (idx, mat), 'fun': nlcon_diagone}
# optimization
algorithm = 'SLSQP'
opt = {'disp': False}
# run the optimization
results = scipy.optimize.minimize(
objectivefunc, x0,
args=(R, idx, mat),
constraints=[condiag],
method=algorithm,
options=opt)
# Compute Correlation Matrix
C, L = xtocorr(results.x, idx, mat)
# done
return C, L, results | python | def luriegold(R):
"""Lurie-Goldberg Algorithm to adjust a correlation
matrix to be semipositive definite
Philip M. Lurie and Matthew S. Goldberg (1998), An Approximate Method
for Sampling Correlated Random Variables from Partially-Specified
Distributions, Management Science, Vol 44, No. 2, February 1998, pp
203-218, URL: http://www.jstor.org/stable/2634496
"""
# subfunctions
def xtotril(x, idx, mat):
"""Create 'L' lower triangular matrix."""
mat[idx] = x
return mat
def xtocorr(x, idx, mat):
L = xtotril(x, idx, mat)
C = np.dot(L, L.T)
return C, L
def objectivefunc(x, R, idx, mat):
C, _ = xtocorr(x, idx, mat)
f = np.sum((R - C)**2)
return f
def nlcon_diagone(x, idx, mat):
C, _ = xtocorr(x, idx, mat)
return np.diag(C) - 1
# dimension of the correlation matrix
d = R.shape[0]
n = int((d**2 + d) / 2.)
# other arguments
mat = np.zeros((d, d)) # the lower triangular matrix without values
idx = np.tril(np.ones((d, d)), k=0) > 0 # boolean matrix
# idx = np.tril_indices(d,k=0); #row/col ids (same result)
# start values of the optimization are Ones
x0 = np.ones(shape=(n, )) / n
# for each of the k factors, the sum of its d absolute params
# values has to be less than 1
condiag = {'type': 'eq', 'args': (idx, mat), 'fun': nlcon_diagone}
# optimization
algorithm = 'SLSQP'
opt = {'disp': False}
# run the optimization
results = scipy.optimize.minimize(
objectivefunc, x0,
args=(R, idx, mat),
constraints=[condiag],
method=algorithm,
options=opt)
# Compute Correlation Matrix
C, L = xtocorr(results.x, idx, mat)
# done
return C, L, results | [
"def",
"luriegold",
"(",
"R",
")",
":",
"# subfunctions",
"def",
"xtotril",
"(",
"x",
",",
"idx",
",",
"mat",
")",
":",
"\"\"\"Create 'L' lower triangular matrix.\"\"\"",
"mat",
"[",
"idx",
"]",
"=",
"x",
"return",
"mat",
"def",
"xtocorr",
"(",
"x",
",",
"idx",
",",
"mat",
")",
":",
"L",
"=",
"xtotril",
"(",
"x",
",",
"idx",
",",
"mat",
")",
"C",
"=",
"np",
".",
"dot",
"(",
"L",
",",
"L",
".",
"T",
")",
"return",
"C",
",",
"L",
"def",
"objectivefunc",
"(",
"x",
",",
"R",
",",
"idx",
",",
"mat",
")",
":",
"C",
",",
"_",
"=",
"xtocorr",
"(",
"x",
",",
"idx",
",",
"mat",
")",
"f",
"=",
"np",
".",
"sum",
"(",
"(",
"R",
"-",
"C",
")",
"**",
"2",
")",
"return",
"f",
"def",
"nlcon_diagone",
"(",
"x",
",",
"idx",
",",
"mat",
")",
":",
"C",
",",
"_",
"=",
"xtocorr",
"(",
"x",
",",
"idx",
",",
"mat",
")",
"return",
"np",
".",
"diag",
"(",
"C",
")",
"-",
"1",
"# dimension of the correlation matrix",
"d",
"=",
"R",
".",
"shape",
"[",
"0",
"]",
"n",
"=",
"int",
"(",
"(",
"d",
"**",
"2",
"+",
"d",
")",
"/",
"2.",
")",
"# other arguments",
"mat",
"=",
"np",
".",
"zeros",
"(",
"(",
"d",
",",
"d",
")",
")",
"# the lower triangular matrix without values",
"idx",
"=",
"np",
".",
"tril",
"(",
"np",
".",
"ones",
"(",
"(",
"d",
",",
"d",
")",
")",
",",
"k",
"=",
"0",
")",
">",
"0",
"# boolean matrix",
"# idx = np.tril_indices(d,k=0); #row/col ids (same result)",
"# start values of the optimization are Ones",
"x0",
"=",
"np",
".",
"ones",
"(",
"shape",
"=",
"(",
"n",
",",
")",
")",
"/",
"n",
"# for each of the k factors, the sum of its d absolute params",
"# values has to be less than 1",
"condiag",
"=",
"{",
"'type'",
":",
"'eq'",
",",
"'args'",
":",
"(",
"idx",
",",
"mat",
")",
",",
"'fun'",
":",
"nlcon_diagone",
"}",
"# optimization",
"algorithm",
"=",
"'SLSQP'",
"opt",
"=",
"{",
"'disp'",
":",
"False",
"}",
"# run the optimization",
"results",
"=",
"scipy",
".",
"optimize",
".",
"minimize",
"(",
"objectivefunc",
",",
"x0",
",",
"args",
"=",
"(",
"R",
",",
"idx",
",",
"mat",
")",
",",
"constraints",
"=",
"[",
"condiag",
"]",
",",
"method",
"=",
"algorithm",
",",
"options",
"=",
"opt",
")",
"# Compute Correlation Matrix",
"C",
",",
"L",
"=",
"xtocorr",
"(",
"results",
".",
"x",
",",
"idx",
",",
"mat",
")",
"# done",
"return",
"C",
",",
"L",
",",
"results"
] | Lurie-Goldberg Algorithm to adjust a correlation
matrix to be semipositive definite
Philip M. Lurie and Matthew S. Goldberg (1998), An Approximate Method
for Sampling Correlated Random Variables from Partially-Specified
Distributions, Management Science, Vol 44, No. 2, February 1998, pp
203-218, URL: http://www.jstor.org/stable/2634496 | [
"Lurie",
"-",
"Goldberg",
"Algorithm",
"to",
"adjust",
"a",
"correlation",
"matrix",
"to",
"be",
"semipositive",
"definite"
] | 9aa77fb3f7277e44973b472cc81aa15bbe171414 | https://github.com/kmedian/luriegold/blob/9aa77fb3f7277e44973b472cc81aa15bbe171414/luriegold/luriegold_func.py#L6-L68 |
246,765 | calvinku96/labreporthelper | labreporthelper/manage.py | generate_datasets_list | def generate_datasets_list(settings, argv):
"""
generate datasets list to activate
args:
settings: dictionary
from settings file
argv: list
from sys.argv
"""
datasets_string_list = settings["DATASETS_LIST"]
datasets_list = []
if len(argv) == 2:
try:
datasets_items = datasets_string_list.iteritems()
except AttributeError:
datasets_items = datasets_string_list.items()
for key, val in datasets_items:
key_module = importlib.import_module(
settings["PYTHON_MODULE"] + "." + key
)
for element in val:
datasets_list.append(
(key, element, getattr(key_module, element)())
)
elif len(argv) > 2:
arguments = argv[2:]
for argument in arguments:
argument_list = argument.split(".")
key = ".".join(argument_list[:-1])
key_module = importlib.import_module(
settings["PYTHON_MODULE"] + "." + key
)
datasets_list.append(
(key, argument_list[-1],
getattr(key_module, argument_list[-1])())
)
else:
print_help()
return datasets_list | python | def generate_datasets_list(settings, argv):
"""
generate datasets list to activate
args:
settings: dictionary
from settings file
argv: list
from sys.argv
"""
datasets_string_list = settings["DATASETS_LIST"]
datasets_list = []
if len(argv) == 2:
try:
datasets_items = datasets_string_list.iteritems()
except AttributeError:
datasets_items = datasets_string_list.items()
for key, val in datasets_items:
key_module = importlib.import_module(
settings["PYTHON_MODULE"] + "." + key
)
for element in val:
datasets_list.append(
(key, element, getattr(key_module, element)())
)
elif len(argv) > 2:
arguments = argv[2:]
for argument in arguments:
argument_list = argument.split(".")
key = ".".join(argument_list[:-1])
key_module = importlib.import_module(
settings["PYTHON_MODULE"] + "." + key
)
datasets_list.append(
(key, argument_list[-1],
getattr(key_module, argument_list[-1])())
)
else:
print_help()
return datasets_list | [
"def",
"generate_datasets_list",
"(",
"settings",
",",
"argv",
")",
":",
"datasets_string_list",
"=",
"settings",
"[",
"\"DATASETS_LIST\"",
"]",
"datasets_list",
"=",
"[",
"]",
"if",
"len",
"(",
"argv",
")",
"==",
"2",
":",
"try",
":",
"datasets_items",
"=",
"datasets_string_list",
".",
"iteritems",
"(",
")",
"except",
"AttributeError",
":",
"datasets_items",
"=",
"datasets_string_list",
".",
"items",
"(",
")",
"for",
"key",
",",
"val",
"in",
"datasets_items",
":",
"key_module",
"=",
"importlib",
".",
"import_module",
"(",
"settings",
"[",
"\"PYTHON_MODULE\"",
"]",
"+",
"\".\"",
"+",
"key",
")",
"for",
"element",
"in",
"val",
":",
"datasets_list",
".",
"append",
"(",
"(",
"key",
",",
"element",
",",
"getattr",
"(",
"key_module",
",",
"element",
")",
"(",
")",
")",
")",
"elif",
"len",
"(",
"argv",
")",
">",
"2",
":",
"arguments",
"=",
"argv",
"[",
"2",
":",
"]",
"for",
"argument",
"in",
"arguments",
":",
"argument_list",
"=",
"argument",
".",
"split",
"(",
"\".\"",
")",
"key",
"=",
"\".\"",
".",
"join",
"(",
"argument_list",
"[",
":",
"-",
"1",
"]",
")",
"key_module",
"=",
"importlib",
".",
"import_module",
"(",
"settings",
"[",
"\"PYTHON_MODULE\"",
"]",
"+",
"\".\"",
"+",
"key",
")",
"datasets_list",
".",
"append",
"(",
"(",
"key",
",",
"argument_list",
"[",
"-",
"1",
"]",
",",
"getattr",
"(",
"key_module",
",",
"argument_list",
"[",
"-",
"1",
"]",
")",
"(",
")",
")",
")",
"else",
":",
"print_help",
"(",
")",
"return",
"datasets_list"
] | generate datasets list to activate
args:
settings: dictionary
from settings file
argv: list
from sys.argv | [
"generate",
"datasets",
"list",
"to",
"activate"
] | 4d436241f389c02eb188c313190df62ab28c3763 | https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/manage.py#L15-L54 |
246,766 | calvinku96/labreporthelper | labreporthelper/manage.py | manage | def manage(settingspath, root_dir, argv):
"""
Manage all processes
"""
# add settings.json to environment variables
os.environ[ENV_VAR_SETTINGS] = settingspath
# add root_dir
os.environ[ENV_VAR_ROOT_DIR] = root_dir
# get datasets list
with open(settingspath) as settings_file:
settings = json.load(settings_file)
# manage args
datasets_list = generate_datasets_list(settings, argv)
if "make-data-file" == argv[1]:
make_data_file(datasets_list, argv)
elif "parse-data" == argv[1]:
parse_data(datasets_list, argv)
elif "do-operations" == argv[1]:
do_operations(datasets_list, argv)
else:
print_help() | python | def manage(settingspath, root_dir, argv):
"""
Manage all processes
"""
# add settings.json to environment variables
os.environ[ENV_VAR_SETTINGS] = settingspath
# add root_dir
os.environ[ENV_VAR_ROOT_DIR] = root_dir
# get datasets list
with open(settingspath) as settings_file:
settings = json.load(settings_file)
# manage args
datasets_list = generate_datasets_list(settings, argv)
if "make-data-file" == argv[1]:
make_data_file(datasets_list, argv)
elif "parse-data" == argv[1]:
parse_data(datasets_list, argv)
elif "do-operations" == argv[1]:
do_operations(datasets_list, argv)
else:
print_help() | [
"def",
"manage",
"(",
"settingspath",
",",
"root_dir",
",",
"argv",
")",
":",
"# add settings.json to environment variables",
"os",
".",
"environ",
"[",
"ENV_VAR_SETTINGS",
"]",
"=",
"settingspath",
"# add root_dir",
"os",
".",
"environ",
"[",
"ENV_VAR_ROOT_DIR",
"]",
"=",
"root_dir",
"# get datasets list",
"with",
"open",
"(",
"settingspath",
")",
"as",
"settings_file",
":",
"settings",
"=",
"json",
".",
"load",
"(",
"settings_file",
")",
"# manage args",
"datasets_list",
"=",
"generate_datasets_list",
"(",
"settings",
",",
"argv",
")",
"if",
"\"make-data-file\"",
"==",
"argv",
"[",
"1",
"]",
":",
"make_data_file",
"(",
"datasets_list",
",",
"argv",
")",
"elif",
"\"parse-data\"",
"==",
"argv",
"[",
"1",
"]",
":",
"parse_data",
"(",
"datasets_list",
",",
"argv",
")",
"elif",
"\"do-operations\"",
"==",
"argv",
"[",
"1",
"]",
":",
"do_operations",
"(",
"datasets_list",
",",
"argv",
")",
"else",
":",
"print_help",
"(",
")"
] | Manage all processes | [
"Manage",
"all",
"processes"
] | 4d436241f389c02eb188c313190df62ab28c3763 | https://github.com/calvinku96/labreporthelper/blob/4d436241f389c02eb188c313190df62ab28c3763/labreporthelper/manage.py#L95-L115 |
246,767 | shaypal5/utilp | utilp/func/_path.py | is_pathname_valid | def is_pathname_valid(pathname: str) -> bool:
"""Checks if the given path name is valid.
Returns
-------
`True` if the passed pathname is a valid pathname for the current OS;
`False` otherwise.
"""
# If this pathname is either not a string or is but is empty, this pathname
# is invalid.
try:
if not isinstance(pathname, str) or not pathname:
return False
# Strip this pathname's Windows-specific drive specifier (e.g., `C:\`)
# if any. Since Windows prohibits path components from containing `:`
# characters, failing to strip this `:`-suffixed prefix would
# erroneously invalidate all valid absolute Windows pathnames.
_, pathname = os.path.splitdrive(pathname)
# Directory guaranteed to exist. If the current OS is Windows, this is
# the drive to which Windows was installed (e.g., the "%HOMEDRIVE%"
# environment variable); else, the typical root directory.
root_dirname = os.environ.get('HOMEDRIVE', 'C:') \
if sys.platform == 'win32' else os.path.sep
assert os.path.isdir(root_dirname) # ...Murphy and her ironclad Law
# Append a path separator to this directory if needed.
root_dirname = root_dirname.rstrip(os.path.sep) + os.path.sep
# Test whether each path component split from this pathname is valid or
# not, ignoring non-existent and non-readable path components.
for pathname_part in pathname.split(os.path.sep):
try:
os.lstat(root_dirname + pathname_part)
# If an OS-specific exception is raised, its error code
# indicates whether this pathname is valid or not. Unless this
# is the case, this exception implies an ignorable kernel or
# filesystem complaint (e.g., path not found or inaccessible).
#
# Only the following exceptions indicate invalid pathnames:
#
# * Instances of the Windows-specific "WindowsError" class
# defining the "winerror" attribute whose value is
# "ERROR_INVALID_NAME". Under Windows, "winerror" is more
# fine-grained and hence useful than the generic "errno"
# attribute. When a too-long pathname is passed, for example,
# "errno" is "ENOENT" (i.e., no such file or directory) rather
# than "ENAMETOOLONG" (i.e., file name too long).
# * Instances of the cross-platform "OSError" class defining the
# generic "errno" attribute whose value is either:
# * Under most POSIX-compatible OSes, "ENAMETOOLONG".
# * Under some edge-case OSes (e.g., SunOS, *BSD), "ERANGE".
except OSError as exc:
if hasattr(exc, 'winerror'):
if exc.winerror == ERROR_INVALID_NAME:
return False
elif exc.errno in {errno.ENAMETOOLONG, errno.ERANGE}:
return False
# If a "TypeError" exception was raised, it almost certainly has the
# error message "embedded NUL character" indicating an invalid pathname.
except TypeError as exc:
return False
# If no exception was raised, all path components and hence this
# pathname itself are valid. (Praise be to the curmudgeonly python.)
else:
return True | python | def is_pathname_valid(pathname: str) -> bool:
"""Checks if the given path name is valid.
Returns
-------
`True` if the passed pathname is a valid pathname for the current OS;
`False` otherwise.
"""
# If this pathname is either not a string or is but is empty, this pathname
# is invalid.
try:
if not isinstance(pathname, str) or not pathname:
return False
# Strip this pathname's Windows-specific drive specifier (e.g., `C:\`)
# if any. Since Windows prohibits path components from containing `:`
# characters, failing to strip this `:`-suffixed prefix would
# erroneously invalidate all valid absolute Windows pathnames.
_, pathname = os.path.splitdrive(pathname)
# Directory guaranteed to exist. If the current OS is Windows, this is
# the drive to which Windows was installed (e.g., the "%HOMEDRIVE%"
# environment variable); else, the typical root directory.
root_dirname = os.environ.get('HOMEDRIVE', 'C:') \
if sys.platform == 'win32' else os.path.sep
assert os.path.isdir(root_dirname) # ...Murphy and her ironclad Law
# Append a path separator to this directory if needed.
root_dirname = root_dirname.rstrip(os.path.sep) + os.path.sep
# Test whether each path component split from this pathname is valid or
# not, ignoring non-existent and non-readable path components.
for pathname_part in pathname.split(os.path.sep):
try:
os.lstat(root_dirname + pathname_part)
# If an OS-specific exception is raised, its error code
# indicates whether this pathname is valid or not. Unless this
# is the case, this exception implies an ignorable kernel or
# filesystem complaint (e.g., path not found or inaccessible).
#
# Only the following exceptions indicate invalid pathnames:
#
# * Instances of the Windows-specific "WindowsError" class
# defining the "winerror" attribute whose value is
# "ERROR_INVALID_NAME". Under Windows, "winerror" is more
# fine-grained and hence useful than the generic "errno"
# attribute. When a too-long pathname is passed, for example,
# "errno" is "ENOENT" (i.e., no such file or directory) rather
# than "ENAMETOOLONG" (i.e., file name too long).
# * Instances of the cross-platform "OSError" class defining the
# generic "errno" attribute whose value is either:
# * Under most POSIX-compatible OSes, "ENAMETOOLONG".
# * Under some edge-case OSes (e.g., SunOS, *BSD), "ERANGE".
except OSError as exc:
if hasattr(exc, 'winerror'):
if exc.winerror == ERROR_INVALID_NAME:
return False
elif exc.errno in {errno.ENAMETOOLONG, errno.ERANGE}:
return False
# If a "TypeError" exception was raised, it almost certainly has the
# error message "embedded NUL character" indicating an invalid pathname.
except TypeError as exc:
return False
# If no exception was raised, all path components and hence this
# pathname itself are valid. (Praise be to the curmudgeonly python.)
else:
return True | [
"def",
"is_pathname_valid",
"(",
"pathname",
":",
"str",
")",
"->",
"bool",
":",
"# If this pathname is either not a string or is but is empty, this pathname",
"# is invalid.",
"try",
":",
"if",
"not",
"isinstance",
"(",
"pathname",
",",
"str",
")",
"or",
"not",
"pathname",
":",
"return",
"False",
"# Strip this pathname's Windows-specific drive specifier (e.g., `C:\\`)",
"# if any. Since Windows prohibits path components from containing `:`",
"# characters, failing to strip this `:`-suffixed prefix would",
"# erroneously invalidate all valid absolute Windows pathnames.",
"_",
",",
"pathname",
"=",
"os",
".",
"path",
".",
"splitdrive",
"(",
"pathname",
")",
"# Directory guaranteed to exist. If the current OS is Windows, this is",
"# the drive to which Windows was installed (e.g., the \"%HOMEDRIVE%\"",
"# environment variable); else, the typical root directory.",
"root_dirname",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'HOMEDRIVE'",
",",
"'C:'",
")",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
"else",
"os",
".",
"path",
".",
"sep",
"assert",
"os",
".",
"path",
".",
"isdir",
"(",
"root_dirname",
")",
"# ...Murphy and her ironclad Law",
"# Append a path separator to this directory if needed.",
"root_dirname",
"=",
"root_dirname",
".",
"rstrip",
"(",
"os",
".",
"path",
".",
"sep",
")",
"+",
"os",
".",
"path",
".",
"sep",
"# Test whether each path component split from this pathname is valid or",
"# not, ignoring non-existent and non-readable path components.",
"for",
"pathname_part",
"in",
"pathname",
".",
"split",
"(",
"os",
".",
"path",
".",
"sep",
")",
":",
"try",
":",
"os",
".",
"lstat",
"(",
"root_dirname",
"+",
"pathname_part",
")",
"# If an OS-specific exception is raised, its error code",
"# indicates whether this pathname is valid or not. Unless this",
"# is the case, this exception implies an ignorable kernel or",
"# filesystem complaint (e.g., path not found or inaccessible).",
"#",
"# Only the following exceptions indicate invalid pathnames:",
"#",
"# * Instances of the Windows-specific \"WindowsError\" class",
"# defining the \"winerror\" attribute whose value is",
"# \"ERROR_INVALID_NAME\". Under Windows, \"winerror\" is more",
"# fine-grained and hence useful than the generic \"errno\"",
"# attribute. When a too-long pathname is passed, for example,",
"# \"errno\" is \"ENOENT\" (i.e., no such file or directory) rather",
"# than \"ENAMETOOLONG\" (i.e., file name too long).",
"# * Instances of the cross-platform \"OSError\" class defining the",
"# generic \"errno\" attribute whose value is either:",
"# * Under most POSIX-compatible OSes, \"ENAMETOOLONG\".",
"# * Under some edge-case OSes (e.g., SunOS, *BSD), \"ERANGE\".",
"except",
"OSError",
"as",
"exc",
":",
"if",
"hasattr",
"(",
"exc",
",",
"'winerror'",
")",
":",
"if",
"exc",
".",
"winerror",
"==",
"ERROR_INVALID_NAME",
":",
"return",
"False",
"elif",
"exc",
".",
"errno",
"in",
"{",
"errno",
".",
"ENAMETOOLONG",
",",
"errno",
".",
"ERANGE",
"}",
":",
"return",
"False",
"# If a \"TypeError\" exception was raised, it almost certainly has the",
"# error message \"embedded NUL character\" indicating an invalid pathname.",
"except",
"TypeError",
"as",
"exc",
":",
"return",
"False",
"# If no exception was raised, all path components and hence this",
"# pathname itself are valid. (Praise be to the curmudgeonly python.)",
"else",
":",
"return",
"True"
] | Checks if the given path name is valid.
Returns
-------
`True` if the passed pathname is a valid pathname for the current OS;
`False` otherwise. | [
"Checks",
"if",
"the",
"given",
"path",
"name",
"is",
"valid",
"."
] | 932abaf8ccfd06557632b7dbebc7775da1de8430 | https://github.com/shaypal5/utilp/blob/932abaf8ccfd06557632b7dbebc7775da1de8430/utilp/func/_path.py#L25-L91 |
246,768 | shaypal5/utilp | utilp/func/_path.py | is_path_creatable | def is_path_creatable(pathname: str) -> bool:
"""Checks whether the given path is creatable.
Returns
-------
`True` if the current user has sufficient permissions to create the passed
pathname; `False` otherwise.
"""
# Parent directory of the passed path. If empty, we substitute the current
# working directory (CWD) instead.
dirname = os.path.dirname(pathname) or os.getcwd()
return os.access(dirname, os.W_OK) | python | def is_path_creatable(pathname: str) -> bool:
"""Checks whether the given path is creatable.
Returns
-------
`True` if the current user has sufficient permissions to create the passed
pathname; `False` otherwise.
"""
# Parent directory of the passed path. If empty, we substitute the current
# working directory (CWD) instead.
dirname = os.path.dirname(pathname) or os.getcwd()
return os.access(dirname, os.W_OK) | [
"def",
"is_path_creatable",
"(",
"pathname",
":",
"str",
")",
"->",
"bool",
":",
"# Parent directory of the passed path. If empty, we substitute the current",
"# working directory (CWD) instead.",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"pathname",
")",
"or",
"os",
".",
"getcwd",
"(",
")",
"return",
"os",
".",
"access",
"(",
"dirname",
",",
"os",
".",
"W_OK",
")"
] | Checks whether the given path is creatable.
Returns
-------
`True` if the current user has sufficient permissions to create the passed
pathname; `False` otherwise. | [
"Checks",
"whether",
"the",
"given",
"path",
"is",
"creatable",
"."
] | 932abaf8ccfd06557632b7dbebc7775da1de8430 | https://github.com/shaypal5/utilp/blob/932abaf8ccfd06557632b7dbebc7775da1de8430/utilp/func/_path.py#L98-L109 |
246,769 | shaypal5/utilp | utilp/func/_path.py | path_exists_or_creatable | def path_exists_or_creatable(pathname: str) -> bool:
"""Checks whether the given path exists or is creatable.
This function is guaranteed to _never_ raise exceptions.
Returns
-------
`True` if the passed pathname is a valid pathname for the current OS _and_
either currently exists or is hypothetically creatable; `False` otherwise.
"""
try:
# To prevent "os" module calls from raising undesirable exceptions on
# invalid pathnames, is_pathname_valid() is explicitly called first.
return is_pathname_valid(pathname) and (
os.path.exists(pathname) or is_path_creatable(pathname))
# Report failure on non-fatal filesystem complaints (e.g., connection
# timeouts, permissions issues) implying this path to be inaccessible. All
# other exceptions are unrelated fatal issues and should not be caught
# here.
except OSError:
return False | python | def path_exists_or_creatable(pathname: str) -> bool:
"""Checks whether the given path exists or is creatable.
This function is guaranteed to _never_ raise exceptions.
Returns
-------
`True` if the passed pathname is a valid pathname for the current OS _and_
either currently exists or is hypothetically creatable; `False` otherwise.
"""
try:
# To prevent "os" module calls from raising undesirable exceptions on
# invalid pathnames, is_pathname_valid() is explicitly called first.
return is_pathname_valid(pathname) and (
os.path.exists(pathname) or is_path_creatable(pathname))
# Report failure on non-fatal filesystem complaints (e.g., connection
# timeouts, permissions issues) implying this path to be inaccessible. All
# other exceptions are unrelated fatal issues and should not be caught
# here.
except OSError:
return False | [
"def",
"path_exists_or_creatable",
"(",
"pathname",
":",
"str",
")",
"->",
"bool",
":",
"try",
":",
"# To prevent \"os\" module calls from raising undesirable exceptions on",
"# invalid pathnames, is_pathname_valid() is explicitly called first.",
"return",
"is_pathname_valid",
"(",
"pathname",
")",
"and",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"pathname",
")",
"or",
"is_path_creatable",
"(",
"pathname",
")",
")",
"# Report failure on non-fatal filesystem complaints (e.g., connection",
"# timeouts, permissions issues) implying this path to be inaccessible. All",
"# other exceptions are unrelated fatal issues and should not be caught",
"# here.",
"except",
"OSError",
":",
"return",
"False"
] | Checks whether the given path exists or is creatable.
This function is guaranteed to _never_ raise exceptions.
Returns
-------
`True` if the passed pathname is a valid pathname for the current OS _and_
either currently exists or is hypothetically creatable; `False` otherwise. | [
"Checks",
"whether",
"the",
"given",
"path",
"exists",
"or",
"is",
"creatable",
"."
] | 932abaf8ccfd06557632b7dbebc7775da1de8430 | https://github.com/shaypal5/utilp/blob/932abaf8ccfd06557632b7dbebc7775da1de8430/utilp/func/_path.py#L112-L132 |
246,770 | shaypal5/utilp | utilp/func/_path.py | is_path_sibling_creatable | def is_path_sibling_creatable(pathname: str) -> bool:
"""Checks whether current user can create siblings of the given path.
Returns
-------
`True` if the current user has sufficient permissions to create siblings
(i.e., arbitrary files in the parent directory) of the passed pathname;
`False` otherwise.
"""
# Parent directory of the passed path. If empty, we substitute the current
# working directory (CWD) instead.
dirname = os.path.dirname(pathname) or os.getcwd()
try:
# For safety, explicitly close and hence delete this temporary file
# immediately after creating it in the passed path's parent directory.
with tempfile.TemporaryFile(dir=dirname):
pass
return True
# While the exact type of exception raised by the above function depends on
# the current version of the Python interpreter, all such types subclass
# the following exception superclass.
except EnvironmentError:
return False | python | def is_path_sibling_creatable(pathname: str) -> bool:
"""Checks whether current user can create siblings of the given path.
Returns
-------
`True` if the current user has sufficient permissions to create siblings
(i.e., arbitrary files in the parent directory) of the passed pathname;
`False` otherwise.
"""
# Parent directory of the passed path. If empty, we substitute the current
# working directory (CWD) instead.
dirname = os.path.dirname(pathname) or os.getcwd()
try:
# For safety, explicitly close and hence delete this temporary file
# immediately after creating it in the passed path's parent directory.
with tempfile.TemporaryFile(dir=dirname):
pass
return True
# While the exact type of exception raised by the above function depends on
# the current version of the Python interpreter, all such types subclass
# the following exception superclass.
except EnvironmentError:
return False | [
"def",
"is_path_sibling_creatable",
"(",
"pathname",
":",
"str",
")",
"->",
"bool",
":",
"# Parent directory of the passed path. If empty, we substitute the current",
"# working directory (CWD) instead.",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"pathname",
")",
"or",
"os",
".",
"getcwd",
"(",
")",
"try",
":",
"# For safety, explicitly close and hence delete this temporary file",
"# immediately after creating it in the passed path's parent directory.",
"with",
"tempfile",
".",
"TemporaryFile",
"(",
"dir",
"=",
"dirname",
")",
":",
"pass",
"return",
"True",
"# While the exact type of exception raised by the above function depends on",
"# the current version of the Python interpreter, all such types subclass",
"# the following exception superclass.",
"except",
"EnvironmentError",
":",
"return",
"False"
] | Checks whether current user can create siblings of the given path.
Returns
-------
`True` if the current user has sufficient permissions to create siblings
(i.e., arbitrary files in the parent directory) of the passed pathname;
`False` otherwise. | [
"Checks",
"whether",
"current",
"user",
"can",
"create",
"siblings",
"of",
"the",
"given",
"path",
"."
] | 932abaf8ccfd06557632b7dbebc7775da1de8430 | https://github.com/shaypal5/utilp/blob/932abaf8ccfd06557632b7dbebc7775da1de8430/utilp/func/_path.py#L135-L158 |
246,771 | shaypal5/utilp | utilp/func/_path.py | path_exists_or_creatable_portable | def path_exists_or_creatable_portable(pathname: str) -> bool:
"""OS-portable check for whether current path exists or is creatable.
This function is guaranteed to _never_ raise exceptions.
Returns
------
`True` if the passed pathname is a valid pathname on the current OS _and_
either currently exists or is hypothetically creatable in a cross-platform
manner optimized for POSIX-unfriendly filesystems; `False` otherwise.
"""
try:
# To prevent "os" module calls from raising undesirable exceptions on
# invalid pathnames, is_pathname_valid() is explicitly called first.
return is_pathname_valid(pathname) and (
os.path.exists(pathname) or is_path_sibling_creatable(pathname))
# Report failure on non-fatal filesystem complaints (e.g., connection
# timeouts, permissions issues) implying this path to be inaccessible. All
# other exceptions are unrelated fatal issues and should not be caught
# here.
except OSError:
return False | python | def path_exists_or_creatable_portable(pathname: str) -> bool:
"""OS-portable check for whether current path exists or is creatable.
This function is guaranteed to _never_ raise exceptions.
Returns
------
`True` if the passed pathname is a valid pathname on the current OS _and_
either currently exists or is hypothetically creatable in a cross-platform
manner optimized for POSIX-unfriendly filesystems; `False` otherwise.
"""
try:
# To prevent "os" module calls from raising undesirable exceptions on
# invalid pathnames, is_pathname_valid() is explicitly called first.
return is_pathname_valid(pathname) and (
os.path.exists(pathname) or is_path_sibling_creatable(pathname))
# Report failure on non-fatal filesystem complaints (e.g., connection
# timeouts, permissions issues) implying this path to be inaccessible. All
# other exceptions are unrelated fatal issues and should not be caught
# here.
except OSError:
return False | [
"def",
"path_exists_or_creatable_portable",
"(",
"pathname",
":",
"str",
")",
"->",
"bool",
":",
"try",
":",
"# To prevent \"os\" module calls from raising undesirable exceptions on",
"# invalid pathnames, is_pathname_valid() is explicitly called first.",
"return",
"is_pathname_valid",
"(",
"pathname",
")",
"and",
"(",
"os",
".",
"path",
".",
"exists",
"(",
"pathname",
")",
"or",
"is_path_sibling_creatable",
"(",
"pathname",
")",
")",
"# Report failure on non-fatal filesystem complaints (e.g., connection",
"# timeouts, permissions issues) implying this path to be inaccessible. All",
"# other exceptions are unrelated fatal issues and should not be caught",
"# here.",
"except",
"OSError",
":",
"return",
"False"
] | OS-portable check for whether current path exists or is creatable.
This function is guaranteed to _never_ raise exceptions.
Returns
------
`True` if the passed pathname is a valid pathname on the current OS _and_
either currently exists or is hypothetically creatable in a cross-platform
manner optimized for POSIX-unfriendly filesystems; `False` otherwise. | [
"OS",
"-",
"portable",
"check",
"for",
"whether",
"current",
"path",
"exists",
"or",
"is",
"creatable",
"."
] | 932abaf8ccfd06557632b7dbebc7775da1de8430 | https://github.com/shaypal5/utilp/blob/932abaf8ccfd06557632b7dbebc7775da1de8430/utilp/func/_path.py#L161-L182 |
246,772 | d0c0nnor/jocelyn | src/jocelyn/__init__.py | Q | def Q(name):
"""Gets a variable from the current sketch. Processing has a number
of methods and variables with the same name, 'mousePressed' for
example. This allows us to disambiguate.
Also casts numeric values as floats to make it easier to translate
code from pde to python.
"""
retval = PApplet.getDeclaredField(name).get(Sketch.get_instance())
if isinstance(retval, (long, int)):
return float(retval)
else:
return retval | python | def Q(name):
"""Gets a variable from the current sketch. Processing has a number
of methods and variables with the same name, 'mousePressed' for
example. This allows us to disambiguate.
Also casts numeric values as floats to make it easier to translate
code from pde to python.
"""
retval = PApplet.getDeclaredField(name).get(Sketch.get_instance())
if isinstance(retval, (long, int)):
return float(retval)
else:
return retval | [
"def",
"Q",
"(",
"name",
")",
":",
"retval",
"=",
"PApplet",
".",
"getDeclaredField",
"(",
"name",
")",
".",
"get",
"(",
"Sketch",
".",
"get_instance",
"(",
")",
")",
"if",
"isinstance",
"(",
"retval",
",",
"(",
"long",
",",
"int",
")",
")",
":",
"return",
"float",
"(",
"retval",
")",
"else",
":",
"return",
"retval"
] | Gets a variable from the current sketch. Processing has a number
of methods and variables with the same name, 'mousePressed' for
example. This allows us to disambiguate.
Also casts numeric values as floats to make it easier to translate
code from pde to python. | [
"Gets",
"a",
"variable",
"from",
"the",
"current",
"sketch",
".",
"Processing",
"has",
"a",
"number",
"of",
"methods",
"and",
"variables",
"with",
"the",
"same",
"name",
"mousePressed",
"for",
"example",
".",
"This",
"allows",
"us",
"to",
"disambiguate",
"."
] | a9bb73ab89d7488cec1b1bcd6d612f7a56d9b01c | https://github.com/d0c0nnor/jocelyn/blob/a9bb73ab89d7488cec1b1bcd6d612f7a56d9b01c/src/jocelyn/__init__.py#L150-L163 |
246,773 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/autoparser/conf_reader.py | _get_source | def _get_source(link):
"""
Return source of the `link` whether it is filename or url.
Args:
link (str): Filename or URL.
Returns:
str: Content.
Raises:
UserWarning: When the `link` couldn't be resolved.
"""
if link.startswith("http://") or link.startswith("https://"):
down = httpkie.Downloader()
return down.download(link)
if os.path.exists(link):
with open(link) as f:
return f.read()
raise UserWarning("html: '%s' is neither URL or data!" % link) | python | def _get_source(link):
"""
Return source of the `link` whether it is filename or url.
Args:
link (str): Filename or URL.
Returns:
str: Content.
Raises:
UserWarning: When the `link` couldn't be resolved.
"""
if link.startswith("http://") or link.startswith("https://"):
down = httpkie.Downloader()
return down.download(link)
if os.path.exists(link):
with open(link) as f:
return f.read()
raise UserWarning("html: '%s' is neither URL or data!" % link) | [
"def",
"_get_source",
"(",
"link",
")",
":",
"if",
"link",
".",
"startswith",
"(",
"\"http://\"",
")",
"or",
"link",
".",
"startswith",
"(",
"\"https://\"",
")",
":",
"down",
"=",
"httpkie",
".",
"Downloader",
"(",
")",
"return",
"down",
".",
"download",
"(",
"link",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"link",
")",
":",
"with",
"open",
"(",
"link",
")",
"as",
"f",
":",
"return",
"f",
".",
"read",
"(",
")",
"raise",
"UserWarning",
"(",
"\"html: '%s' is neither URL or data!\"",
"%",
"link",
")"
] | Return source of the `link` whether it is filename or url.
Args:
link (str): Filename or URL.
Returns:
str: Content.
Raises:
UserWarning: When the `link` couldn't be resolved. | [
"Return",
"source",
"of",
"the",
"link",
"whether",
"it",
"is",
"filename",
"or",
"url",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/conf_reader.py#L18-L39 |
246,774 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/autoparser/conf_reader.py | _process_config_item | def _process_config_item(item, dirname):
"""
Process one item from the configuration file, which contains multiple items
saved as dictionary.
This function reads additional data from the config and do some
replacements - for example, if you specify url, it will download data
from this url and so on.
Args:
item (dict): Item, which will be processed.
Note:
Returned data format::
{
"link": "link to html page/file",
"html": "html code from file/url",
"vars": {
"varname": {
"data": "matching data..",
...
}
}
}
Returns:
dict: Dictionary in format showed above.
"""
item = copy.deepcopy(item)
html = item.get("html", None)
if not html:
raise UserWarning("Can't find HTML source for item:\n%s" % str(item))
# process HTML link
link = html if "://" in html else os.path.join(dirname, html)
del item["html"]
# replace $name with the actual name of the field
for key, val in item.items():
if "notfoundmsg" in val:
val["notfoundmsg"] = val["notfoundmsg"].replace("$name", key)
return {
"html": _get_source(link),
"link": link,
"vars": item
} | python | def _process_config_item(item, dirname):
"""
Process one item from the configuration file, which contains multiple items
saved as dictionary.
This function reads additional data from the config and do some
replacements - for example, if you specify url, it will download data
from this url and so on.
Args:
item (dict): Item, which will be processed.
Note:
Returned data format::
{
"link": "link to html page/file",
"html": "html code from file/url",
"vars": {
"varname": {
"data": "matching data..",
...
}
}
}
Returns:
dict: Dictionary in format showed above.
"""
item = copy.deepcopy(item)
html = item.get("html", None)
if not html:
raise UserWarning("Can't find HTML source for item:\n%s" % str(item))
# process HTML link
link = html if "://" in html else os.path.join(dirname, html)
del item["html"]
# replace $name with the actual name of the field
for key, val in item.items():
if "notfoundmsg" in val:
val["notfoundmsg"] = val["notfoundmsg"].replace("$name", key)
return {
"html": _get_source(link),
"link": link,
"vars": item
} | [
"def",
"_process_config_item",
"(",
"item",
",",
"dirname",
")",
":",
"item",
"=",
"copy",
".",
"deepcopy",
"(",
"item",
")",
"html",
"=",
"item",
".",
"get",
"(",
"\"html\"",
",",
"None",
")",
"if",
"not",
"html",
":",
"raise",
"UserWarning",
"(",
"\"Can't find HTML source for item:\\n%s\"",
"%",
"str",
"(",
"item",
")",
")",
"# process HTML link",
"link",
"=",
"html",
"if",
"\"://\"",
"in",
"html",
"else",
"os",
".",
"path",
".",
"join",
"(",
"dirname",
",",
"html",
")",
"del",
"item",
"[",
"\"html\"",
"]",
"# replace $name with the actual name of the field",
"for",
"key",
",",
"val",
"in",
"item",
".",
"items",
"(",
")",
":",
"if",
"\"notfoundmsg\"",
"in",
"val",
":",
"val",
"[",
"\"notfoundmsg\"",
"]",
"=",
"val",
"[",
"\"notfoundmsg\"",
"]",
".",
"replace",
"(",
"\"$name\"",
",",
"key",
")",
"return",
"{",
"\"html\"",
":",
"_get_source",
"(",
"link",
")",
",",
"\"link\"",
":",
"link",
",",
"\"vars\"",
":",
"item",
"}"
] | Process one item from the configuration file, which contains multiple items
saved as dictionary.
This function reads additional data from the config and do some
replacements - for example, if you specify url, it will download data
from this url and so on.
Args:
item (dict): Item, which will be processed.
Note:
Returned data format::
{
"link": "link to html page/file",
"html": "html code from file/url",
"vars": {
"varname": {
"data": "matching data..",
...
}
}
}
Returns:
dict: Dictionary in format showed above. | [
"Process",
"one",
"item",
"from",
"the",
"configuration",
"file",
"which",
"contains",
"multiple",
"items",
"saved",
"as",
"dictionary",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/conf_reader.py#L42-L89 |
246,775 | edeposit/edeposit.amqp.harvester | src/edeposit/amqp/harvester/autoparser/conf_reader.py | read_config | def read_config(file_name):
"""
Read YAML file with configuration and pointers to example data.
Args:
file_name (str): Name of the file, where the configuration is stored.
Returns:
dict: Parsed and processed data (see :func:`_process_config_item`).
Example YAML file::
html: simple_xml.xml
first:
data: i wan't this
required: true
notfoundmsg: Can't find variable $name.
second:
data: and this
---
html: simple_xml2.xml
first:
data: something wanted
required: true
notfoundmsg: Can't find variable $name.
second:
data: another wanted thing
"""
dirname = os.path.dirname(
os.path.abspath(file_name)
)
dirname = os.path.relpath(dirname)
# create utf-8 strings, not unicode
def custom_str_constructor(loader, node):
return loader.construct_scalar(node).encode('utf-8')
yaml.add_constructor(u'tag:yaml.org,2002:str', custom_str_constructor)
config = []
with open(file_name) as f:
for item in yaml.load_all(f.read()):
config.append(
_process_config_item(item, dirname)
)
return config | python | def read_config(file_name):
"""
Read YAML file with configuration and pointers to example data.
Args:
file_name (str): Name of the file, where the configuration is stored.
Returns:
dict: Parsed and processed data (see :func:`_process_config_item`).
Example YAML file::
html: simple_xml.xml
first:
data: i wan't this
required: true
notfoundmsg: Can't find variable $name.
second:
data: and this
---
html: simple_xml2.xml
first:
data: something wanted
required: true
notfoundmsg: Can't find variable $name.
second:
data: another wanted thing
"""
dirname = os.path.dirname(
os.path.abspath(file_name)
)
dirname = os.path.relpath(dirname)
# create utf-8 strings, not unicode
def custom_str_constructor(loader, node):
return loader.construct_scalar(node).encode('utf-8')
yaml.add_constructor(u'tag:yaml.org,2002:str', custom_str_constructor)
config = []
with open(file_name) as f:
for item in yaml.load_all(f.read()):
config.append(
_process_config_item(item, dirname)
)
return config | [
"def",
"read_config",
"(",
"file_name",
")",
":",
"dirname",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"file_name",
")",
")",
"dirname",
"=",
"os",
".",
"path",
".",
"relpath",
"(",
"dirname",
")",
"# create utf-8 strings, not unicode",
"def",
"custom_str_constructor",
"(",
"loader",
",",
"node",
")",
":",
"return",
"loader",
".",
"construct_scalar",
"(",
"node",
")",
".",
"encode",
"(",
"'utf-8'",
")",
"yaml",
".",
"add_constructor",
"(",
"u'tag:yaml.org,2002:str'",
",",
"custom_str_constructor",
")",
"config",
"=",
"[",
"]",
"with",
"open",
"(",
"file_name",
")",
"as",
"f",
":",
"for",
"item",
"in",
"yaml",
".",
"load_all",
"(",
"f",
".",
"read",
"(",
")",
")",
":",
"config",
".",
"append",
"(",
"_process_config_item",
"(",
"item",
",",
"dirname",
")",
")",
"return",
"config"
] | Read YAML file with configuration and pointers to example data.
Args:
file_name (str): Name of the file, where the configuration is stored.
Returns:
dict: Parsed and processed data (see :func:`_process_config_item`).
Example YAML file::
html: simple_xml.xml
first:
data: i wan't this
required: true
notfoundmsg: Can't find variable $name.
second:
data: and this
---
html: simple_xml2.xml
first:
data: something wanted
required: true
notfoundmsg: Can't find variable $name.
second:
data: another wanted thing | [
"Read",
"YAML",
"file",
"with",
"configuration",
"and",
"pointers",
"to",
"example",
"data",
"."
] | 38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e | https://github.com/edeposit/edeposit.amqp.harvester/blob/38cb87ccdf6bf2f550a98460d0a329c4b9dc8e2e/src/edeposit/amqp/harvester/autoparser/conf_reader.py#L92-L136 |
246,776 | andrewjsledge/django-hash-filter | django_hash_filter/templatetags/hash_filter.py | hash | def hash(value, arg):
"""
Returns a hex-digest of the passed in value for the hash algorithm given.
"""
arg = str(arg).lower()
if sys.version_info >= (3,0):
value = value.encode("utf-8")
if not arg in get_available_hashes():
raise TemplateSyntaxError("The %s hash algorithm does not exist. Supported algorithms are: %" % (arg, get_available_hashes()))
try:
f = getattr(hashlib, arg)
hashed = f(value).hexdigest()
except Exception:
raise ValueError("The %s hash algorithm cannot produce a hex digest. Ensure that OpenSSL is properly installed." % arg)
return hashed | python | def hash(value, arg):
"""
Returns a hex-digest of the passed in value for the hash algorithm given.
"""
arg = str(arg).lower()
if sys.version_info >= (3,0):
value = value.encode("utf-8")
if not arg in get_available_hashes():
raise TemplateSyntaxError("The %s hash algorithm does not exist. Supported algorithms are: %" % (arg, get_available_hashes()))
try:
f = getattr(hashlib, arg)
hashed = f(value).hexdigest()
except Exception:
raise ValueError("The %s hash algorithm cannot produce a hex digest. Ensure that OpenSSL is properly installed." % arg)
return hashed | [
"def",
"hash",
"(",
"value",
",",
"arg",
")",
":",
"arg",
"=",
"str",
"(",
"arg",
")",
".",
"lower",
"(",
")",
"if",
"sys",
".",
"version_info",
">=",
"(",
"3",
",",
"0",
")",
":",
"value",
"=",
"value",
".",
"encode",
"(",
"\"utf-8\"",
")",
"if",
"not",
"arg",
"in",
"get_available_hashes",
"(",
")",
":",
"raise",
"TemplateSyntaxError",
"(",
"\"The %s hash algorithm does not exist. Supported algorithms are: %\"",
"%",
"(",
"arg",
",",
"get_available_hashes",
"(",
")",
")",
")",
"try",
":",
"f",
"=",
"getattr",
"(",
"hashlib",
",",
"arg",
")",
"hashed",
"=",
"f",
"(",
"value",
")",
".",
"hexdigest",
"(",
")",
"except",
"Exception",
":",
"raise",
"ValueError",
"(",
"\"The %s hash algorithm cannot produce a hex digest. Ensure that OpenSSL is properly installed.\"",
"%",
"arg",
")",
"return",
"hashed"
] | Returns a hex-digest of the passed in value for the hash algorithm given. | [
"Returns",
"a",
"hex",
"-",
"digest",
"of",
"the",
"passed",
"in",
"value",
"for",
"the",
"hash",
"algorithm",
"given",
"."
] | ea90b2903938e0733d3abfafed308a8d041d9fe7 | https://github.com/andrewjsledge/django-hash-filter/blob/ea90b2903938e0733d3abfafed308a8d041d9fe7/django_hash_filter/templatetags/hash_filter.py#L13-L27 |
246,777 | tBaxter/django-fretboard | fretboard/templatetags/paginator.py | paginator | def paginator(context, adjacent_pages=2):
"""
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic view.
"""
current_page = context.get('page')
paginator = context.get('paginator')
if not paginator:
return
pages = paginator.num_pages
current_range = range(current_page - adjacent_pages, current_page + adjacent_pages + 1)
page_numbers = [n for n in current_range if n > 0 and n <= pages]
slugtype = ''
if 'topic_slug' in context:
page_url = context["topic"].get_short_url()
slugtype = 'topic'
elif 'forum_slug' in context:
page_url = '/forum/%s/' % context["forum_slug"]
slugtype = 'forum'
else:
page_url = context['request'].get_full_path()
return {
"is_paginated": context["is_paginated"],
"page": current_page,
"pages": pages,
"page_obj": context['page_obj'],
"page_numbers": page_numbers,
"has_next": context["page_obj"].has_next(),
"has_previous": context["page_obj"].has_previous(),
"page_url" : page_url,
'slugtype' : slugtype,
} | python | def paginator(context, adjacent_pages=2):
"""
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic view.
"""
current_page = context.get('page')
paginator = context.get('paginator')
if not paginator:
return
pages = paginator.num_pages
current_range = range(current_page - adjacent_pages, current_page + adjacent_pages + 1)
page_numbers = [n for n in current_range if n > 0 and n <= pages]
slugtype = ''
if 'topic_slug' in context:
page_url = context["topic"].get_short_url()
slugtype = 'topic'
elif 'forum_slug' in context:
page_url = '/forum/%s/' % context["forum_slug"]
slugtype = 'forum'
else:
page_url = context['request'].get_full_path()
return {
"is_paginated": context["is_paginated"],
"page": current_page,
"pages": pages,
"page_obj": context['page_obj'],
"page_numbers": page_numbers,
"has_next": context["page_obj"].has_next(),
"has_previous": context["page_obj"].has_previous(),
"page_url" : page_url,
'slugtype' : slugtype,
} | [
"def",
"paginator",
"(",
"context",
",",
"adjacent_pages",
"=",
"2",
")",
":",
"current_page",
"=",
"context",
".",
"get",
"(",
"'page'",
")",
"paginator",
"=",
"context",
".",
"get",
"(",
"'paginator'",
")",
"if",
"not",
"paginator",
":",
"return",
"pages",
"=",
"paginator",
".",
"num_pages",
"current_range",
"=",
"range",
"(",
"current_page",
"-",
"adjacent_pages",
",",
"current_page",
"+",
"adjacent_pages",
"+",
"1",
")",
"page_numbers",
"=",
"[",
"n",
"for",
"n",
"in",
"current_range",
"if",
"n",
">",
"0",
"and",
"n",
"<=",
"pages",
"]",
"slugtype",
"=",
"''",
"if",
"'topic_slug'",
"in",
"context",
":",
"page_url",
"=",
"context",
"[",
"\"topic\"",
"]",
".",
"get_short_url",
"(",
")",
"slugtype",
"=",
"'topic'",
"elif",
"'forum_slug'",
"in",
"context",
":",
"page_url",
"=",
"'/forum/%s/'",
"%",
"context",
"[",
"\"forum_slug\"",
"]",
"slugtype",
"=",
"'forum'",
"else",
":",
"page_url",
"=",
"context",
"[",
"'request'",
"]",
".",
"get_full_path",
"(",
")",
"return",
"{",
"\"is_paginated\"",
":",
"context",
"[",
"\"is_paginated\"",
"]",
",",
"\"page\"",
":",
"current_page",
",",
"\"pages\"",
":",
"pages",
",",
"\"page_obj\"",
":",
"context",
"[",
"'page_obj'",
"]",
",",
"\"page_numbers\"",
":",
"page_numbers",
",",
"\"has_next\"",
":",
"context",
"[",
"\"page_obj\"",
"]",
".",
"has_next",
"(",
")",
",",
"\"has_previous\"",
":",
"context",
"[",
"\"page_obj\"",
"]",
".",
"has_previous",
"(",
")",
",",
"\"page_url\"",
":",
"page_url",
",",
"'slugtype'",
":",
"slugtype",
",",
"}"
] | To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic view. | [
"To",
"be",
"used",
"in",
"conjunction",
"with",
"the",
"object_list",
"generic",
"view",
".",
"Adds",
"pagination",
"context",
"variables",
"for",
"use",
"in",
"displaying",
"first",
"adjacent",
"and",
"last",
"page",
"links",
"in",
"addition",
"to",
"those",
"created",
"by",
"the",
"object_list",
"generic",
"view",
"."
] | 3c3f9557089821283f315a07f3e5a57a2725ab3b | https://github.com/tBaxter/django-fretboard/blob/3c3f9557089821283f315a07f3e5a57a2725ab3b/fretboard/templatetags/paginator.py#L7-L41 |
246,778 | genericclient/genericclient-base | genericclient_base/utils.py | parse_headers_link | def parse_headers_link(headers):
"""Returns the parsed header links of the response, if any."""
header = CaseInsensitiveDict(headers).get('link')
l = {}
if header:
links = parse_link(header)
for link in links:
key = link.get('rel') or link.get('url')
l[key] = link
return l | python | def parse_headers_link(headers):
"""Returns the parsed header links of the response, if any."""
header = CaseInsensitiveDict(headers).get('link')
l = {}
if header:
links = parse_link(header)
for link in links:
key = link.get('rel') or link.get('url')
l[key] = link
return l | [
"def",
"parse_headers_link",
"(",
"headers",
")",
":",
"header",
"=",
"CaseInsensitiveDict",
"(",
"headers",
")",
".",
"get",
"(",
"'link'",
")",
"l",
"=",
"{",
"}",
"if",
"header",
":",
"links",
"=",
"parse_link",
"(",
"header",
")",
"for",
"link",
"in",
"links",
":",
"key",
"=",
"link",
".",
"get",
"(",
"'rel'",
")",
"or",
"link",
".",
"get",
"(",
"'url'",
")",
"l",
"[",
"key",
"]",
"=",
"link",
"return",
"l"
] | Returns the parsed header links of the response, if any. | [
"Returns",
"the",
"parsed",
"header",
"links",
"of",
"the",
"response",
"if",
"any",
"."
] | 193f7c879c40decaf03504af633f593b88e4abc5 | https://github.com/genericclient/genericclient-base/blob/193f7c879c40decaf03504af633f593b88e4abc5/genericclient_base/utils.py#L60-L74 |
246,779 | zyga/python-phablet | phablet.py | Phablet.run | def run(self, cmd, timeout=None, key=None):
"""
Run a command on the phablet device using ssh
:param cmd:
a list of strings to execute as a command
:param timeout:
a timeout (in seconds) for device discovery
:param key:
a path to a public ssh key to use for connection
:returns:
the exit code of the command
This method will not allow you to capture stdout/stderr from the target
process. If you wish to do that please consider switching to one of
subprocess functions along with. :meth:`cmdline()`.
"""
if not isinstance(cmd, list):
raise TypeError("cmd needs to be a list")
if not all(isinstance(item, str) for item in cmd):
raise TypeError("cmd needs to be a list of strings")
self.connect(timeout, key)
return self._run_ssh(cmd) | python | def run(self, cmd, timeout=None, key=None):
"""
Run a command on the phablet device using ssh
:param cmd:
a list of strings to execute as a command
:param timeout:
a timeout (in seconds) for device discovery
:param key:
a path to a public ssh key to use for connection
:returns:
the exit code of the command
This method will not allow you to capture stdout/stderr from the target
process. If you wish to do that please consider switching to one of
subprocess functions along with. :meth:`cmdline()`.
"""
if not isinstance(cmd, list):
raise TypeError("cmd needs to be a list")
if not all(isinstance(item, str) for item in cmd):
raise TypeError("cmd needs to be a list of strings")
self.connect(timeout, key)
return self._run_ssh(cmd) | [
"def",
"run",
"(",
"self",
",",
"cmd",
",",
"timeout",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"cmd",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"cmd needs to be a list\"",
")",
"if",
"not",
"all",
"(",
"isinstance",
"(",
"item",
",",
"str",
")",
"for",
"item",
"in",
"cmd",
")",
":",
"raise",
"TypeError",
"(",
"\"cmd needs to be a list of strings\"",
")",
"self",
".",
"connect",
"(",
"timeout",
",",
"key",
")",
"return",
"self",
".",
"_run_ssh",
"(",
"cmd",
")"
] | Run a command on the phablet device using ssh
:param cmd:
a list of strings to execute as a command
:param timeout:
a timeout (in seconds) for device discovery
:param key:
a path to a public ssh key to use for connection
:returns:
the exit code of the command
This method will not allow you to capture stdout/stderr from the target
process. If you wish to do that please consider switching to one of
subprocess functions along with. :meth:`cmdline()`. | [
"Run",
"a",
"command",
"on",
"the",
"phablet",
"device",
"using",
"ssh"
] | c281045dfb8b55dd2888e1efe9631f72ffc77ac8 | https://github.com/zyga/python-phablet/blob/c281045dfb8b55dd2888e1efe9631f72ffc77ac8/phablet.py#L165-L187 |
246,780 | zyga/python-phablet | phablet.py | Phablet.connect | def connect(self, timeout=None, key=None):
"""
Perform one-time setup procedure.
:param timeout:
a timeout (in seconds) for device discovery
:param key:
a path to a public ssh key to use for connection
This method will allow you to execute :meth:`cmdline()`
repeatedly without incurring the extra overhead of the setup procedure.
Note that this procedure needs to be repeated whenever:
- the target device reboots
- the local adb server is restarted
- your ssh keys change
.. versionadded:: 0.2
"""
if self.port is not None:
return
self._wait_for_device(timeout)
self._setup_port_forwarding()
self._purge_known_hosts_entry()
self._copy_ssh_key(key) | python | def connect(self, timeout=None, key=None):
"""
Perform one-time setup procedure.
:param timeout:
a timeout (in seconds) for device discovery
:param key:
a path to a public ssh key to use for connection
This method will allow you to execute :meth:`cmdline()`
repeatedly without incurring the extra overhead of the setup procedure.
Note that this procedure needs to be repeated whenever:
- the target device reboots
- the local adb server is restarted
- your ssh keys change
.. versionadded:: 0.2
"""
if self.port is not None:
return
self._wait_for_device(timeout)
self._setup_port_forwarding()
self._purge_known_hosts_entry()
self._copy_ssh_key(key) | [
"def",
"connect",
"(",
"self",
",",
"timeout",
"=",
"None",
",",
"key",
"=",
"None",
")",
":",
"if",
"self",
".",
"port",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_wait_for_device",
"(",
"timeout",
")",
"self",
".",
"_setup_port_forwarding",
"(",
")",
"self",
".",
"_purge_known_hosts_entry",
"(",
")",
"self",
".",
"_copy_ssh_key",
"(",
"key",
")"
] | Perform one-time setup procedure.
:param timeout:
a timeout (in seconds) for device discovery
:param key:
a path to a public ssh key to use for connection
This method will allow you to execute :meth:`cmdline()`
repeatedly without incurring the extra overhead of the setup procedure.
Note that this procedure needs to be repeated whenever:
- the target device reboots
- the local adb server is restarted
- your ssh keys change
.. versionadded:: 0.2 | [
"Perform",
"one",
"-",
"time",
"setup",
"procedure",
"."
] | c281045dfb8b55dd2888e1efe9631f72ffc77ac8 | https://github.com/zyga/python-phablet/blob/c281045dfb8b55dd2888e1efe9631f72ffc77ac8/phablet.py#L189-L213 |
246,781 | kodexlab/reliure | reliure/options.py | Option.FromType | def FromType(name, otype):
""" ValueOption subclasses factory, creates a convenient option to store
data from a given Type.
attribute precedence :
* ``|attrs| > 0`` (``multi`` and ``uniq`` are implicit) => NotImplementedError
* ``uniq`` (``multi`` is implicit) => NotImplementedError
* ``multi`` and ``not uniq`` => NotImplementedError
* ``not multi`` => ValueOption
:param name: Name of the option
:type name: str
:param otype: the desired type of field
:type otype: subclass of :class:`.GenericType`
"""
if otype.attrs is not None and len(otype.attrs):
raise NotImplementedError("for otype, options can't have attributs")
#return VectorField(ftype)
elif otype.uniq:
return SetOption(name, otype)
elif otype.multi:
#XXX: dbl check needed?
#raise NotImplementedError("for now, options can't have multiple values")
return ListOption(name, otype)
else:
return ValueOption(name, otype) | python | def FromType(name, otype):
""" ValueOption subclasses factory, creates a convenient option to store
data from a given Type.
attribute precedence :
* ``|attrs| > 0`` (``multi`` and ``uniq`` are implicit) => NotImplementedError
* ``uniq`` (``multi`` is implicit) => NotImplementedError
* ``multi`` and ``not uniq`` => NotImplementedError
* ``not multi`` => ValueOption
:param name: Name of the option
:type name: str
:param otype: the desired type of field
:type otype: subclass of :class:`.GenericType`
"""
if otype.attrs is not None and len(otype.attrs):
raise NotImplementedError("for otype, options can't have attributs")
#return VectorField(ftype)
elif otype.uniq:
return SetOption(name, otype)
elif otype.multi:
#XXX: dbl check needed?
#raise NotImplementedError("for now, options can't have multiple values")
return ListOption(name, otype)
else:
return ValueOption(name, otype) | [
"def",
"FromType",
"(",
"name",
",",
"otype",
")",
":",
"if",
"otype",
".",
"attrs",
"is",
"not",
"None",
"and",
"len",
"(",
"otype",
".",
"attrs",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"for otype, options can't have attributs\"",
")",
"#return VectorField(ftype)",
"elif",
"otype",
".",
"uniq",
":",
"return",
"SetOption",
"(",
"name",
",",
"otype",
")",
"elif",
"otype",
".",
"multi",
":",
"#XXX: dbl check needed?",
"#raise NotImplementedError(\"for now, options can't have multiple values\")",
"return",
"ListOption",
"(",
"name",
",",
"otype",
")",
"else",
":",
"return",
"ValueOption",
"(",
"name",
",",
"otype",
")"
] | ValueOption subclasses factory, creates a convenient option to store
data from a given Type.
attribute precedence :
* ``|attrs| > 0`` (``multi`` and ``uniq`` are implicit) => NotImplementedError
* ``uniq`` (``multi`` is implicit) => NotImplementedError
* ``multi`` and ``not uniq`` => NotImplementedError
* ``not multi`` => ValueOption
:param name: Name of the option
:type name: str
:param otype: the desired type of field
:type otype: subclass of :class:`.GenericType` | [
"ValueOption",
"subclasses",
"factory",
"creates",
"a",
"convenient",
"option",
"to",
"store",
"data",
"from",
"a",
"given",
"Type",
"."
] | 0450c7a9254c5c003162738458bbe0c49e777ba5 | https://github.com/kodexlab/reliure/blob/0450c7a9254c5c003162738458bbe0c49e777ba5/reliure/options.py#L24-L50 |
246,782 | heikomuller/sco-datastore | scodata/datastore.py | ObjectStore.upsert_object_property | def upsert_object_property(self, identifier, properties, ignore_constraints=False):
"""Manipulate an object's property set. Inserts or updates properties in
given dictionary. If a property key does not exist in the object's
property set it is created. If the value is None an existing property is
deleted.
Existing object properties that are not present in the given property
set remain unaffacted.
Deleting mandatory properties or updating immutable properties results
in a ValueError. These constraints can be disabled using the
ignore_constraints parameter.
Parameters
----------
identifier : string
Unique object identifier
properties : Dictionary()
Dictionary of property names and their new values.
ignore_constraints : Boolean
Flag indicating whether to ignore immutable and mandatory property
constraints (True) or nore (False, Default).
Returns
-------
ObjectHandle
Handle to updated object or None if object does not exist
"""
# Retrieve the object with the gievn identifier. This is a (sub-)class
# of ObjectHandle
obj = self.get_object(identifier)
if not obj is None:
# Modify property set of retrieved object handle. Raise exception if
# and of the upserts is not valid.
for key in properties:
value = properties[key]
# If the update affects an immutable property raise exception
if not ignore_constraints and key in self.immutable_properties:
raise ValueError('update to immutable property: ' + key)
# Check whether the operation is an UPSERT (value != None) or
# DELETE (value == None)
if not value is None:
obj.properties[key] = value
else:
# DELETE. Make sure the property is not mandatory
if not ignore_constraints and key in self.mandatory_properties:
raise ValueError('delete mandatory property: ' + key)
elif key in obj.properties:
del obj.properties[key]
# Update object in database
self.replace_object(obj)
# Return object handle
return obj | python | def upsert_object_property(self, identifier, properties, ignore_constraints=False):
"""Manipulate an object's property set. Inserts or updates properties in
given dictionary. If a property key does not exist in the object's
property set it is created. If the value is None an existing property is
deleted.
Existing object properties that are not present in the given property
set remain unaffacted.
Deleting mandatory properties or updating immutable properties results
in a ValueError. These constraints can be disabled using the
ignore_constraints parameter.
Parameters
----------
identifier : string
Unique object identifier
properties : Dictionary()
Dictionary of property names and their new values.
ignore_constraints : Boolean
Flag indicating whether to ignore immutable and mandatory property
constraints (True) or nore (False, Default).
Returns
-------
ObjectHandle
Handle to updated object or None if object does not exist
"""
# Retrieve the object with the gievn identifier. This is a (sub-)class
# of ObjectHandle
obj = self.get_object(identifier)
if not obj is None:
# Modify property set of retrieved object handle. Raise exception if
# and of the upserts is not valid.
for key in properties:
value = properties[key]
# If the update affects an immutable property raise exception
if not ignore_constraints and key in self.immutable_properties:
raise ValueError('update to immutable property: ' + key)
# Check whether the operation is an UPSERT (value != None) or
# DELETE (value == None)
if not value is None:
obj.properties[key] = value
else:
# DELETE. Make sure the property is not mandatory
if not ignore_constraints and key in self.mandatory_properties:
raise ValueError('delete mandatory property: ' + key)
elif key in obj.properties:
del obj.properties[key]
# Update object in database
self.replace_object(obj)
# Return object handle
return obj | [
"def",
"upsert_object_property",
"(",
"self",
",",
"identifier",
",",
"properties",
",",
"ignore_constraints",
"=",
"False",
")",
":",
"# Retrieve the object with the gievn identifier. This is a (sub-)class",
"# of ObjectHandle",
"obj",
"=",
"self",
".",
"get_object",
"(",
"identifier",
")",
"if",
"not",
"obj",
"is",
"None",
":",
"# Modify property set of retrieved object handle. Raise exception if",
"# and of the upserts is not valid.",
"for",
"key",
"in",
"properties",
":",
"value",
"=",
"properties",
"[",
"key",
"]",
"# If the update affects an immutable property raise exception",
"if",
"not",
"ignore_constraints",
"and",
"key",
"in",
"self",
".",
"immutable_properties",
":",
"raise",
"ValueError",
"(",
"'update to immutable property: '",
"+",
"key",
")",
"# Check whether the operation is an UPSERT (value != None) or",
"# DELETE (value == None)",
"if",
"not",
"value",
"is",
"None",
":",
"obj",
".",
"properties",
"[",
"key",
"]",
"=",
"value",
"else",
":",
"# DELETE. Make sure the property is not mandatory",
"if",
"not",
"ignore_constraints",
"and",
"key",
"in",
"self",
".",
"mandatory_properties",
":",
"raise",
"ValueError",
"(",
"'delete mandatory property: '",
"+",
"key",
")",
"elif",
"key",
"in",
"obj",
".",
"properties",
":",
"del",
"obj",
".",
"properties",
"[",
"key",
"]",
"# Update object in database",
"self",
".",
"replace_object",
"(",
"obj",
")",
"# Return object handle",
"return",
"obj"
] | Manipulate an object's property set. Inserts or updates properties in
given dictionary. If a property key does not exist in the object's
property set it is created. If the value is None an existing property is
deleted.
Existing object properties that are not present in the given property
set remain unaffacted.
Deleting mandatory properties or updating immutable properties results
in a ValueError. These constraints can be disabled using the
ignore_constraints parameter.
Parameters
----------
identifier : string
Unique object identifier
properties : Dictionary()
Dictionary of property names and their new values.
ignore_constraints : Boolean
Flag indicating whether to ignore immutable and mandatory property
constraints (True) or nore (False, Default).
Returns
-------
ObjectHandle
Handle to updated object or None if object does not exist | [
"Manipulate",
"an",
"object",
"s",
"property",
"set",
".",
"Inserts",
"or",
"updates",
"properties",
"in",
"given",
"dictionary",
".",
"If",
"a",
"property",
"key",
"does",
"not",
"exist",
"in",
"the",
"object",
"s",
"property",
"set",
"it",
"is",
"created",
".",
"If",
"the",
"value",
"is",
"None",
"an",
"existing",
"property",
"is",
"deleted",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/datastore.py#L334-L386 |
246,783 | heikomuller/sco-datastore | scodata/datastore.py | MongoDBStore.delete_object | def delete_object(self, identifier, erase=False):
"""Delete the entry with given identifier in the database. Returns the
handle for the deleted object or None if object identifier is unknown.
If the read-only property of the object is set to true a ValueError is
raised.
Parameters
----------
identifier : string
Unique object identifier
erase : Boolean, optinal
If true, the record will be deleted from the database. Otherwise,
the active flag will be set to False to support provenance tracking.
Returns
-------
(Sub-class of)ObjectHandle
"""
# Get object to ensure that it exists.
db_object = self.get_object(identifier)
# Set active flag to False if object exists.
if db_object is None:
return None
# Check whether the read-only property is set to true
if PROPERTY_READONLY in db_object.properties:
if db_object.properties[PROPERTY_READONLY]:
raise ValueError('cannot delete read-only resource')
if erase:
# Erase object from database
self.collection.delete_many({"_id": identifier})
else:
# Delete object with given identifier by setting active flag
# to False
self.collection.update_one({"_id": identifier}, {'$set' : {'active' : False}})
# Return retrieved object or None if it didn't exist.
return db_object | python | def delete_object(self, identifier, erase=False):
"""Delete the entry with given identifier in the database. Returns the
handle for the deleted object or None if object identifier is unknown.
If the read-only property of the object is set to true a ValueError is
raised.
Parameters
----------
identifier : string
Unique object identifier
erase : Boolean, optinal
If true, the record will be deleted from the database. Otherwise,
the active flag will be set to False to support provenance tracking.
Returns
-------
(Sub-class of)ObjectHandle
"""
# Get object to ensure that it exists.
db_object = self.get_object(identifier)
# Set active flag to False if object exists.
if db_object is None:
return None
# Check whether the read-only property is set to true
if PROPERTY_READONLY in db_object.properties:
if db_object.properties[PROPERTY_READONLY]:
raise ValueError('cannot delete read-only resource')
if erase:
# Erase object from database
self.collection.delete_many({"_id": identifier})
else:
# Delete object with given identifier by setting active flag
# to False
self.collection.update_one({"_id": identifier}, {'$set' : {'active' : False}})
# Return retrieved object or None if it didn't exist.
return db_object | [
"def",
"delete_object",
"(",
"self",
",",
"identifier",
",",
"erase",
"=",
"False",
")",
":",
"# Get object to ensure that it exists.",
"db_object",
"=",
"self",
".",
"get_object",
"(",
"identifier",
")",
"# Set active flag to False if object exists.",
"if",
"db_object",
"is",
"None",
":",
"return",
"None",
"# Check whether the read-only property is set to true",
"if",
"PROPERTY_READONLY",
"in",
"db_object",
".",
"properties",
":",
"if",
"db_object",
".",
"properties",
"[",
"PROPERTY_READONLY",
"]",
":",
"raise",
"ValueError",
"(",
"'cannot delete read-only resource'",
")",
"if",
"erase",
":",
"# Erase object from database",
"self",
".",
"collection",
".",
"delete_many",
"(",
"{",
"\"_id\"",
":",
"identifier",
"}",
")",
"else",
":",
"# Delete object with given identifier by setting active flag",
"# to False",
"self",
".",
"collection",
".",
"update_one",
"(",
"{",
"\"_id\"",
":",
"identifier",
"}",
",",
"{",
"'$set'",
":",
"{",
"'active'",
":",
"False",
"}",
"}",
")",
"# Return retrieved object or None if it didn't exist.",
"return",
"db_object"
] | Delete the entry with given identifier in the database. Returns the
handle for the deleted object or None if object identifier is unknown.
If the read-only property of the object is set to true a ValueError is
raised.
Parameters
----------
identifier : string
Unique object identifier
erase : Boolean, optinal
If true, the record will be deleted from the database. Otherwise,
the active flag will be set to False to support provenance tracking.
Returns
-------
(Sub-class of)ObjectHandle | [
"Delete",
"the",
"entry",
"with",
"given",
"identifier",
"in",
"the",
"database",
".",
"Returns",
"the",
"handle",
"for",
"the",
"deleted",
"object",
"or",
"None",
"if",
"object",
"identifier",
"is",
"unknown",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/datastore.py#L418-L454 |
246,784 | heikomuller/sco-datastore | scodata/datastore.py | MongoDBStore.get_object | def get_object(self, identifier, include_inactive=False):
"""Retrieve object with given identifier from the database.
Parameters
----------
identifier : string
Unique object identifier
include_inactive : Boolean
Flag indicating whether inactive (i.e., deleted) object should be
included in the search (i.e., return an object with given
identifier if it has been deleted or return None)
Returns
-------
(Sub-class of)ObjectHandle
The database object with given identifier or None if no object
with identifier exists.
"""
# Find all objects with given identifier. The result size is expected
# to be zero or one
query = {'_id': identifier}
if not include_inactive:
query['active'] = True
cursor = self.collection.find(query)
if cursor.count() > 0:
return self.from_dict(cursor.next())
else:
return None | python | def get_object(self, identifier, include_inactive=False):
"""Retrieve object with given identifier from the database.
Parameters
----------
identifier : string
Unique object identifier
include_inactive : Boolean
Flag indicating whether inactive (i.e., deleted) object should be
included in the search (i.e., return an object with given
identifier if it has been deleted or return None)
Returns
-------
(Sub-class of)ObjectHandle
The database object with given identifier or None if no object
with identifier exists.
"""
# Find all objects with given identifier. The result size is expected
# to be zero or one
query = {'_id': identifier}
if not include_inactive:
query['active'] = True
cursor = self.collection.find(query)
if cursor.count() > 0:
return self.from_dict(cursor.next())
else:
return None | [
"def",
"get_object",
"(",
"self",
",",
"identifier",
",",
"include_inactive",
"=",
"False",
")",
":",
"# Find all objects with given identifier. The result size is expected",
"# to be zero or one",
"query",
"=",
"{",
"'_id'",
":",
"identifier",
"}",
"if",
"not",
"include_inactive",
":",
"query",
"[",
"'active'",
"]",
"=",
"True",
"cursor",
"=",
"self",
".",
"collection",
".",
"find",
"(",
"query",
")",
"if",
"cursor",
".",
"count",
"(",
")",
">",
"0",
":",
"return",
"self",
".",
"from_dict",
"(",
"cursor",
".",
"next",
"(",
")",
")",
"else",
":",
"return",
"None"
] | Retrieve object with given identifier from the database.
Parameters
----------
identifier : string
Unique object identifier
include_inactive : Boolean
Flag indicating whether inactive (i.e., deleted) object should be
included in the search (i.e., return an object with given
identifier if it has been deleted or return None)
Returns
-------
(Sub-class of)ObjectHandle
The database object with given identifier or None if no object
with identifier exists. | [
"Retrieve",
"object",
"with",
"given",
"identifier",
"from",
"the",
"database",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/datastore.py#L488-L515 |
246,785 | heikomuller/sco-datastore | scodata/datastore.py | MongoDBStore.insert_object | def insert_object(self, db_object):
"""Create new entry in the database.
Parameters
----------
db_object : (Sub-class of)ObjectHandle
"""
# Create object using the to_dict() method.
obj = self.to_dict(db_object)
obj['active'] = True
self.collection.insert_one(obj) | python | def insert_object(self, db_object):
"""Create new entry in the database.
Parameters
----------
db_object : (Sub-class of)ObjectHandle
"""
# Create object using the to_dict() method.
obj = self.to_dict(db_object)
obj['active'] = True
self.collection.insert_one(obj) | [
"def",
"insert_object",
"(",
"self",
",",
"db_object",
")",
":",
"# Create object using the to_dict() method.",
"obj",
"=",
"self",
".",
"to_dict",
"(",
"db_object",
")",
"obj",
"[",
"'active'",
"]",
"=",
"True",
"self",
".",
"collection",
".",
"insert_one",
"(",
"obj",
")"
] | Create new entry in the database.
Parameters
----------
db_object : (Sub-class of)ObjectHandle | [
"Create",
"new",
"entry",
"in",
"the",
"database",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/datastore.py#L517-L527 |
246,786 | heikomuller/sco-datastore | scodata/datastore.py | MongoDBStore.list_objects | def list_objects(self, query=None, limit=-1, offset=-1):
"""List of all objects in the database. Optinal parameter limit and
offset for pagination. A dictionary of key,value-pairs can be given as
addictional query condition for document properties.
Parameters
----------
query : Dictionary
Filter objects by property-value pairs defined by dictionary.
limit : int
Limit number of items in the result set
offset : int
Set offset in list (order as defined by object store)
Returns
-------
ObjectListing
"""
result = []
# Build the document query
doc = {'active' : True}
if not query is None:
for key in query:
doc[key] = query[key]
# Iterate over all objects in the MongoDB collection and add them to
# the result
coll = self.collection.find(doc).sort([('timestamp', pymongo.DESCENDING)])
count = 0
for document in coll:
# We are done if the limit is reached. Test first in case limit is
# zero.
if limit >= 0 and len(result) == limit:
break
if offset < 0 or count >= offset:
result.append(self.from_dict(document))
count += 1
return ObjectListing(result, offset, limit, coll.count()) | python | def list_objects(self, query=None, limit=-1, offset=-1):
"""List of all objects in the database. Optinal parameter limit and
offset for pagination. A dictionary of key,value-pairs can be given as
addictional query condition for document properties.
Parameters
----------
query : Dictionary
Filter objects by property-value pairs defined by dictionary.
limit : int
Limit number of items in the result set
offset : int
Set offset in list (order as defined by object store)
Returns
-------
ObjectListing
"""
result = []
# Build the document query
doc = {'active' : True}
if not query is None:
for key in query:
doc[key] = query[key]
# Iterate over all objects in the MongoDB collection and add them to
# the result
coll = self.collection.find(doc).sort([('timestamp', pymongo.DESCENDING)])
count = 0
for document in coll:
# We are done if the limit is reached. Test first in case limit is
# zero.
if limit >= 0 and len(result) == limit:
break
if offset < 0 or count >= offset:
result.append(self.from_dict(document))
count += 1
return ObjectListing(result, offset, limit, coll.count()) | [
"def",
"list_objects",
"(",
"self",
",",
"query",
"=",
"None",
",",
"limit",
"=",
"-",
"1",
",",
"offset",
"=",
"-",
"1",
")",
":",
"result",
"=",
"[",
"]",
"# Build the document query",
"doc",
"=",
"{",
"'active'",
":",
"True",
"}",
"if",
"not",
"query",
"is",
"None",
":",
"for",
"key",
"in",
"query",
":",
"doc",
"[",
"key",
"]",
"=",
"query",
"[",
"key",
"]",
"# Iterate over all objects in the MongoDB collection and add them to",
"# the result",
"coll",
"=",
"self",
".",
"collection",
".",
"find",
"(",
"doc",
")",
".",
"sort",
"(",
"[",
"(",
"'timestamp'",
",",
"pymongo",
".",
"DESCENDING",
")",
"]",
")",
"count",
"=",
"0",
"for",
"document",
"in",
"coll",
":",
"# We are done if the limit is reached. Test first in case limit is",
"# zero.",
"if",
"limit",
">=",
"0",
"and",
"len",
"(",
"result",
")",
"==",
"limit",
":",
"break",
"if",
"offset",
"<",
"0",
"or",
"count",
">=",
"offset",
":",
"result",
".",
"append",
"(",
"self",
".",
"from_dict",
"(",
"document",
")",
")",
"count",
"+=",
"1",
"return",
"ObjectListing",
"(",
"result",
",",
"offset",
",",
"limit",
",",
"coll",
".",
"count",
"(",
")",
")"
] | List of all objects in the database. Optinal parameter limit and
offset for pagination. A dictionary of key,value-pairs can be given as
addictional query condition for document properties.
Parameters
----------
query : Dictionary
Filter objects by property-value pairs defined by dictionary.
limit : int
Limit number of items in the result set
offset : int
Set offset in list (order as defined by object store)
Returns
-------
ObjectListing | [
"List",
"of",
"all",
"objects",
"in",
"the",
"database",
".",
"Optinal",
"parameter",
"limit",
"and",
"offset",
"for",
"pagination",
".",
"A",
"dictionary",
"of",
"key",
"value",
"-",
"pairs",
"can",
"be",
"given",
"as",
"addictional",
"query",
"condition",
"for",
"document",
"properties",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/datastore.py#L529-L565 |
246,787 | heikomuller/sco-datastore | scodata/datastore.py | MongoDBStore.to_dict | def to_dict(self, db_obj):
"""Create a Json-like dictionary for objects managed by this object
store.
Parameters
----------
db_obj : (Sub-class of)ObjectHandle
Returns
-------
(JSON)
Json-like object, i.e., dictionary.
"""
# Base Json serialization for database objects
return {
'_id' : db_obj.identifier,
'timestamp' : str(db_obj.timestamp.isoformat()),
'properties' : db_obj.properties} | python | def to_dict(self, db_obj):
"""Create a Json-like dictionary for objects managed by this object
store.
Parameters
----------
db_obj : (Sub-class of)ObjectHandle
Returns
-------
(JSON)
Json-like object, i.e., dictionary.
"""
# Base Json serialization for database objects
return {
'_id' : db_obj.identifier,
'timestamp' : str(db_obj.timestamp.isoformat()),
'properties' : db_obj.properties} | [
"def",
"to_dict",
"(",
"self",
",",
"db_obj",
")",
":",
"# Base Json serialization for database objects",
"return",
"{",
"'_id'",
":",
"db_obj",
".",
"identifier",
",",
"'timestamp'",
":",
"str",
"(",
"db_obj",
".",
"timestamp",
".",
"isoformat",
"(",
")",
")",
",",
"'properties'",
":",
"db_obj",
".",
"properties",
"}"
] | Create a Json-like dictionary for objects managed by this object
store.
Parameters
----------
db_obj : (Sub-class of)ObjectHandle
Returns
-------
(JSON)
Json-like object, i.e., dictionary. | [
"Create",
"a",
"Json",
"-",
"like",
"dictionary",
"for",
"objects",
"managed",
"by",
"this",
"object",
"store",
"."
] | 7180a6b51150667e47629da566aedaa742e39342 | https://github.com/heikomuller/sco-datastore/blob/7180a6b51150667e47629da566aedaa742e39342/scodata/datastore.py#L582-L599 |
246,788 | praekeltfoundation/seed-service-rating | ratings/tasks.py | SendInviteMessage.compile_msg_payload | def compile_msg_payload(self, invite):
""" Determine recipient, message content, return it as
a dict that can be Posted to the message sender
"""
self.l.info("Compiling the outbound message payload")
update_invite = False
# Determine the recipient address
if "to_addr" in invite.invite:
to_addr = invite.invite["to_addr"]
else:
update_invite = True
to_addr = get_identity_address(invite.identity)
# Determine the message content
if "content" in invite.invite:
content = invite.invite["content"]
else:
update_invite = True
content = settings.INVITE_TEXT
# Determine the metadata
if "metadata" in invite.invite:
metadata = invite.invite["metadata"]
else:
update_invite = True
metadata = {}
msg_payload = {
"to_addr": to_addr,
"content": content,
"metadata": metadata
}
if update_invite is True:
self.l.info("Updating the invite.invite field")
invite.invite = msg_payload
invite.save()
self.l.info("Compiled the outbound message payload")
return msg_payload | python | def compile_msg_payload(self, invite):
""" Determine recipient, message content, return it as
a dict that can be Posted to the message sender
"""
self.l.info("Compiling the outbound message payload")
update_invite = False
# Determine the recipient address
if "to_addr" in invite.invite:
to_addr = invite.invite["to_addr"]
else:
update_invite = True
to_addr = get_identity_address(invite.identity)
# Determine the message content
if "content" in invite.invite:
content = invite.invite["content"]
else:
update_invite = True
content = settings.INVITE_TEXT
# Determine the metadata
if "metadata" in invite.invite:
metadata = invite.invite["metadata"]
else:
update_invite = True
metadata = {}
msg_payload = {
"to_addr": to_addr,
"content": content,
"metadata": metadata
}
if update_invite is True:
self.l.info("Updating the invite.invite field")
invite.invite = msg_payload
invite.save()
self.l.info("Compiled the outbound message payload")
return msg_payload | [
"def",
"compile_msg_payload",
"(",
"self",
",",
"invite",
")",
":",
"self",
".",
"l",
".",
"info",
"(",
"\"Compiling the outbound message payload\"",
")",
"update_invite",
"=",
"False",
"# Determine the recipient address",
"if",
"\"to_addr\"",
"in",
"invite",
".",
"invite",
":",
"to_addr",
"=",
"invite",
".",
"invite",
"[",
"\"to_addr\"",
"]",
"else",
":",
"update_invite",
"=",
"True",
"to_addr",
"=",
"get_identity_address",
"(",
"invite",
".",
"identity",
")",
"# Determine the message content",
"if",
"\"content\"",
"in",
"invite",
".",
"invite",
":",
"content",
"=",
"invite",
".",
"invite",
"[",
"\"content\"",
"]",
"else",
":",
"update_invite",
"=",
"True",
"content",
"=",
"settings",
".",
"INVITE_TEXT",
"# Determine the metadata",
"if",
"\"metadata\"",
"in",
"invite",
".",
"invite",
":",
"metadata",
"=",
"invite",
".",
"invite",
"[",
"\"metadata\"",
"]",
"else",
":",
"update_invite",
"=",
"True",
"metadata",
"=",
"{",
"}",
"msg_payload",
"=",
"{",
"\"to_addr\"",
":",
"to_addr",
",",
"\"content\"",
":",
"content",
",",
"\"metadata\"",
":",
"metadata",
"}",
"if",
"update_invite",
"is",
"True",
":",
"self",
".",
"l",
".",
"info",
"(",
"\"Updating the invite.invite field\"",
")",
"invite",
".",
"invite",
"=",
"msg_payload",
"invite",
".",
"save",
"(",
")",
"self",
".",
"l",
".",
"info",
"(",
"\"Compiled the outbound message payload\"",
")",
"return",
"msg_payload"
] | Determine recipient, message content, return it as
a dict that can be Posted to the message sender | [
"Determine",
"recipient",
"message",
"content",
"return",
"it",
"as",
"a",
"dict",
"that",
"can",
"be",
"Posted",
"to",
"the",
"message",
"sender"
] | 73f7974a5bcb6e1f32a756be5274b200084c2670 | https://github.com/praekeltfoundation/seed-service-rating/blob/73f7974a5bcb6e1f32a756be5274b200084c2670/ratings/tasks.py#L60-L100 |
246,789 | praekeltfoundation/seed-service-rating | ratings/tasks.py | SendInviteMessage.send_message | def send_message(self, payload):
""" Create a post request to the message sender
"""
self.l.info("Creating outbound message request")
result = ms_client.create_outbound(payload)
self.l.info("Created outbound message request")
return result | python | def send_message(self, payload):
""" Create a post request to the message sender
"""
self.l.info("Creating outbound message request")
result = ms_client.create_outbound(payload)
self.l.info("Created outbound message request")
return result | [
"def",
"send_message",
"(",
"self",
",",
"payload",
")",
":",
"self",
".",
"l",
".",
"info",
"(",
"\"Creating outbound message request\"",
")",
"result",
"=",
"ms_client",
".",
"create_outbound",
"(",
"payload",
")",
"self",
".",
"l",
".",
"info",
"(",
"\"Created outbound message request\"",
")",
"return",
"result"
] | Create a post request to the message sender | [
"Create",
"a",
"post",
"request",
"to",
"the",
"message",
"sender"
] | 73f7974a5bcb6e1f32a756be5274b200084c2670 | https://github.com/praekeltfoundation/seed-service-rating/blob/73f7974a5bcb6e1f32a756be5274b200084c2670/ratings/tasks.py#L102-L108 |
246,790 | praekeltfoundation/seed-service-rating | ratings/tasks.py | SendInviteMessage.run | def run(self, invite_id, **kwargs):
""" Sends a message about service rating to invitee
"""
self.l = self.get_logger(**kwargs)
self.l.info("Looking up the invite")
invite = Invite.objects.get(id=invite_id)
msg_payload = self.compile_msg_payload(invite)
result = self.send_message(msg_payload)
self.l.info("Creating task to update invite after send")
post_send_update_invite.apply_async(args=[invite_id])
self.l.info("Created task to update invite after send")
return "Message queued for send. ID: <%s>" % str(result["id"]) | python | def run(self, invite_id, **kwargs):
""" Sends a message about service rating to invitee
"""
self.l = self.get_logger(**kwargs)
self.l.info("Looking up the invite")
invite = Invite.objects.get(id=invite_id)
msg_payload = self.compile_msg_payload(invite)
result = self.send_message(msg_payload)
self.l.info("Creating task to update invite after send")
post_send_update_invite.apply_async(args=[invite_id])
self.l.info("Created task to update invite after send")
return "Message queued for send. ID: <%s>" % str(result["id"]) | [
"def",
"run",
"(",
"self",
",",
"invite_id",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"l",
"=",
"self",
".",
"get_logger",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"l",
".",
"info",
"(",
"\"Looking up the invite\"",
")",
"invite",
"=",
"Invite",
".",
"objects",
".",
"get",
"(",
"id",
"=",
"invite_id",
")",
"msg_payload",
"=",
"self",
".",
"compile_msg_payload",
"(",
"invite",
")",
"result",
"=",
"self",
".",
"send_message",
"(",
"msg_payload",
")",
"self",
".",
"l",
".",
"info",
"(",
"\"Creating task to update invite after send\"",
")",
"post_send_update_invite",
".",
"apply_async",
"(",
"args",
"=",
"[",
"invite_id",
"]",
")",
"self",
".",
"l",
".",
"info",
"(",
"\"Created task to update invite after send\"",
")",
"return",
"\"Message queued for send. ID: <%s>\"",
"%",
"str",
"(",
"result",
"[",
"\"id\"",
"]",
")"
] | Sends a message about service rating to invitee | [
"Sends",
"a",
"message",
"about",
"service",
"rating",
"to",
"invitee"
] | 73f7974a5bcb6e1f32a756be5274b200084c2670 | https://github.com/praekeltfoundation/seed-service-rating/blob/73f7974a5bcb6e1f32a756be5274b200084c2670/ratings/tasks.py#L110-L121 |
246,791 | praekelt/vumi-http-api | vumi_http_api/concurrency_limiter.py | ConcurrencyLimitManager.stop | def stop(self, key):
"""
Stop a concurrent operation.
This gets the concurrency limiter for the given key (creating it if
necessary) and stops a concurrent operation on it. If the concurrency
limiter is empty, it is deleted.
"""
self._get_limiter(key).stop()
self._cleanup_limiter(key) | python | def stop(self, key):
"""
Stop a concurrent operation.
This gets the concurrency limiter for the given key (creating it if
necessary) and stops a concurrent operation on it. If the concurrency
limiter is empty, it is deleted.
"""
self._get_limiter(key).stop()
self._cleanup_limiter(key) | [
"def",
"stop",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"_get_limiter",
"(",
"key",
")",
".",
"stop",
"(",
")",
"self",
".",
"_cleanup_limiter",
"(",
"key",
")"
] | Stop a concurrent operation.
This gets the concurrency limiter for the given key (creating it if
necessary) and stops a concurrent operation on it. If the concurrency
limiter is empty, it is deleted. | [
"Stop",
"a",
"concurrent",
"operation",
"."
] | 0d7cf1cb71794c93272c19095cf8c37f4c250a59 | https://github.com/praekelt/vumi-http-api/blob/0d7cf1cb71794c93272c19095cf8c37f4c250a59/vumi_http_api/concurrency_limiter.py#L143-L152 |
246,792 | minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | fields_for | def fields_for(context, form, template="includes/form_fields.html"):
"""
Renders fields for a form with an optional template choice.
"""
context["form_for_fields"] = form
return get_template(template).render(context) | python | def fields_for(context, form, template="includes/form_fields.html"):
"""
Renders fields for a form with an optional template choice.
"""
context["form_for_fields"] = form
return get_template(template).render(context) | [
"def",
"fields_for",
"(",
"context",
",",
"form",
",",
"template",
"=",
"\"includes/form_fields.html\"",
")",
":",
"context",
"[",
"\"form_for_fields\"",
"]",
"=",
"form",
"return",
"get_template",
"(",
"template",
")",
".",
"render",
"(",
"context",
")"
] | Renders fields for a form with an optional template choice. | [
"Renders",
"fields",
"for",
"a",
"form",
"with",
"an",
"optional",
"template",
"choice",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L104-L109 |
246,793 | minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | sort_by | def sort_by(items, attr):
"""
General sort filter - sorts by either attribute or key.
"""
def key_func(item):
try:
return getattr(item, attr)
except AttributeError:
try:
return item[attr]
except TypeError:
getattr(item, attr) # Reraise AttributeError
return sorted(items, key=key_func) | python | def sort_by(items, attr):
"""
General sort filter - sorts by either attribute or key.
"""
def key_func(item):
try:
return getattr(item, attr)
except AttributeError:
try:
return item[attr]
except TypeError:
getattr(item, attr) # Reraise AttributeError
return sorted(items, key=key_func) | [
"def",
"sort_by",
"(",
"items",
",",
"attr",
")",
":",
"def",
"key_func",
"(",
"item",
")",
":",
"try",
":",
"return",
"getattr",
"(",
"item",
",",
"attr",
")",
"except",
"AttributeError",
":",
"try",
":",
"return",
"item",
"[",
"attr",
"]",
"except",
"TypeError",
":",
"getattr",
"(",
"item",
",",
"attr",
")",
"# Reraise AttributeError",
"return",
"sorted",
"(",
"items",
",",
"key",
"=",
"key_func",
")"
] | General sort filter - sorts by either attribute or key. | [
"General",
"sort",
"filter",
"-",
"sorts",
"by",
"either",
"attribute",
"or",
"key",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L121-L133 |
246,794 | minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | gravatar_url | def gravatar_url(email, size=32):
"""
Return the full URL for a Gravatar given an email hash.
"""
bits = (md5(email.lower().encode("utf-8")).hexdigest(), size)
return "//www.gravatar.com/avatar/%s?s=%s&d=identicon&r=PG" % bits | python | def gravatar_url(email, size=32):
"""
Return the full URL for a Gravatar given an email hash.
"""
bits = (md5(email.lower().encode("utf-8")).hexdigest(), size)
return "//www.gravatar.com/avatar/%s?s=%s&d=identicon&r=PG" % bits | [
"def",
"gravatar_url",
"(",
"email",
",",
"size",
"=",
"32",
")",
":",
"bits",
"=",
"(",
"md5",
"(",
"email",
".",
"lower",
"(",
")",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
".",
"hexdigest",
"(",
")",
",",
"size",
")",
"return",
"\"//www.gravatar.com/avatar/%s?s=%s&d=identicon&r=PG\"",
"%",
"bits"
] | Return the full URL for a Gravatar given an email hash. | [
"Return",
"the",
"full",
"URL",
"for",
"a",
"Gravatar",
"given",
"an",
"email",
"hash",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L203-L208 |
246,795 | minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | metablock | def metablock(parsed):
"""
Remove HTML tags, entities and superfluous characters from
meta blocks.
"""
parsed = " ".join(parsed.replace("\n", "").split()).replace(" ,", ",")
return escape(strip_tags(decode_entities(parsed))) | python | def metablock(parsed):
"""
Remove HTML tags, entities and superfluous characters from
meta blocks.
"""
parsed = " ".join(parsed.replace("\n", "").split()).replace(" ,", ",")
return escape(strip_tags(decode_entities(parsed))) | [
"def",
"metablock",
"(",
"parsed",
")",
":",
"parsed",
"=",
"\" \"",
".",
"join",
"(",
"parsed",
".",
"replace",
"(",
"\"\\n\"",
",",
"\"\"",
")",
".",
"split",
"(",
")",
")",
".",
"replace",
"(",
"\" ,\"",
",",
"\",\"",
")",
"return",
"escape",
"(",
"strip_tags",
"(",
"decode_entities",
"(",
"parsed",
")",
")",
")"
] | Remove HTML tags, entities and superfluous characters from
meta blocks. | [
"Remove",
"HTML",
"tags",
"entities",
"and",
"superfluous",
"characters",
"from",
"meta",
"blocks",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L212-L218 |
246,796 | minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | pagination_for | def pagination_for(context, current_page, page_var="page", exclude_vars=""):
"""
Include the pagination template and data for persisting querystring
in pagination links. Can also contain a comma separated string of
var names in the current querystring to exclude from the pagination
links, via the ``exclude_vars`` arg.
"""
querystring = context["request"].GET.copy()
exclude_vars = [v for v in exclude_vars.split(",") if v] + [page_var]
for exclude_var in exclude_vars:
if exclude_var in querystring:
del querystring[exclude_var]
querystring = querystring.urlencode()
return {
"current_page": current_page,
"querystring": querystring,
"page_var": page_var,
} | python | def pagination_for(context, current_page, page_var="page", exclude_vars=""):
"""
Include the pagination template and data for persisting querystring
in pagination links. Can also contain a comma separated string of
var names in the current querystring to exclude from the pagination
links, via the ``exclude_vars`` arg.
"""
querystring = context["request"].GET.copy()
exclude_vars = [v for v in exclude_vars.split(",") if v] + [page_var]
for exclude_var in exclude_vars:
if exclude_var in querystring:
del querystring[exclude_var]
querystring = querystring.urlencode()
return {
"current_page": current_page,
"querystring": querystring,
"page_var": page_var,
} | [
"def",
"pagination_for",
"(",
"context",
",",
"current_page",
",",
"page_var",
"=",
"\"page\"",
",",
"exclude_vars",
"=",
"\"\"",
")",
":",
"querystring",
"=",
"context",
"[",
"\"request\"",
"]",
".",
"GET",
".",
"copy",
"(",
")",
"exclude_vars",
"=",
"[",
"v",
"for",
"v",
"in",
"exclude_vars",
".",
"split",
"(",
"\",\"",
")",
"if",
"v",
"]",
"+",
"[",
"page_var",
"]",
"for",
"exclude_var",
"in",
"exclude_vars",
":",
"if",
"exclude_var",
"in",
"querystring",
":",
"del",
"querystring",
"[",
"exclude_var",
"]",
"querystring",
"=",
"querystring",
".",
"urlencode",
"(",
")",
"return",
"{",
"\"current_page\"",
":",
"current_page",
",",
"\"querystring\"",
":",
"querystring",
",",
"\"page_var\"",
":",
"page_var",
",",
"}"
] | Include the pagination template and data for persisting querystring
in pagination links. Can also contain a comma separated string of
var names in the current querystring to exclude from the pagination
links, via the ``exclude_vars`` arg. | [
"Include",
"the",
"pagination",
"template",
"and",
"data",
"for",
"persisting",
"querystring",
"in",
"pagination",
"links",
".",
"Can",
"also",
"contain",
"a",
"comma",
"separated",
"string",
"of",
"var",
"names",
"in",
"the",
"current",
"querystring",
"to",
"exclude",
"from",
"the",
"pagination",
"links",
"via",
"the",
"exclude_vars",
"arg",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L222-L239 |
246,797 | minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | search_form | def search_form(context, search_model_names=None):
"""
Includes the search form with a list of models to use as choices
for filtering the search by. Models should be a string with models
in the format ``app_label.model_name`` separated by spaces. The
string ``all`` can also be used, in which case the models defined
by the ``SEARCH_MODEL_CHOICES`` setting will be used.
"""
template_vars = {
"request": context["request"],
}
if not search_model_names or not settings.SEARCH_MODEL_CHOICES:
search_model_names = []
elif search_model_names == "all":
search_model_names = list(settings.SEARCH_MODEL_CHOICES)
else:
search_model_names = search_model_names.split(" ")
search_model_choices = []
for model_name in search_model_names:
try:
model = apps.get_model(*model_name.split(".", 1))
except LookupError:
pass
else:
verbose_name = model._meta.verbose_name_plural.capitalize()
search_model_choices.append((verbose_name, model_name))
template_vars["search_model_choices"] = sorted(search_model_choices)
return template_vars | python | def search_form(context, search_model_names=None):
"""
Includes the search form with a list of models to use as choices
for filtering the search by. Models should be a string with models
in the format ``app_label.model_name`` separated by spaces. The
string ``all`` can also be used, in which case the models defined
by the ``SEARCH_MODEL_CHOICES`` setting will be used.
"""
template_vars = {
"request": context["request"],
}
if not search_model_names or not settings.SEARCH_MODEL_CHOICES:
search_model_names = []
elif search_model_names == "all":
search_model_names = list(settings.SEARCH_MODEL_CHOICES)
else:
search_model_names = search_model_names.split(" ")
search_model_choices = []
for model_name in search_model_names:
try:
model = apps.get_model(*model_name.split(".", 1))
except LookupError:
pass
else:
verbose_name = model._meta.verbose_name_plural.capitalize()
search_model_choices.append((verbose_name, model_name))
template_vars["search_model_choices"] = sorted(search_model_choices)
return template_vars | [
"def",
"search_form",
"(",
"context",
",",
"search_model_names",
"=",
"None",
")",
":",
"template_vars",
"=",
"{",
"\"request\"",
":",
"context",
"[",
"\"request\"",
"]",
",",
"}",
"if",
"not",
"search_model_names",
"or",
"not",
"settings",
".",
"SEARCH_MODEL_CHOICES",
":",
"search_model_names",
"=",
"[",
"]",
"elif",
"search_model_names",
"==",
"\"all\"",
":",
"search_model_names",
"=",
"list",
"(",
"settings",
".",
"SEARCH_MODEL_CHOICES",
")",
"else",
":",
"search_model_names",
"=",
"search_model_names",
".",
"split",
"(",
"\" \"",
")",
"search_model_choices",
"=",
"[",
"]",
"for",
"model_name",
"in",
"search_model_names",
":",
"try",
":",
"model",
"=",
"apps",
".",
"get_model",
"(",
"*",
"model_name",
".",
"split",
"(",
"\".\"",
",",
"1",
")",
")",
"except",
"LookupError",
":",
"pass",
"else",
":",
"verbose_name",
"=",
"model",
".",
"_meta",
".",
"verbose_name_plural",
".",
"capitalize",
"(",
")",
"search_model_choices",
".",
"append",
"(",
"(",
"verbose_name",
",",
"model_name",
")",
")",
"template_vars",
"[",
"\"search_model_choices\"",
"]",
"=",
"sorted",
"(",
"search_model_choices",
")",
"return",
"template_vars"
] | Includes the search form with a list of models to use as choices
for filtering the search by. Models should be a string with models
in the format ``app_label.model_name`` separated by spaces. The
string ``all`` can also be used, in which case the models defined
by the ``SEARCH_MODEL_CHOICES`` setting will be used. | [
"Includes",
"the",
"search",
"form",
"with",
"a",
"list",
"of",
"models",
"to",
"use",
"as",
"choices",
"for",
"filtering",
"the",
"search",
"by",
".",
"Models",
"should",
"be",
"a",
"string",
"with",
"models",
"in",
"the",
"format",
"app_label",
".",
"model_name",
"separated",
"by",
"spaces",
".",
"The",
"string",
"all",
"can",
"also",
"be",
"used",
"in",
"which",
"case",
"the",
"models",
"defined",
"by",
"the",
"SEARCH_MODEL_CHOICES",
"setting",
"will",
"be",
"used",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L243-L270 |
246,798 | minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | richtext_filters | def richtext_filters(content):
"""
Takes a value edited via the WYSIWYG editor, and passes it through
each of the functions specified by the RICHTEXT_FILTERS setting.
"""
for filter_name in settings.RICHTEXT_FILTERS:
filter_func = import_dotted_path(filter_name)
content = filter_func(content)
return content | python | def richtext_filters(content):
"""
Takes a value edited via the WYSIWYG editor, and passes it through
each of the functions specified by the RICHTEXT_FILTERS setting.
"""
for filter_name in settings.RICHTEXT_FILTERS:
filter_func = import_dotted_path(filter_name)
content = filter_func(content)
return content | [
"def",
"richtext_filters",
"(",
"content",
")",
":",
"for",
"filter_name",
"in",
"settings",
".",
"RICHTEXT_FILTERS",
":",
"filter_func",
"=",
"import_dotted_path",
"(",
"filter_name",
")",
"content",
"=",
"filter_func",
"(",
"content",
")",
"return",
"content"
] | Takes a value edited via the WYSIWYG editor, and passes it through
each of the functions specified by the RICHTEXT_FILTERS setting. | [
"Takes",
"a",
"value",
"edited",
"via",
"the",
"WYSIWYG",
"editor",
"and",
"passes",
"it",
"through",
"each",
"of",
"the",
"functions",
"specified",
"by",
"the",
"RICHTEXT_FILTERS",
"setting",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L466-L474 |
246,799 | minhhoit/yacms | yacms/core/templatetags/yacms_tags.py | editable | def editable(parsed, context, token):
"""
Add the required HTML to the parsed content for in-line editing,
such as the icon and edit form if the object is deemed to be
editable - either it has an ``editable`` method which returns
``True``, or the logged in user has change permissions for the
model.
"""
def parse_field(field):
field = field.split(".")
obj = context.get(field.pop(0), None)
attr = field.pop()
while field:
obj = getattr(obj, field.pop(0))
if callable(obj):
# Allows {% editable page.get_content_model.content %}
obj = obj()
return obj, attr
fields = [parse_field(f) for f in token.split_contents()[1:]]
if fields:
fields = [f for f in fields if len(f) == 2 and f[0] is fields[0][0]]
if not parsed.strip():
try:
parsed = "".join([str(getattr(*field)) for field in fields])
except AttributeError:
pass
if settings.INLINE_EDITING_ENABLED and fields and "request" in context:
obj = fields[0][0]
if isinstance(obj, Model) and is_editable(obj, context["request"]):
field_names = ",".join([f[1] for f in fields])
context["editable_form"] = get_edit_form(obj, field_names)
context["original"] = parsed
t = get_template("includes/editable_form.html")
return t.render(context)
return parsed | python | def editable(parsed, context, token):
"""
Add the required HTML to the parsed content for in-line editing,
such as the icon and edit form if the object is deemed to be
editable - either it has an ``editable`` method which returns
``True``, or the logged in user has change permissions for the
model.
"""
def parse_field(field):
field = field.split(".")
obj = context.get(field.pop(0), None)
attr = field.pop()
while field:
obj = getattr(obj, field.pop(0))
if callable(obj):
# Allows {% editable page.get_content_model.content %}
obj = obj()
return obj, attr
fields = [parse_field(f) for f in token.split_contents()[1:]]
if fields:
fields = [f for f in fields if len(f) == 2 and f[0] is fields[0][0]]
if not parsed.strip():
try:
parsed = "".join([str(getattr(*field)) for field in fields])
except AttributeError:
pass
if settings.INLINE_EDITING_ENABLED and fields and "request" in context:
obj = fields[0][0]
if isinstance(obj, Model) and is_editable(obj, context["request"]):
field_names = ",".join([f[1] for f in fields])
context["editable_form"] = get_edit_form(obj, field_names)
context["original"] = parsed
t = get_template("includes/editable_form.html")
return t.render(context)
return parsed | [
"def",
"editable",
"(",
"parsed",
",",
"context",
",",
"token",
")",
":",
"def",
"parse_field",
"(",
"field",
")",
":",
"field",
"=",
"field",
".",
"split",
"(",
"\".\"",
")",
"obj",
"=",
"context",
".",
"get",
"(",
"field",
".",
"pop",
"(",
"0",
")",
",",
"None",
")",
"attr",
"=",
"field",
".",
"pop",
"(",
")",
"while",
"field",
":",
"obj",
"=",
"getattr",
"(",
"obj",
",",
"field",
".",
"pop",
"(",
"0",
")",
")",
"if",
"callable",
"(",
"obj",
")",
":",
"# Allows {% editable page.get_content_model.content %}",
"obj",
"=",
"obj",
"(",
")",
"return",
"obj",
",",
"attr",
"fields",
"=",
"[",
"parse_field",
"(",
"f",
")",
"for",
"f",
"in",
"token",
".",
"split_contents",
"(",
")",
"[",
"1",
":",
"]",
"]",
"if",
"fields",
":",
"fields",
"=",
"[",
"f",
"for",
"f",
"in",
"fields",
"if",
"len",
"(",
"f",
")",
"==",
"2",
"and",
"f",
"[",
"0",
"]",
"is",
"fields",
"[",
"0",
"]",
"[",
"0",
"]",
"]",
"if",
"not",
"parsed",
".",
"strip",
"(",
")",
":",
"try",
":",
"parsed",
"=",
"\"\"",
".",
"join",
"(",
"[",
"str",
"(",
"getattr",
"(",
"*",
"field",
")",
")",
"for",
"field",
"in",
"fields",
"]",
")",
"except",
"AttributeError",
":",
"pass",
"if",
"settings",
".",
"INLINE_EDITING_ENABLED",
"and",
"fields",
"and",
"\"request\"",
"in",
"context",
":",
"obj",
"=",
"fields",
"[",
"0",
"]",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"obj",
",",
"Model",
")",
"and",
"is_editable",
"(",
"obj",
",",
"context",
"[",
"\"request\"",
"]",
")",
":",
"field_names",
"=",
"\",\"",
".",
"join",
"(",
"[",
"f",
"[",
"1",
"]",
"for",
"f",
"in",
"fields",
"]",
")",
"context",
"[",
"\"editable_form\"",
"]",
"=",
"get_edit_form",
"(",
"obj",
",",
"field_names",
")",
"context",
"[",
"\"original\"",
"]",
"=",
"parsed",
"t",
"=",
"get_template",
"(",
"\"includes/editable_form.html\"",
")",
"return",
"t",
".",
"render",
"(",
"context",
")",
"return",
"parsed"
] | Add the required HTML to the parsed content for in-line editing,
such as the icon and edit form if the object is deemed to be
editable - either it has an ``editable`` method which returns
``True``, or the logged in user has change permissions for the
model. | [
"Add",
"the",
"required",
"HTML",
"to",
"the",
"parsed",
"content",
"for",
"in",
"-",
"line",
"editing",
"such",
"as",
"the",
"icon",
"and",
"edit",
"form",
"if",
"the",
"object",
"is",
"deemed",
"to",
"be",
"editable",
"-",
"either",
"it",
"has",
"an",
"editable",
"method",
"which",
"returns",
"True",
"or",
"the",
"logged",
"in",
"user",
"has",
"change",
"permissions",
"for",
"the",
"model",
"."
] | 2921b706b7107c6e8c5f2bbf790ff11f85a2167f | https://github.com/minhhoit/yacms/blob/2921b706b7107c6e8c5f2bbf790ff11f85a2167f/yacms/core/templatetags/yacms_tags.py#L478-L514 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.