body_hash
stringlengths 64
64
| body
stringlengths 23
109k
| docstring
stringlengths 1
57k
| path
stringlengths 4
198
| name
stringlengths 1
115
| repository_name
stringlengths 7
111
| repository_stars
float64 0
191k
| lang
stringclasses 1
value | body_without_docstring
stringlengths 14
108k
| unified
stringlengths 45
133k
|
|---|---|---|---|---|---|---|---|---|---|
d7adfbc3b920df9bddf2be5cab3ba2d0179a29ce5eb43cbf5f9831b19755cc68
|
def contents(path, type=None, default=None):
'\n Return the contents of file *path* as *type* (string [default], or list)\n '
try:
with open(path, 'r') as f:
if (type == list):
rv = f.readlines()
else:
rv = f.read()
except IOError as e:
if (default is not None):
rv = default
else:
raise
return rv
|
Return the contents of file *path* as *type* (string [default], or list)
|
gitr/tbx.py
|
contents
|
tbarron/gitr
| 0
|
python
|
def contents(path, type=None, default=None):
'\n \n '
try:
with open(path, 'r') as f:
if (type == list):
rv = f.readlines()
else:
rv = f.read()
except IOError as e:
if (default is not None):
rv = default
else:
raise
return rv
|
def contents(path, type=None, default=None):
'\n \n '
try:
with open(path, 'r') as f:
if (type == list):
rv = f.readlines()
else:
rv = f.read()
except IOError as e:
if (default is not None):
rv = default
else:
raise
return rv<|docstring|>Return the contents of file *path* as *type* (string [default], or list)<|endoftext|>
|
dc481383c1ea26a1694ace44b7e33eac8845ab6510401061c21504cc85552456
|
def dirname(path):
'\n Convenience wrapper for os.path.dirname()\n '
return os.path.dirname(path)
|
Convenience wrapper for os.path.dirname()
|
gitr/tbx.py
|
dirname
|
tbarron/gitr
| 0
|
python
|
def dirname(path):
'\n \n '
return os.path.dirname(path)
|
def dirname(path):
'\n \n '
return os.path.dirname(path)<|docstring|>Convenience wrapper for os.path.dirname()<|endoftext|>
|
65acd798dd8e7978d29a515f1bcba8531e65af42e6a590c17e257c9ee9ec5aea
|
def revnumerate(seq):
"\n Enumerate a copy of a sequence in reverse as a generator\n\n Often this will be used to scan a list backwards so that we can add things\n to the list without disturbing the indices of earlier elements. We don't\n want the list changing out from under us as we work on it, so we scan a\n copy rather than the origin sequence.\n "
n = (len(seq) - 1)
seqcopy = copy.deepcopy(seq)
for elem in reversed(seqcopy):
(yield (n, elem))
n -= 1
|
Enumerate a copy of a sequence in reverse as a generator
Often this will be used to scan a list backwards so that we can add things
to the list without disturbing the indices of earlier elements. We don't
want the list changing out from under us as we work on it, so we scan a
copy rather than the origin sequence.
|
gitr/tbx.py
|
revnumerate
|
tbarron/gitr
| 0
|
python
|
def revnumerate(seq):
"\n Enumerate a copy of a sequence in reverse as a generator\n\n Often this will be used to scan a list backwards so that we can add things\n to the list without disturbing the indices of earlier elements. We don't\n want the list changing out from under us as we work on it, so we scan a\n copy rather than the origin sequence.\n "
n = (len(seq) - 1)
seqcopy = copy.deepcopy(seq)
for elem in reversed(seqcopy):
(yield (n, elem))
n -= 1
|
def revnumerate(seq):
"\n Enumerate a copy of a sequence in reverse as a generator\n\n Often this will be used to scan a list backwards so that we can add things\n to the list without disturbing the indices of earlier elements. We don't\n want the list changing out from under us as we work on it, so we scan a\n copy rather than the origin sequence.\n "
n = (len(seq) - 1)
seqcopy = copy.deepcopy(seq)
for elem in reversed(seqcopy):
(yield (n, elem))
n -= 1<|docstring|>Enumerate a copy of a sequence in reverse as a generator
Often this will be used to scan a list backwards so that we can add things
to the list without disturbing the indices of earlier elements. We don't
want the list changing out from under us as we work on it, so we scan a
copy rather than the origin sequence.<|endoftext|>
|
6c525e2c6d56c1763f242321f768365c1f1d0699cc9eaf68f1961fe5d659c7da
|
def run(cmd, input=None):
'\n Run *cmd*, optionally passing string *input* to it on stdin, and return\n what the process writes to stdout\n '
try:
p = subprocess.Popen(shlex.split(cmd), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if input:
p.stdin.write(input)
(o, e) = p.communicate()
if (p.returncode == 0):
rval = o
else:
rval = ('ERR:' + e)
except OSError as e:
if ('No such file or directory' in str(e)):
rval = ('ERR:' + str(e))
else:
raise
return rval
|
Run *cmd*, optionally passing string *input* to it on stdin, and return
what the process writes to stdout
|
gitr/tbx.py
|
run
|
tbarron/gitr
| 0
|
python
|
def run(cmd, input=None):
'\n Run *cmd*, optionally passing string *input* to it on stdin, and return\n what the process writes to stdout\n '
try:
p = subprocess.Popen(shlex.split(cmd), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if input:
p.stdin.write(input)
(o, e) = p.communicate()
if (p.returncode == 0):
rval = o
else:
rval = ('ERR:' + e)
except OSError as e:
if ('No such file or directory' in str(e)):
rval = ('ERR:' + str(e))
else:
raise
return rval
|
def run(cmd, input=None):
'\n Run *cmd*, optionally passing string *input* to it on stdin, and return\n what the process writes to stdout\n '
try:
p = subprocess.Popen(shlex.split(cmd), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
if input:
p.stdin.write(input)
(o, e) = p.communicate()
if (p.returncode == 0):
rval = o
else:
rval = ('ERR:' + e)
except OSError as e:
if ('No such file or directory' in str(e)):
rval = ('ERR:' + str(e))
else:
raise
return rval<|docstring|>Run *cmd*, optionally passing string *input* to it on stdin, and return
what the process writes to stdout<|endoftext|>
|
aef8846fc486f9ff13f2784668212eeadfbd828aa8e4b2b1f21c4afa557a6e58
|
def add_type_param_arguments(parser):
'Function to add qos rule type arguments.'
add_bandwidth_limit_arguments(parser)
|
Function to add qos rule type arguments.
|
neutronclient/neutron/v2_0/qos/type.py
|
add_type_param_arguments
|
mangelajo/python-neutronclient
| 0
|
python
|
def add_type_param_arguments(parser):
add_bandwidth_limit_arguments(parser)
|
def add_type_param_arguments(parser):
add_bandwidth_limit_arguments(parser)<|docstring|>Function to add qos rule type arguments.<|endoftext|>
|
a042740318020772d69dcaadd01049f289961f93d35e237f3dd1ba48ad143e82
|
def update_type_param_args2body(parsed_args, body):
'Function to parse qos rule type arguments.'
update_bandwidth_limit_args2body(parsed_args, body)
|
Function to parse qos rule type arguments.
|
neutronclient/neutron/v2_0/qos/type.py
|
update_type_param_args2body
|
mangelajo/python-neutronclient
| 0
|
python
|
def update_type_param_args2body(parsed_args, body):
update_bandwidth_limit_args2body(parsed_args, body)
|
def update_type_param_args2body(parsed_args, body):
update_bandwidth_limit_args2body(parsed_args, body)<|docstring|>Function to parse qos rule type arguments.<|endoftext|>
|
d9d1cd6aa43ab3934bbc93490f808006acebc7e8a307440b1f71e8103c25557b
|
def rotate(self, tresh=60, method='rect'):
'Rotate the form to correct the skew after scanning\n\n Parameters\n ----------\n tresh : int, optional\n All pixels lower than the treshold are supposed to be black.\n method : str, optional\n The method to find the angle of the rotation. "pca" does a PCA\n and "rect" tries to find the upper edge of the rectangle in the\n header.\n '
data = self.get_header_data()
if (method == 'pca'):
(x, y) = np.where((data < tresh))
(eigval, eigvec) = np.linalg.eigh(np.cov(np.array([x, y])))
angle = ((np.arctan2(eigvec[(0, :)], eigvec[(1, :)])[1] * 180) / np.pi)
elif (method == 'rect'):
data = np.where((data < tresh), 1, 0)
(y, x) = np.nonzero(data)
data = data[(y.min():(y.max() + 1), x.min():(x.max() + 1))]
width = data.shape[1]
p1 = (np.nonzero(data[(0, :)])[0][0], 0)
if (p1[0] < (width / 2)):
(y, x) = np.nonzero(data[(:20, (- 10):)])
p2 = (((width - 10) + x[0]), y[0])
else:
p2 = p1
(y, x) = np.nonzero(data[(:20, :10)])
p1 = (x[0], y[0])
angle = ((np.arctan2((p2[1] - p1[1]), (p2[0] - p1[0])) * 180) / np.pi)
else:
raise NotImplementedError('method not implemented')
self.img = self.img.rotate(angle)
|
Rotate the form to correct the skew after scanning
Parameters
----------
tresh : int, optional
All pixels lower than the treshold are supposed to be black.
method : str, optional
The method to find the angle of the rotation. "pca" does a PCA
and "rect" tries to find the upper edge of the rectangle in the
header.
|
survey/form.py
|
rotate
|
stescholz/survey
| 0
|
python
|
def rotate(self, tresh=60, method='rect'):
'Rotate the form to correct the skew after scanning\n\n Parameters\n ----------\n tresh : int, optional\n All pixels lower than the treshold are supposed to be black.\n method : str, optional\n The method to find the angle of the rotation. "pca" does a PCA\n and "rect" tries to find the upper edge of the rectangle in the\n header.\n '
data = self.get_header_data()
if (method == 'pca'):
(x, y) = np.where((data < tresh))
(eigval, eigvec) = np.linalg.eigh(np.cov(np.array([x, y])))
angle = ((np.arctan2(eigvec[(0, :)], eigvec[(1, :)])[1] * 180) / np.pi)
elif (method == 'rect'):
data = np.where((data < tresh), 1, 0)
(y, x) = np.nonzero(data)
data = data[(y.min():(y.max() + 1), x.min():(x.max() + 1))]
width = data.shape[1]
p1 = (np.nonzero(data[(0, :)])[0][0], 0)
if (p1[0] < (width / 2)):
(y, x) = np.nonzero(data[(:20, (- 10):)])
p2 = (((width - 10) + x[0]), y[0])
else:
p2 = p1
(y, x) = np.nonzero(data[(:20, :10)])
p1 = (x[0], y[0])
angle = ((np.arctan2((p2[1] - p1[1]), (p2[0] - p1[0])) * 180) / np.pi)
else:
raise NotImplementedError('method not implemented')
self.img = self.img.rotate(angle)
|
def rotate(self, tresh=60, method='rect'):
'Rotate the form to correct the skew after scanning\n\n Parameters\n ----------\n tresh : int, optional\n All pixels lower than the treshold are supposed to be black.\n method : str, optional\n The method to find the angle of the rotation. "pca" does a PCA\n and "rect" tries to find the upper edge of the rectangle in the\n header.\n '
data = self.get_header_data()
if (method == 'pca'):
(x, y) = np.where((data < tresh))
(eigval, eigvec) = np.linalg.eigh(np.cov(np.array([x, y])))
angle = ((np.arctan2(eigvec[(0, :)], eigvec[(1, :)])[1] * 180) / np.pi)
elif (method == 'rect'):
data = np.where((data < tresh), 1, 0)
(y, x) = np.nonzero(data)
data = data[(y.min():(y.max() + 1), x.min():(x.max() + 1))]
width = data.shape[1]
p1 = (np.nonzero(data[(0, :)])[0][0], 0)
if (p1[0] < (width / 2)):
(y, x) = np.nonzero(data[(:20, (- 10):)])
p2 = (((width - 10) + x[0]), y[0])
else:
p2 = p1
(y, x) = np.nonzero(data[(:20, :10)])
p1 = (x[0], y[0])
angle = ((np.arctan2((p2[1] - p1[1]), (p2[0] - p1[0])) * 180) / np.pi)
else:
raise NotImplementedError('method not implemented')
self.img = self.img.rotate(angle)<|docstring|>Rotate the form to correct the skew after scanning
Parameters
----------
tresh : int, optional
All pixels lower than the treshold are supposed to be black.
method : str, optional
The method to find the angle of the rotation. "pca" does a PCA
and "rect" tries to find the upper edge of the rectangle in the
header.<|endoftext|>
|
76b3e59d6a8c5f51b9d099abb4ef0c7d069d68d82bc57a75221662ab17a37d58
|
def get_left_upper_bbox_header(self, tresh=40):
'Get the left upper coordinate of the bounding box of the header\n\n Parameters\n ----------\n tresh : int, optional\n All pixels lower than the treshold are supposed to be black.\n '
data = self.get_header_data()
crop = np.where((data > tresh), 0, 1)
left = np.where(np.any(crop, axis=0))[0][0]
upper = np.where(np.any(crop, axis=1))[0][0]
return (left, upper)
|
Get the left upper coordinate of the bounding box of the header
Parameters
----------
tresh : int, optional
All pixels lower than the treshold are supposed to be black.
|
survey/form.py
|
get_left_upper_bbox_header
|
stescholz/survey
| 0
|
python
|
def get_left_upper_bbox_header(self, tresh=40):
'Get the left upper coordinate of the bounding box of the header\n\n Parameters\n ----------\n tresh : int, optional\n All pixels lower than the treshold are supposed to be black.\n '
data = self.get_header_data()
crop = np.where((data > tresh), 0, 1)
left = np.where(np.any(crop, axis=0))[0][0]
upper = np.where(np.any(crop, axis=1))[0][0]
return (left, upper)
|
def get_left_upper_bbox_header(self, tresh=40):
'Get the left upper coordinate of the bounding box of the header\n\n Parameters\n ----------\n tresh : int, optional\n All pixels lower than the treshold are supposed to be black.\n '
data = self.get_header_data()
crop = np.where((data > tresh), 0, 1)
left = np.where(np.any(crop, axis=0))[0][0]
upper = np.where(np.any(crop, axis=1))[0][0]
return (left, upper)<|docstring|>Get the left upper coordinate of the bounding box of the header
Parameters
----------
tresh : int, optional
All pixels lower than the treshold are supposed to be black.<|endoftext|>
|
22c50c5213be8c231bc932aa0d99bcb64cf6c9ea3f74547d07257e32e118d989
|
def shift(self, left_h, upper_h):
'Shift the image according to the first form\n\n Compare the bounding box of the header with the one from the first form\n and shift the image.\n\n Parameters\n ----------\n left_h, upper_h : int\n The coordinates of the left upper corner of the bounding box of\n the header to which the one of this form is aligned.\n '
(left, upper) = self.get_left_upper_bbox_header()
self.img = self.img.transform(self.img.size, Image.AFFINE, (1, 0, (left - left_h), 0, 1, (upper - upper_h)))
|
Shift the image according to the first form
Compare the bounding box of the header with the one from the first form
and shift the image.
Parameters
----------
left_h, upper_h : int
The coordinates of the left upper corner of the bounding box of
the header to which the one of this form is aligned.
|
survey/form.py
|
shift
|
stescholz/survey
| 0
|
python
|
def shift(self, left_h, upper_h):
'Shift the image according to the first form\n\n Compare the bounding box of the header with the one from the first form\n and shift the image.\n\n Parameters\n ----------\n left_h, upper_h : int\n The coordinates of the left upper corner of the bounding box of\n the header to which the one of this form is aligned.\n '
(left, upper) = self.get_left_upper_bbox_header()
self.img = self.img.transform(self.img.size, Image.AFFINE, (1, 0, (left - left_h), 0, 1, (upper - upper_h)))
|
def shift(self, left_h, upper_h):
'Shift the image according to the first form\n\n Compare the bounding box of the header with the one from the first form\n and shift the image.\n\n Parameters\n ----------\n left_h, upper_h : int\n The coordinates of the left upper corner of the bounding box of\n the header to which the one of this form is aligned.\n '
(left, upper) = self.get_left_upper_bbox_header()
self.img = self.img.transform(self.img.size, Image.AFFINE, (1, 0, (left - left_h), 0, 1, (upper - upper_h)))<|docstring|>Shift the image according to the first form
Compare the bounding box of the header with the one from the first form
and shift the image.
Parameters
----------
left_h, upper_h : int
The coordinates of the left upper corner of the bounding box of
the header to which the one of this form is aligned.<|endoftext|>
|
bd1184c16852fbe178e7de6a08d27c0a62ac1ae17c3df9ad63455a46dfbd81a2
|
def init_questions(self):
'Create all boxes for the questions of this form'
self.boxes = [q.generate_boxes(self.img) for q in self.questions]
|
Create all boxes for the questions of this form
|
survey/form.py
|
init_questions
|
stescholz/survey
| 0
|
python
|
def init_questions(self):
self.boxes = [q.generate_boxes(self.img) for q in self.questions]
|
def init_questions(self):
self.boxes = [q.generate_boxes(self.img) for q in self.questions]<|docstring|>Create all boxes for the questions of this form<|endoftext|>
|
b626d64234fbef2aeb3afdc8e806b06b9702bbe1ad85fff86b90f3e3144e6bf9
|
def check_positions(self, original=False):
'Mark all positions of the boxes and the header in the image.\n\n Parameters\n ----------\n original : boolean, optional\n Use the orignal position of the center or the calculated.\n\n Returns\n -------\n object\n The copy of the Image instance where all boxes and the header are\n marked as rectangles.\n '
img = self.img.copy()
draw = ImageDraw.Draw(img)
draw.rectangle(self.header, outline=0)
for boxes in self.boxes:
for b in boxes:
b.mark_position(img, original=original)
return img
|
Mark all positions of the boxes and the header in the image.
Parameters
----------
original : boolean, optional
Use the orignal position of the center or the calculated.
Returns
-------
object
The copy of the Image instance where all boxes and the header are
marked as rectangles.
|
survey/form.py
|
check_positions
|
stescholz/survey
| 0
|
python
|
def check_positions(self, original=False):
'Mark all positions of the boxes and the header in the image.\n\n Parameters\n ----------\n original : boolean, optional\n Use the orignal position of the center or the calculated.\n\n Returns\n -------\n object\n The copy of the Image instance where all boxes and the header are\n marked as rectangles.\n '
img = self.img.copy()
draw = ImageDraw.Draw(img)
draw.rectangle(self.header, outline=0)
for boxes in self.boxes:
for b in boxes:
b.mark_position(img, original=original)
return img
|
def check_positions(self, original=False):
'Mark all positions of the boxes and the header in the image.\n\n Parameters\n ----------\n original : boolean, optional\n Use the orignal position of the center or the calculated.\n\n Returns\n -------\n object\n The copy of the Image instance where all boxes and the header are\n marked as rectangles.\n '
img = self.img.copy()
draw = ImageDraw.Draw(img)
draw.rectangle(self.header, outline=0)
for boxes in self.boxes:
for b in boxes:
b.mark_position(img, original=original)
return img<|docstring|>Mark all positions of the boxes and the header in the image.
Parameters
----------
original : boolean, optional
Use the orignal position of the center or the calculated.
Returns
-------
object
The copy of the Image instance where all boxes and the header are
marked as rectangles.<|endoftext|>
|
3f72ab1e06871f8641a94b6692ee7642f341480a89c8c1c3a97ca684d08bb1a5
|
def get_answers(self, lower=115, upper=208, full=False):
'Find all answers to the questions.\n\n Parameters\n ----------\n lower, upper : int, optional\n The treshold for the mean of the pixels of the box. If the mean is\n between the upper and lower bound the box should be checked\n otherwise not.\n full : boolean, optional\n If true, the status of every box of the question is returned.\n Otherwise only the answer is given.\n\n Returns\n -------\n tuple\n The first element is the list of answers. According to the\n parameter for every question the status of all the boxes is given\n or only the answer. The second element is a dictionary of the\n errors which occured in the analysis of the boxes.\n '
answers = []
errors = {}
for (i, (q, boxes)) in enumerate(zip(self.questions, self.boxes)):
(ans, error) = q.get_answers(boxes, lower, upper, full)
answers.append(ans)
if error:
errors[i] = error
return (answers, errors)
|
Find all answers to the questions.
Parameters
----------
lower, upper : int, optional
The treshold for the mean of the pixels of the box. If the mean is
between the upper and lower bound the box should be checked
otherwise not.
full : boolean, optional
If true, the status of every box of the question is returned.
Otherwise only the answer is given.
Returns
-------
tuple
The first element is the list of answers. According to the
parameter for every question the status of all the boxes is given
or only the answer. The second element is a dictionary of the
errors which occured in the analysis of the boxes.
|
survey/form.py
|
get_answers
|
stescholz/survey
| 0
|
python
|
def get_answers(self, lower=115, upper=208, full=False):
'Find all answers to the questions.\n\n Parameters\n ----------\n lower, upper : int, optional\n The treshold for the mean of the pixels of the box. If the mean is\n between the upper and lower bound the box should be checked\n otherwise not.\n full : boolean, optional\n If true, the status of every box of the question is returned.\n Otherwise only the answer is given.\n\n Returns\n -------\n tuple\n The first element is the list of answers. According to the\n parameter for every question the status of all the boxes is given\n or only the answer. The second element is a dictionary of the\n errors which occured in the analysis of the boxes.\n '
answers = []
errors = {}
for (i, (q, boxes)) in enumerate(zip(self.questions, self.boxes)):
(ans, error) = q.get_answers(boxes, lower, upper, full)
answers.append(ans)
if error:
errors[i] = error
return (answers, errors)
|
def get_answers(self, lower=115, upper=208, full=False):
'Find all answers to the questions.\n\n Parameters\n ----------\n lower, upper : int, optional\n The treshold for the mean of the pixels of the box. If the mean is\n between the upper and lower bound the box should be checked\n otherwise not.\n full : boolean, optional\n If true, the status of every box of the question is returned.\n Otherwise only the answer is given.\n\n Returns\n -------\n tuple\n The first element is the list of answers. According to the\n parameter for every question the status of all the boxes is given\n or only the answer. The second element is a dictionary of the\n errors which occured in the analysis of the boxes.\n '
answers = []
errors = {}
for (i, (q, boxes)) in enumerate(zip(self.questions, self.boxes)):
(ans, error) = q.get_answers(boxes, lower, upper, full)
answers.append(ans)
if error:
errors[i] = error
return (answers, errors)<|docstring|>Find all answers to the questions.
Parameters
----------
lower, upper : int, optional
The treshold for the mean of the pixels of the box. If the mean is
between the upper and lower bound the box should be checked
otherwise not.
full : boolean, optional
If true, the status of every box of the question is returned.
Otherwise only the answer is given.
Returns
-------
tuple
The first element is the list of answers. According to the
parameter for every question the status of all the boxes is given
or only the answer. The second element is a dictionary of the
errors which occured in the analysis of the boxes.<|endoftext|>
|
72e56f9bc3460ad6f13891649bceb5547abf847f797a81c93332e29eaee4954e
|
def setUp(self):
'\n Bootstrap test data\n '
super(VideoUnarchiveTests, self).setUp()
self.project = milkman.deliver(Project)
self.project.set_owner(self.admin)
self.project.add_assigned(self.user, pending=False)
|
Bootstrap test data
|
appengine/src/greenday_api/tests/test_video_api/test_archiving.py
|
setUp
|
meedan/montage
| 6
|
python
|
def setUp(self):
'\n \n '
super(VideoUnarchiveTests, self).setUp()
self.project = milkman.deliver(Project)
self.project.set_owner(self.admin)
self.project.add_assigned(self.user, pending=False)
|
def setUp(self):
'\n \n '
super(VideoUnarchiveTests, self).setUp()
self.project = milkman.deliver(Project)
self.project.set_owner(self.admin)
self.project.add_assigned(self.user, pending=False)<|docstring|>Bootstrap test data<|endoftext|>
|
b22b322943c59411927f6946a7f27f01ff40a8a1525dacc874f28cfbd57fed60
|
def test_video_unarchive(self):
'\n Unarchive a video\n '
self._sign_in(self.user)
video = self.create_video(project=self.project, user=self.user, archived_at=timezone.now())
request = VideoEntityContainer.combined_message_class(project_id=self.project.pk, youtube_id=video.youtube_id)
with self.assertEventRecorded(EventKind.VIDEOUNARCHIVED, object_id=video.pk, video_id=video.pk, project_id=self.project.pk), self.assertNumQueries(6):
self.api.video_unarchive(request)
video = self.reload(video)
self.assertFalse(video.archived_at)
|
Unarchive a video
|
appengine/src/greenday_api/tests/test_video_api/test_archiving.py
|
test_video_unarchive
|
meedan/montage
| 6
|
python
|
def test_video_unarchive(self):
'\n \n '
self._sign_in(self.user)
video = self.create_video(project=self.project, user=self.user, archived_at=timezone.now())
request = VideoEntityContainer.combined_message_class(project_id=self.project.pk, youtube_id=video.youtube_id)
with self.assertEventRecorded(EventKind.VIDEOUNARCHIVED, object_id=video.pk, video_id=video.pk, project_id=self.project.pk), self.assertNumQueries(6):
self.api.video_unarchive(request)
video = self.reload(video)
self.assertFalse(video.archived_at)
|
def test_video_unarchive(self):
'\n \n '
self._sign_in(self.user)
video = self.create_video(project=self.project, user=self.user, archived_at=timezone.now())
request = VideoEntityContainer.combined_message_class(project_id=self.project.pk, youtube_id=video.youtube_id)
with self.assertEventRecorded(EventKind.VIDEOUNARCHIVED, object_id=video.pk, video_id=video.pk, project_id=self.project.pk), self.assertNumQueries(6):
self.api.video_unarchive(request)
video = self.reload(video)
self.assertFalse(video.archived_at)<|docstring|>Unarchive a video<|endoftext|>
|
d500d45803750d07b473a15926b398ce59ef64ab1544be75a3169e41af6644f5
|
def setUp(self):
'\n Bootstrap test data\n '
super(VideoBatchUnarchiveTests, self).setUp()
self.project = milkman.deliver(Project)
self.project.set_owner(self.admin)
self.project.add_assigned(self.user, pending=False)
self.video = self.create_video(project=self.project, user=self.user, archived_at=timezone.now())
self.video2 = self.create_video(project=self.project, user=self.user, archived_at=timezone.now())
|
Bootstrap test data
|
appengine/src/greenday_api/tests/test_video_api/test_archiving.py
|
setUp
|
meedan/montage
| 6
|
python
|
def setUp(self):
'\n \n '
super(VideoBatchUnarchiveTests, self).setUp()
self.project = milkman.deliver(Project)
self.project.set_owner(self.admin)
self.project.add_assigned(self.user, pending=False)
self.video = self.create_video(project=self.project, user=self.user, archived_at=timezone.now())
self.video2 = self.create_video(project=self.project, user=self.user, archived_at=timezone.now())
|
def setUp(self):
'\n \n '
super(VideoBatchUnarchiveTests, self).setUp()
self.project = milkman.deliver(Project)
self.project.set_owner(self.admin)
self.project.add_assigned(self.user, pending=False)
self.video = self.create_video(project=self.project, user=self.user, archived_at=timezone.now())
self.video2 = self.create_video(project=self.project, user=self.user, archived_at=timezone.now())<|docstring|>Bootstrap test data<|endoftext|>
|
d50832749bbb46f8159ffc1aeb7b6abf8de37d379988865c9f308eb9a84e84c2
|
def test_video_batch_unarchive(self):
'\n Unarchive list of videos\n '
self._sign_in(self.user)
request = ArchiveVideoBatchContainer.combined_message_class(project_id=self.project.pk, unarchive=True, youtube_ids=(self.video.youtube_id, self.video2.youtube_id))
event_recorder = self.assertEventRecorded([{'kind': EventKind.VIDEOUNARCHIVED, 'object_id': video.pk, 'video_id': video.pk, 'project_id': self.project.pk} for video in (self.video, self.video2)])
event_recorder.start()
with self.assertNumQueries(8):
response = self.api.video_batch_archive(request)
for vid in (self.video, self.video2):
item = next((i for i in response.items if (i.youtube_id == vid.youtube_id)))
self.assertEqual(item.msg, 'ok')
self.assertTrue(item.success)
self.assertEqual(2, len(response.videos))
self.assertEqual(0, Video.archived_objects.count())
self.assertEqual(2, Video.objects.count())
event_recorder.do_assert()
|
Unarchive list of videos
|
appengine/src/greenday_api/tests/test_video_api/test_archiving.py
|
test_video_batch_unarchive
|
meedan/montage
| 6
|
python
|
def test_video_batch_unarchive(self):
'\n \n '
self._sign_in(self.user)
request = ArchiveVideoBatchContainer.combined_message_class(project_id=self.project.pk, unarchive=True, youtube_ids=(self.video.youtube_id, self.video2.youtube_id))
event_recorder = self.assertEventRecorded([{'kind': EventKind.VIDEOUNARCHIVED, 'object_id': video.pk, 'video_id': video.pk, 'project_id': self.project.pk} for video in (self.video, self.video2)])
event_recorder.start()
with self.assertNumQueries(8):
response = self.api.video_batch_archive(request)
for vid in (self.video, self.video2):
item = next((i for i in response.items if (i.youtube_id == vid.youtube_id)))
self.assertEqual(item.msg, 'ok')
self.assertTrue(item.success)
self.assertEqual(2, len(response.videos))
self.assertEqual(0, Video.archived_objects.count())
self.assertEqual(2, Video.objects.count())
event_recorder.do_assert()
|
def test_video_batch_unarchive(self):
'\n \n '
self._sign_in(self.user)
request = ArchiveVideoBatchContainer.combined_message_class(project_id=self.project.pk, unarchive=True, youtube_ids=(self.video.youtube_id, self.video2.youtube_id))
event_recorder = self.assertEventRecorded([{'kind': EventKind.VIDEOUNARCHIVED, 'object_id': video.pk, 'video_id': video.pk, 'project_id': self.project.pk} for video in (self.video, self.video2)])
event_recorder.start()
with self.assertNumQueries(8):
response = self.api.video_batch_archive(request)
for vid in (self.video, self.video2):
item = next((i for i in response.items if (i.youtube_id == vid.youtube_id)))
self.assertEqual(item.msg, 'ok')
self.assertTrue(item.success)
self.assertEqual(2, len(response.videos))
self.assertEqual(0, Video.archived_objects.count())
self.assertEqual(2, Video.objects.count())
event_recorder.do_assert()<|docstring|>Unarchive list of videos<|endoftext|>
|
691e0bf07056ac0eab15040b35ef40f746fc8c8e7b38454dbcb8e742018bff74
|
def setUp(self):
'\n Bootstrap test data\n '
super(VideoBatchArchiveTests, self).setUp()
self.project = milkman.deliver(Project)
self.project.set_owner(self.admin)
self.project.add_assigned(self.user, pending=False)
self.video = self.create_video(project=self.project, user=self.user)
self.video2 = self.create_video(project=self.project, user=self.user)
|
Bootstrap test data
|
appengine/src/greenday_api/tests/test_video_api/test_archiving.py
|
setUp
|
meedan/montage
| 6
|
python
|
def setUp(self):
'\n \n '
super(VideoBatchArchiveTests, self).setUp()
self.project = milkman.deliver(Project)
self.project.set_owner(self.admin)
self.project.add_assigned(self.user, pending=False)
self.video = self.create_video(project=self.project, user=self.user)
self.video2 = self.create_video(project=self.project, user=self.user)
|
def setUp(self):
'\n \n '
super(VideoBatchArchiveTests, self).setUp()
self.project = milkman.deliver(Project)
self.project.set_owner(self.admin)
self.project.add_assigned(self.user, pending=False)
self.video = self.create_video(project=self.project, user=self.user)
self.video2 = self.create_video(project=self.project, user=self.user)<|docstring|>Bootstrap test data<|endoftext|>
|
ee9bb3d04e2d9cbcd5f5e77af964f8b6af7c3e3b72af502ef07132e1807d499f
|
def test_video_batch_archive(self):
'\n Test archiving list of videos\n '
self._sign_in(self.user)
request = ArchiveVideoBatchContainer.combined_message_class(project_id=self.project.pk, youtube_ids=(self.video.youtube_id, self.video2.youtube_id))
event_recorder = self.assertEventRecorded([{'kind': EventKind.VIDEOARCHIVED, 'object_id': video.pk, 'video_id': video.pk, 'project_id': self.project.pk} for video in (self.video, self.video2)])
event_recorder.start()
with self.assertNumQueries(8):
response = self.api.video_batch_archive(request)
for vid in (self.video, self.video2):
item = next((i for i in response.items if (i.youtube_id == vid.youtube_id)))
self.assertEqual(item.msg, 'ok')
self.assertTrue(item.success)
self.assertEqual(2, len(response.videos))
self.assertEqual(0, Video.objects.count())
self.assertEqual(2, Video.archived_objects.count())
event_recorder.do_assert()
|
Test archiving list of videos
|
appengine/src/greenday_api/tests/test_video_api/test_archiving.py
|
test_video_batch_archive
|
meedan/montage
| 6
|
python
|
def test_video_batch_archive(self):
'\n \n '
self._sign_in(self.user)
request = ArchiveVideoBatchContainer.combined_message_class(project_id=self.project.pk, youtube_ids=(self.video.youtube_id, self.video2.youtube_id))
event_recorder = self.assertEventRecorded([{'kind': EventKind.VIDEOARCHIVED, 'object_id': video.pk, 'video_id': video.pk, 'project_id': self.project.pk} for video in (self.video, self.video2)])
event_recorder.start()
with self.assertNumQueries(8):
response = self.api.video_batch_archive(request)
for vid in (self.video, self.video2):
item = next((i for i in response.items if (i.youtube_id == vid.youtube_id)))
self.assertEqual(item.msg, 'ok')
self.assertTrue(item.success)
self.assertEqual(2, len(response.videos))
self.assertEqual(0, Video.objects.count())
self.assertEqual(2, Video.archived_objects.count())
event_recorder.do_assert()
|
def test_video_batch_archive(self):
'\n \n '
self._sign_in(self.user)
request = ArchiveVideoBatchContainer.combined_message_class(project_id=self.project.pk, youtube_ids=(self.video.youtube_id, self.video2.youtube_id))
event_recorder = self.assertEventRecorded([{'kind': EventKind.VIDEOARCHIVED, 'object_id': video.pk, 'video_id': video.pk, 'project_id': self.project.pk} for video in (self.video, self.video2)])
event_recorder.start()
with self.assertNumQueries(8):
response = self.api.video_batch_archive(request)
for vid in (self.video, self.video2):
item = next((i for i in response.items if (i.youtube_id == vid.youtube_id)))
self.assertEqual(item.msg, 'ok')
self.assertTrue(item.success)
self.assertEqual(2, len(response.videos))
self.assertEqual(0, Video.objects.count())
self.assertEqual(2, Video.archived_objects.count())
event_recorder.do_assert()<|docstring|>Test archiving list of videos<|endoftext|>
|
8a232c8cbb709ec7f79123dc19da1bd85fb282839f5836dcb19b64db76d738fb
|
def test_video_batch_archive_permission_denied(self):
'\n Test archiving video as normal collaborator\n '
self._sign_in(self.user)
self.project.add_assigned(self.user2, pending=False)
self.video2.user = self.user2
self.video2.save()
request = ArchiveVideoBatchContainer.combined_message_class(project_id=self.project.pk, youtube_ids=(self.video.youtube_id, self.video2.youtube_id))
with self.assertEventRecorded(EventKind.VIDEOARCHIVED, object_id=self.video.pk, video_id=self.video.pk, project_id=self.project.pk), self.assertNumQueries(7):
response = self.api.video_batch_archive(request)
ok_item = next((i for i in response.items if (i.youtube_id == self.video.youtube_id)))
self.assertEqual(ok_item.msg, 'ok')
self.assertTrue(ok_item.success)
bad_item = next((i for i in response.items if (i.youtube_id == self.video2.youtube_id)))
self.assertEqual(bad_item.msg, 'Permission Denied!')
self.assertFalse(bad_item.success)
self.assertEqual(1, len(response.videos))
self.assertEqual(1, Video.objects.count())
self.assertEqual(1, Video.archived_objects.count())
|
Test archiving video as normal collaborator
|
appengine/src/greenday_api/tests/test_video_api/test_archiving.py
|
test_video_batch_archive_permission_denied
|
meedan/montage
| 6
|
python
|
def test_video_batch_archive_permission_denied(self):
'\n \n '
self._sign_in(self.user)
self.project.add_assigned(self.user2, pending=False)
self.video2.user = self.user2
self.video2.save()
request = ArchiveVideoBatchContainer.combined_message_class(project_id=self.project.pk, youtube_ids=(self.video.youtube_id, self.video2.youtube_id))
with self.assertEventRecorded(EventKind.VIDEOARCHIVED, object_id=self.video.pk, video_id=self.video.pk, project_id=self.project.pk), self.assertNumQueries(7):
response = self.api.video_batch_archive(request)
ok_item = next((i for i in response.items if (i.youtube_id == self.video.youtube_id)))
self.assertEqual(ok_item.msg, 'ok')
self.assertTrue(ok_item.success)
bad_item = next((i for i in response.items if (i.youtube_id == self.video2.youtube_id)))
self.assertEqual(bad_item.msg, 'Permission Denied!')
self.assertFalse(bad_item.success)
self.assertEqual(1, len(response.videos))
self.assertEqual(1, Video.objects.count())
self.assertEqual(1, Video.archived_objects.count())
|
def test_video_batch_archive_permission_denied(self):
'\n \n '
self._sign_in(self.user)
self.project.add_assigned(self.user2, pending=False)
self.video2.user = self.user2
self.video2.save()
request = ArchiveVideoBatchContainer.combined_message_class(project_id=self.project.pk, youtube_ids=(self.video.youtube_id, self.video2.youtube_id))
with self.assertEventRecorded(EventKind.VIDEOARCHIVED, object_id=self.video.pk, video_id=self.video.pk, project_id=self.project.pk), self.assertNumQueries(7):
response = self.api.video_batch_archive(request)
ok_item = next((i for i in response.items if (i.youtube_id == self.video.youtube_id)))
self.assertEqual(ok_item.msg, 'ok')
self.assertTrue(ok_item.success)
bad_item = next((i for i in response.items if (i.youtube_id == self.video2.youtube_id)))
self.assertEqual(bad_item.msg, 'Permission Denied!')
self.assertFalse(bad_item.success)
self.assertEqual(1, len(response.videos))
self.assertEqual(1, Video.objects.count())
self.assertEqual(1, Video.archived_objects.count())<|docstring|>Test archiving video as normal collaborator<|endoftext|>
|
2b78da7349c27f2f874f39073a39c5bd945ce694badb987022a0533f2ce63f7c
|
def test_video_batch_archive_video_already_archived(self):
'\n Archive an archived video\n '
self._sign_in(self.user)
self.video2.archived_at = timezone.now()
self.video2.save()
request = ArchiveVideoBatchContainer.combined_message_class(project_id=self.project.pk, youtube_ids=(self.video.youtube_id, self.video2.youtube_id))
with self.assertEventRecorded(EventKind.VIDEOARCHIVED, object_id=self.video.pk, video_id=self.video.pk, project_id=self.project.pk), self.assertNumQueries(7):
response = self.api.video_batch_archive(request)
ok_item = next((i for i in response.items if (i.youtube_id == self.video.youtube_id)))
self.assertEqual(ok_item.msg, 'ok')
self.assertTrue(ok_item.success)
bad_item = next((i for i in response.items if (i.youtube_id == self.video2.youtube_id)))
self.assertEqual(bad_item.msg, ('Video with youtube_id %s does not exist' % self.video2.youtube_id))
self.assertFalse(bad_item.success)
self.assertEqual(1, len(response.videos))
self.assertEqual(0, Video.objects.count())
self.assertEqual(2, Video.archived_objects.count())
|
Archive an archived video
|
appengine/src/greenday_api/tests/test_video_api/test_archiving.py
|
test_video_batch_archive_video_already_archived
|
meedan/montage
| 6
|
python
|
def test_video_batch_archive_video_already_archived(self):
'\n \n '
self._sign_in(self.user)
self.video2.archived_at = timezone.now()
self.video2.save()
request = ArchiveVideoBatchContainer.combined_message_class(project_id=self.project.pk, youtube_ids=(self.video.youtube_id, self.video2.youtube_id))
with self.assertEventRecorded(EventKind.VIDEOARCHIVED, object_id=self.video.pk, video_id=self.video.pk, project_id=self.project.pk), self.assertNumQueries(7):
response = self.api.video_batch_archive(request)
ok_item = next((i for i in response.items if (i.youtube_id == self.video.youtube_id)))
self.assertEqual(ok_item.msg, 'ok')
self.assertTrue(ok_item.success)
bad_item = next((i for i in response.items if (i.youtube_id == self.video2.youtube_id)))
self.assertEqual(bad_item.msg, ('Video with youtube_id %s does not exist' % self.video2.youtube_id))
self.assertFalse(bad_item.success)
self.assertEqual(1, len(response.videos))
self.assertEqual(0, Video.objects.count())
self.assertEqual(2, Video.archived_objects.count())
|
def test_video_batch_archive_video_already_archived(self):
'\n \n '
self._sign_in(self.user)
self.video2.archived_at = timezone.now()
self.video2.save()
request = ArchiveVideoBatchContainer.combined_message_class(project_id=self.project.pk, youtube_ids=(self.video.youtube_id, self.video2.youtube_id))
with self.assertEventRecorded(EventKind.VIDEOARCHIVED, object_id=self.video.pk, video_id=self.video.pk, project_id=self.project.pk), self.assertNumQueries(7):
response = self.api.video_batch_archive(request)
ok_item = next((i for i in response.items if (i.youtube_id == self.video.youtube_id)))
self.assertEqual(ok_item.msg, 'ok')
self.assertTrue(ok_item.success)
bad_item = next((i for i in response.items if (i.youtube_id == self.video2.youtube_id)))
self.assertEqual(bad_item.msg, ('Video with youtube_id %s does not exist' % self.video2.youtube_id))
self.assertFalse(bad_item.success)
self.assertEqual(1, len(response.videos))
self.assertEqual(0, Video.objects.count())
self.assertEqual(2, Video.archived_objects.count())<|docstring|>Archive an archived video<|endoftext|>
|
eb5ba4e8fe0c406e48ad84adb6de3fd433b9a588b5daaed2d41cd28af23ef638
|
def test_video_batch_archive_video_does_not_exist(self):
'\n Archive a video that does not exist\n '
self._sign_in(self.user)
request = ArchiveVideoBatchContainer.combined_message_class(project_id=self.project.pk, youtube_ids=(self.video.youtube_id, '9999'))
with self.assertEventRecorded(EventKind.VIDEOARCHIVED, object_id=self.video.pk, video_id=self.video.pk, project_id=self.project.pk), self.assertNumQueries(7):
response = self.api.video_batch_archive(request)
ok_item = next((i for i in response.items if (i.youtube_id == self.video.youtube_id)))
self.assertEqual(ok_item.msg, 'ok')
self.assertTrue(ok_item.success)
bad_item = next((i for i in response.items if (i.youtube_id == '9999')))
self.assertEqual(bad_item.msg, 'Video with youtube_id 9999 does not exist')
self.assertFalse(bad_item.success)
self.assertEqual(1, len(response.videos))
self.assertEqual(1, Video.objects.count())
self.assertEqual(1, Video.archived_objects.count())
|
Archive a video that does not exist
|
appengine/src/greenday_api/tests/test_video_api/test_archiving.py
|
test_video_batch_archive_video_does_not_exist
|
meedan/montage
| 6
|
python
|
def test_video_batch_archive_video_does_not_exist(self):
'\n \n '
self._sign_in(self.user)
request = ArchiveVideoBatchContainer.combined_message_class(project_id=self.project.pk, youtube_ids=(self.video.youtube_id, '9999'))
with self.assertEventRecorded(EventKind.VIDEOARCHIVED, object_id=self.video.pk, video_id=self.video.pk, project_id=self.project.pk), self.assertNumQueries(7):
response = self.api.video_batch_archive(request)
ok_item = next((i for i in response.items if (i.youtube_id == self.video.youtube_id)))
self.assertEqual(ok_item.msg, 'ok')
self.assertTrue(ok_item.success)
bad_item = next((i for i in response.items if (i.youtube_id == '9999')))
self.assertEqual(bad_item.msg, 'Video with youtube_id 9999 does not exist')
self.assertFalse(bad_item.success)
self.assertEqual(1, len(response.videos))
self.assertEqual(1, Video.objects.count())
self.assertEqual(1, Video.archived_objects.count())
|
def test_video_batch_archive_video_does_not_exist(self):
'\n \n '
self._sign_in(self.user)
request = ArchiveVideoBatchContainer.combined_message_class(project_id=self.project.pk, youtube_ids=(self.video.youtube_id, '9999'))
with self.assertEventRecorded(EventKind.VIDEOARCHIVED, object_id=self.video.pk, video_id=self.video.pk, project_id=self.project.pk), self.assertNumQueries(7):
response = self.api.video_batch_archive(request)
ok_item = next((i for i in response.items if (i.youtube_id == self.video.youtube_id)))
self.assertEqual(ok_item.msg, 'ok')
self.assertTrue(ok_item.success)
bad_item = next((i for i in response.items if (i.youtube_id == '9999')))
self.assertEqual(bad_item.msg, 'Video with youtube_id 9999 does not exist')
self.assertFalse(bad_item.success)
self.assertEqual(1, len(response.videos))
self.assertEqual(1, Video.objects.count())
self.assertEqual(1, Video.archived_objects.count())<|docstring|>Archive a video that does not exist<|endoftext|>
|
cd1451c02c607b736ffef5d8eb15497c069e840036964e2e6ac94b3b95081920
|
def dup(n_in: int=1) -> Dup:
'Creates a duplicate combinator.\n\n The combinator makes a copy of inputs.\n\n >>> from redex import combinator as cb\n >>> dup = cb.dup()\n >>> dup(1) == (1, 1)\n True\n\n Args:\n n_in: a number of inputs.\n\n Returns:\n a combinator.\n '
return Dup(signature=Signature(n_in=n_in, n_out=(n_in * 2)))
|
Creates a duplicate combinator.
The combinator makes a copy of inputs.
>>> from redex import combinator as cb
>>> dup = cb.dup()
>>> dup(1) == (1, 1)
True
Args:
n_in: a number of inputs.
Returns:
a combinator.
|
src/redex/combinator/_dup.py
|
dup
|
manifest/redex
| 0
|
python
|
def dup(n_in: int=1) -> Dup:
'Creates a duplicate combinator.\n\n The combinator makes a copy of inputs.\n\n >>> from redex import combinator as cb\n >>> dup = cb.dup()\n >>> dup(1) == (1, 1)\n True\n\n Args:\n n_in: a number of inputs.\n\n Returns:\n a combinator.\n '
return Dup(signature=Signature(n_in=n_in, n_out=(n_in * 2)))
|
def dup(n_in: int=1) -> Dup:
'Creates a duplicate combinator.\n\n The combinator makes a copy of inputs.\n\n >>> from redex import combinator as cb\n >>> dup = cb.dup()\n >>> dup(1) == (1, 1)\n True\n\n Args:\n n_in: a number of inputs.\n\n Returns:\n a combinator.\n '
return Dup(signature=Signature(n_in=n_in, n_out=(n_in * 2)))<|docstring|>Creates a duplicate combinator.
The combinator makes a copy of inputs.
>>> from redex import combinator as cb
>>> dup = cb.dup()
>>> dup(1) == (1, 1)
True
Args:
n_in: a number of inputs.
Returns:
a combinator.<|endoftext|>
|
3d916d15837b07ab65fe1618f2e00df912f04bc6cbc1953399cbdf469a687e1a
|
def anagramMappings(self, A, B):
'\n :type A: List[int]\n :type B: List[int]\n :rtype: List[int]\n '
D = {x: i for (i, x) in enumerate(B)}
return [D[x] for x in A]
|
:type A: List[int]
:type B: List[int]
:rtype: List[int]
|
cs15211/FindAnagramMappings.py
|
anagramMappings
|
JulyKikuAkita/PythonPrac
| 1
|
python
|
def anagramMappings(self, A, B):
'\n :type A: List[int]\n :type B: List[int]\n :rtype: List[int]\n '
D = {x: i for (i, x) in enumerate(B)}
return [D[x] for x in A]
|
def anagramMappings(self, A, B):
'\n :type A: List[int]\n :type B: List[int]\n :rtype: List[int]\n '
D = {x: i for (i, x) in enumerate(B)}
return [D[x] for x in A]<|docstring|>:type A: List[int]
:type B: List[int]
:rtype: List[int]<|endoftext|>
|
69d3557c7d523b22a939dbff18fb5503ffa15ec68384aead4d037ce88e303de0
|
def __iter__(self) -> Page[T]:
'\n Returns:\n This same [Page](./page.md) object.\n '
return self
|
Returns:
This same [Page](./page.md) object.
|
miku/paginator.py
|
__iter__
|
blanketsucks/miku
| 3
|
python
|
def __iter__(self) -> Page[T]:
'\n Returns:\n This same [Page](./page.md) object.\n '
return self
|
def __iter__(self) -> Page[T]:
'\n Returns:\n This same [Page](./page.md) object.\n '
return self<|docstring|>Returns:
This same [Page](./page.md) object.<|endoftext|>
|
ad069c88edd5019b2797f8473396ab5ba9de4f165a153d88dd939b80fb09d388
|
def __next__(self) -> T:
'\n Returns:\n The next element on this page.\n '
data = self.next()
if (not data):
raise StopIteration
return data
|
Returns:
The next element on this page.
|
miku/paginator.py
|
__next__
|
blanketsucks/miku
| 3
|
python
|
def __next__(self) -> T:
'\n Returns:\n The next element on this page.\n '
data = self.next()
if (not data):
raise StopIteration
return data
|
def __next__(self) -> T:
'\n Returns:\n The next element on this page.\n '
data = self.next()
if (not data):
raise StopIteration
return data<|docstring|>Returns:
The next element on this page.<|endoftext|>
|
258a9a5bdcc549392fb68ad238afc61c9c065ef2e9a8cdf134d22c0873992da4
|
@property
def entries(self) -> int:
'\n Returns the number of data entries are in this page.\n\n Returns:\n Number of entries.\n\n '
return len(self.payload)
|
Returns the number of data entries are in this page.
Returns:
Number of entries.
|
miku/paginator.py
|
entries
|
blanketsucks/miku
| 3
|
python
|
@property
def entries(self) -> int:
'\n Returns the number of data entries are in this page.\n\n Returns:\n Number of entries.\n\n '
return len(self.payload)
|
@property
def entries(self) -> int:
'\n Returns the number of data entries are in this page.\n\n Returns:\n Number of entries.\n\n '
return len(self.payload)<|docstring|>Returns the number of data entries are in this page.
Returns:
Number of entries.<|endoftext|>
|
fb3aa54580cca4983d823f461c8a29f67241cef3cf9ca56650a82217e546ceb1
|
@property
def number(self) -> int:
'\n Returns the current page number.\n\n Returns:\n Page number.\n \n '
return self.info['currentPage']
|
Returns the current page number.
Returns:
Page number.
|
miku/paginator.py
|
number
|
blanketsucks/miku
| 3
|
python
|
@property
def number(self) -> int:
'\n Returns the current page number.\n\n Returns:\n Page number.\n \n '
return self.info['currentPage']
|
@property
def number(self) -> int:
'\n Returns the current page number.\n\n Returns:\n Page number.\n \n '
return self.info['currentPage']<|docstring|>Returns the current page number.
Returns:
Page number.<|endoftext|>
|
249d0a8713a2d9c9e5baf12dc43532575e033eb9bd2da9e62c351987df0a4909
|
def next(self) -> Optional[T]:
'\n Returns the next element on this page.\n\n Returns:\n The next element on this page.\n '
try:
data = self.payload[self.current_item]
except IndexError:
return None
self.current_item += 1
return self.model(payload=data, session=self.session)
|
Returns the next element on this page.
Returns:
The next element on this page.
|
miku/paginator.py
|
next
|
blanketsucks/miku
| 3
|
python
|
def next(self) -> Optional[T]:
'\n Returns the next element on this page.\n\n Returns:\n The next element on this page.\n '
try:
data = self.payload[self.current_item]
except IndexError:
return None
self.current_item += 1
return self.model(payload=data, session=self.session)
|
def next(self) -> Optional[T]:
'\n Returns the next element on this page.\n\n Returns:\n The next element on this page.\n '
try:
data = self.payload[self.current_item]
except IndexError:
return None
self.current_item += 1
return self.model(payload=data, session=self.session)<|docstring|>Returns the next element on this page.
Returns:
The next element on this page.<|endoftext|>
|
cf7f1b5e59defa39fe8dcf827a4e58d6c479649e9d26afb24554aab3271b29fc
|
def current(self) -> T:
'\n Returns the current element on this page.\n\n Returns:\n The current element on this page.\n '
data = self.payload[self.current_item]
return self.model(payload=data, session=self.session)
|
Returns the current element on this page.
Returns:
The current element on this page.
|
miku/paginator.py
|
current
|
blanketsucks/miku
| 3
|
python
|
def current(self) -> T:
'\n Returns the current element on this page.\n\n Returns:\n The current element on this page.\n '
data = self.payload[self.current_item]
return self.model(payload=data, session=self.session)
|
def current(self) -> T:
'\n Returns the current element on this page.\n\n Returns:\n The current element on this page.\n '
data = self.payload[self.current_item]
return self.model(payload=data, session=self.session)<|docstring|>Returns the current element on this page.
Returns:
The current element on this page.<|endoftext|>
|
ec3438bf557ff6ce48a9ace74f007e0f922ac9e88a1ee899da2466128d615ab2
|
def previous(self) -> T:
'\n Returns the previous element on this page.\n\n Returns:\n The previous element on this page.\n '
index = (self.current_item - 1)
if (self.current_item == 0):
index = 0
data = self.payload[index]
return self.model(payload=data, session=self.session)
|
Returns the previous element on this page.
Returns:
The previous element on this page.
|
miku/paginator.py
|
previous
|
blanketsucks/miku
| 3
|
python
|
def previous(self) -> T:
'\n Returns the previous element on this page.\n\n Returns:\n The previous element on this page.\n '
index = (self.current_item - 1)
if (self.current_item == 0):
index = 0
data = self.payload[index]
return self.model(payload=data, session=self.session)
|
def previous(self) -> T:
'\n Returns the previous element on this page.\n\n Returns:\n The previous element on this page.\n '
index = (self.current_item - 1)
if (self.current_item == 0):
index = 0
data = self.payload[index]
return self.model(payload=data, session=self.session)<|docstring|>Returns the previous element on this page.
Returns:
The previous element on this page.<|endoftext|>
|
5c7162d3c4290d9062fefc55bf9228bd50047e695ee4408e91017c2147cb7a08
|
def get_page(self, page: int) -> Optional[Page[T]]:
'\n Returns the page with that number if available.\n\n Args:\n page: The number of the page.\n\n Returns:\n a [Page](./page.md) object or None.\n '
return self.pages.get(page)
|
Returns the page with that number if available.
Args:
page: The number of the page.
Returns:
a [Page](./page.md) object or None.
|
miku/paginator.py
|
get_page
|
blanketsucks/miku
| 3
|
python
|
def get_page(self, page: int) -> Optional[Page[T]]:
'\n Returns the page with that number if available.\n\n Args:\n page: The number of the page.\n\n Returns:\n a [Page](./page.md) object or None.\n '
return self.pages.get(page)
|
def get_page(self, page: int) -> Optional[Page[T]]:
'\n Returns the page with that number if available.\n\n Args:\n page: The number of the page.\n\n Returns:\n a [Page](./page.md) object or None.\n '
return self.pages.get(page)<|docstring|>Returns the page with that number if available.
Args:
page: The number of the page.
Returns:
a [Page](./page.md) object or None.<|endoftext|>
|
bc374d46ed31ef274f0320a06eb259e8c4a6f7bf361e5917a34ac080f055c7f4
|
async def next(self) -> Optional[Page[T]]:
'\n Fetches the next page.\n\n Returns:\n a [Page](./page.md) object or None.\n '
if (not self.has_next_page):
return None
self.vars['page'] = self.next_page
json = (await self.http.request(self.query, self.vars))
data = json['data']
if (not data):
return None
page = data['Page']['pageInfo']
self.has_next_page = page['hasNextPage']
self.next_page = (page['currentPage'] + 1)
self.current_page = page['currentPage']
page = Page(self.type, json, self.model, self.http)
self.pages[self.current_page] = page
return page
|
Fetches the next page.
Returns:
a [Page](./page.md) object or None.
|
miku/paginator.py
|
next
|
blanketsucks/miku
| 3
|
python
|
async def next(self) -> Optional[Page[T]]:
'\n Fetches the next page.\n\n Returns:\n a [Page](./page.md) object or None.\n '
if (not self.has_next_page):
return None
self.vars['page'] = self.next_page
json = (await self.http.request(self.query, self.vars))
data = json['data']
if (not data):
return None
page = data['Page']['pageInfo']
self.has_next_page = page['hasNextPage']
self.next_page = (page['currentPage'] + 1)
self.current_page = page['currentPage']
page = Page(self.type, json, self.model, self.http)
self.pages[self.current_page] = page
return page
|
async def next(self) -> Optional[Page[T]]:
'\n Fetches the next page.\n\n Returns:\n a [Page](./page.md) object or None.\n '
if (not self.has_next_page):
return None
self.vars['page'] = self.next_page
json = (await self.http.request(self.query, self.vars))
data = json['data']
if (not data):
return None
page = data['Page']['pageInfo']
self.has_next_page = page['hasNextPage']
self.next_page = (page['currentPage'] + 1)
self.current_page = page['currentPage']
page = Page(self.type, json, self.model, self.http)
self.pages[self.current_page] = page
return page<|docstring|>Fetches the next page.
Returns:
a [Page](./page.md) object or None.<|endoftext|>
|
5688e3b94de46e10cd13f1ae284f2cefeb9dba1d79c5c3a4b3c05c5f5a46fb79
|
async def current(self) -> Optional[Page[T]]:
'\n Fetches the current page.\n\n Returns:\n a [Page](./page.md) object or None.\n '
json = (await self.http.request(self.query, self.vars))
data = json['data']
if (not data):
return None
return Page(self.type, json, self.model, self.http)
|
Fetches the current page.
Returns:
a [Page](./page.md) object or None.
|
miku/paginator.py
|
current
|
blanketsucks/miku
| 3
|
python
|
async def current(self) -> Optional[Page[T]]:
'\n Fetches the current page.\n\n Returns:\n a [Page](./page.md) object or None.\n '
json = (await self.http.request(self.query, self.vars))
data = json['data']
if (not data):
return None
return Page(self.type, json, self.model, self.http)
|
async def current(self) -> Optional[Page[T]]:
'\n Fetches the current page.\n\n Returns:\n a [Page](./page.md) object or None.\n '
json = (await self.http.request(self.query, self.vars))
data = json['data']
if (not data):
return None
return Page(self.type, json, self.model, self.http)<|docstring|>Fetches the current page.
Returns:
a [Page](./page.md) object or None.<|endoftext|>
|
47a57ebf8fc038bcac8b716cf934efd9cf95ebce59a24633b6659278ee3e4e99
|
async def previous(self) -> Optional[Page[T]]:
'\n Fetches the previous page.\n\n Returns:\n a [Page](./page.md) object or None.\n '
vars = self.vars.copy()
page = (self.current_page - 1)
if (self.current_page == 0):
page = 0
vars['page'] = page
json = (await self.http.request(self.query, vars))
data = json['data']
if (not data):
return None
return Page(self.type, json, self.model, self.http)
|
Fetches the previous page.
Returns:
a [Page](./page.md) object or None.
|
miku/paginator.py
|
previous
|
blanketsucks/miku
| 3
|
python
|
async def previous(self) -> Optional[Page[T]]:
'\n Fetches the previous page.\n\n Returns:\n a [Page](./page.md) object or None.\n '
vars = self.vars.copy()
page = (self.current_page - 1)
if (self.current_page == 0):
page = 0
vars['page'] = page
json = (await self.http.request(self.query, vars))
data = json['data']
if (not data):
return None
return Page(self.type, json, self.model, self.http)
|
async def previous(self) -> Optional[Page[T]]:
'\n Fetches the previous page.\n\n Returns:\n a [Page](./page.md) object or None.\n '
vars = self.vars.copy()
page = (self.current_page - 1)
if (self.current_page == 0):
page = 0
vars['page'] = page
json = (await self.http.request(self.query, vars))
data = json['data']
if (not data):
return None
return Page(self.type, json, self.model, self.http)<|docstring|>Fetches the previous page.
Returns:
a [Page](./page.md) object or None.<|endoftext|>
|
d6c66d4a84835bd4155c8830e4f98f364af425e70ac528cd85cdca7469fd2afa
|
async def collect(self) -> Data[Page[T]]:
'\n Collects all the fetchable pages and returns them as a list\n\n Returns:\n A list containing [Page](./page.md) objects. \n '
pages = Data()
while True:
page = (await self.next())
if (not page):
break
pages.extend(page)
return pages
|
Collects all the fetchable pages and returns them as a list
Returns:
A list containing [Page](./page.md) objects.
|
miku/paginator.py
|
collect
|
blanketsucks/miku
| 3
|
python
|
async def collect(self) -> Data[Page[T]]:
'\n Collects all the fetchable pages and returns them as a list\n\n Returns:\n A list containing [Page](./page.md) objects. \n '
pages = Data()
while True:
page = (await self.next())
if (not page):
break
pages.extend(page)
return pages
|
async def collect(self) -> Data[Page[T]]:
'\n Collects all the fetchable pages and returns them as a list\n\n Returns:\n A list containing [Page](./page.md) objects. \n '
pages = Data()
while True:
page = (await self.next())
if (not page):
break
pages.extend(page)
return pages<|docstring|>Collects all the fetchable pages and returns them as a list
Returns:
A list containing [Page](./page.md) objects.<|endoftext|>
|
988aa5df258d35b8d3a761e9f147eb573b3489806a81335cf2a47ef37c2ab580
|
def __aiter__(self) -> Paginator[T]:
'\n Returns:\n This same [Paginator](./paginator.md) object.\n '
return self
|
Returns:
This same [Paginator](./paginator.md) object.
|
miku/paginator.py
|
__aiter__
|
blanketsucks/miku
| 3
|
python
|
def __aiter__(self) -> Paginator[T]:
'\n Returns:\n This same [Paginator](./paginator.md) object.\n '
return self
|
def __aiter__(self) -> Paginator[T]:
'\n Returns:\n This same [Paginator](./paginator.md) object.\n '
return self<|docstring|>Returns:
This same [Paginator](./paginator.md) object.<|endoftext|>
|
c8a4c6b0e046ac4bd200329cd850236085624653f58b971af6c7b3be6c444e89
|
async def __anext__(self) -> Page[T]:
'\n Returns:\n The next [Page](./page.md).\n '
data = (await self.next())
if (not data):
raise StopAsyncIteration
return data
|
Returns:
The next [Page](./page.md).
|
miku/paginator.py
|
__anext__
|
blanketsucks/miku
| 3
|
python
|
async def __anext__(self) -> Page[T]:
'\n Returns:\n The next [Page](./page.md).\n '
data = (await self.next())
if (not data):
raise StopAsyncIteration
return data
|
async def __anext__(self) -> Page[T]:
'\n Returns:\n The next [Page](./page.md).\n '
data = (await self.next())
if (not data):
raise StopAsyncIteration
return data<|docstring|>Returns:
The next [Page](./page.md).<|endoftext|>
|
c0fb8cddfd4ba62a0900a77068db9b17d3eb77a895ad6ec9e7d1718f0d87e9bb
|
def trace():
'\n trace finds the line, the filename\n and error message and returns it\n to the user\n '
import traceback, inspect
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
filename = inspect.getfile(inspect.currentframe())
line = tbinfo.split(', ')[1]
synerror = traceback.format_exc().splitlines()[(- 1)]
return (line, filename, synerror)
|
trace finds the line, the filename
and error message and returns it
to the user
|
Scripts/AssetByStatus.py
|
trace
|
gavinr/adopta
| 1
|
python
|
def trace():
'\n trace finds the line, the filename\n and error message and returns it\n to the user\n '
import traceback, inspect
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
filename = inspect.getfile(inspect.currentframe())
line = tbinfo.split(', ')[1]
synerror = traceback.format_exc().splitlines()[(- 1)]
return (line, filename, synerror)
|
def trace():
'\n trace finds the line, the filename\n and error message and returns it\n to the user\n '
import traceback, inspect
tb = sys.exc_info()[2]
tbinfo = traceback.format_tb(tb)[0]
filename = inspect.getfile(inspect.currentframe())
line = tbinfo.split(', ')[1]
synerror = traceback.format_exc().splitlines()[(- 1)]
return (line, filename, synerror)<|docstring|>trace finds the line, the filename
and error message and returns it
to the user<|endoftext|>
|
f4d4859243f1a36ebee0dda9cf2f3af747c9f559b5a1d45210877f77af93b5a6
|
def testNonString(self):
'See if token parsing fails appropriately on non-strings'
generator = parseTokens(None)
with self.assertRaises(TypeError):
next(generator)
generator = parseTokens(3)
with self.assertRaises(TypeError):
next(generator)
generator = parseTokens(object())
with self.assertRaises(TypeError):
next(generator)
|
See if token parsing fails appropriately on non-strings
|
src/edrn.summarizer/edrn/summarizer/tests/test_dmccparser.py
|
testNonString
|
EDRN/DMCCBackend
| 0
|
python
|
def testNonString(self):
generator = parseTokens(None)
with self.assertRaises(TypeError):
next(generator)
generator = parseTokens(3)
with self.assertRaises(TypeError):
next(generator)
generator = parseTokens(object())
with self.assertRaises(TypeError):
next(generator)
|
def testNonString(self):
generator = parseTokens(None)
with self.assertRaises(TypeError):
next(generator)
generator = parseTokens(3)
with self.assertRaises(TypeError):
next(generator)
generator = parseTokens(object())
with self.assertRaises(TypeError):
next(generator)<|docstring|>See if token parsing fails appropriately on non-strings<|endoftext|>
|
6503890f35d2af5923eebcf257e3ec0ae257ab9498ba90a22a178d72bac8fb78
|
def testEmptyString(self):
'Ensure we get no key-value tokens from an empty string'
generator = parseTokens('')
with self.assertRaises(StopIteration):
next(generator)
|
Ensure we get no key-value tokens from an empty string
|
src/edrn.summarizer/edrn/summarizer/tests/test_dmccparser.py
|
testEmptyString
|
EDRN/DMCCBackend
| 0
|
python
|
def testEmptyString(self):
generator = parseTokens()
with self.assertRaises(StopIteration):
next(generator)
|
def testEmptyString(self):
generator = parseTokens()
with self.assertRaises(StopIteration):
next(generator)<|docstring|>Ensure we get no key-value tokens from an empty string<|endoftext|>
|
1534c4486e58dd2a7f23aff44145ecd8034e355b56f7f652e70341f9a544a303
|
def testGarbageString(self):
'Check that we get no key-value tokens from a garbage string'
generator = parseTokens('No angle brackets')
with self.assertRaises(ValueError):
next(generator)
|
Check that we get no key-value tokens from a garbage string
|
src/edrn.summarizer/edrn/summarizer/tests/test_dmccparser.py
|
testGarbageString
|
EDRN/DMCCBackend
| 0
|
python
|
def testGarbageString(self):
generator = parseTokens('No angle brackets')
with self.assertRaises(ValueError):
next(generator)
|
def testGarbageString(self):
generator = parseTokens('No angle brackets')
with self.assertRaises(ValueError):
next(generator)<|docstring|>Check that we get no key-value tokens from a garbage string<|endoftext|>
|
4ce650407c140a45863c715f876ad0b7e3b6aff556a3ef200b83722dc32ac692
|
def testSingleElement(self):
'Test if we get a single key-value token from a DMCC-formatted string'
(key, value) = next(parseTokens('<Temperature>Spicy</Temperature>'))
self.assertEquals('Temperature', key)
self.assertEquals('Spicy', value)
|
Test if we get a single key-value token from a DMCC-formatted string
|
src/edrn.summarizer/edrn/summarizer/tests/test_dmccparser.py
|
testSingleElement
|
EDRN/DMCCBackend
| 0
|
python
|
def testSingleElement(self):
(key, value) = next(parseTokens('<Temperature>Spicy</Temperature>'))
self.assertEquals('Temperature', key)
self.assertEquals('Spicy', value)
|
def testSingleElement(self):
(key, value) = next(parseTokens('<Temperature>Spicy</Temperature>'))
self.assertEquals('Temperature', key)
self.assertEquals('Spicy', value)<|docstring|>Test if we get a single key-value token from a DMCC-formatted string<|endoftext|>
|
9dde413fd5f6531844fdf266b810a257a805893bf6fa0ef6d2cd2ce43e14fc1d
|
def testMultipleElements(self):
'Verify that we get multiple key-value tokens from a DMCC-formatted string'
(keys, values) = ([], [])
for (k, v) in parseTokens('<Temperature>Spicy</Temperature><Protein>Shrimp</Protein><Sauce>Poblano</Sauce>'):
keys.append(k)
values.append(v)
self.assertEquals(['Temperature', 'Protein', 'Sauce'], keys)
self.assertEquals(['Spicy', 'Shrimp', 'Poblano'], values)
|
Verify that we get multiple key-value tokens from a DMCC-formatted string
|
src/edrn.summarizer/edrn/summarizer/tests/test_dmccparser.py
|
testMultipleElements
|
EDRN/DMCCBackend
| 0
|
python
|
def testMultipleElements(self):
(keys, values) = ([], [])
for (k, v) in parseTokens('<Temperature>Spicy</Temperature><Protein>Shrimp</Protein><Sauce>Poblano</Sauce>'):
keys.append(k)
values.append(v)
self.assertEquals(['Temperature', 'Protein', 'Sauce'], keys)
self.assertEquals(['Spicy', 'Shrimp', 'Poblano'], values)
|
def testMultipleElements(self):
(keys, values) = ([], [])
for (k, v) in parseTokens('<Temperature>Spicy</Temperature><Protein>Shrimp</Protein><Sauce>Poblano</Sauce>'):
keys.append(k)
values.append(v)
self.assertEquals(['Temperature', 'Protein', 'Sauce'], keys)
self.assertEquals(['Spicy', 'Shrimp', 'Poblano'], values)<|docstring|>Verify that we get multiple key-value tokens from a DMCC-formatted string<|endoftext|>
|
546ddcccbfd594889a5a802c3b5149c2ea776afb7aace985c829119f12286a5b
|
def testExtraSpace(self):
'See to it that extra white space is stripped between tokens'
(key, value) = next(parseTokens(' <Temperature>Spicy</Temperature>'))
self.assertEquals(('Temperature', 'Spicy'), (key, value))
(key, value) = next(parseTokens('<Temperature>Spicy</Temperature> '))
self.assertEquals(('Temperature', 'Spicy'), (key, value))
(key, value) = next(parseTokens(' <Temperature>Spicy</Temperature> '))
self.assertEquals(('Temperature', 'Spicy'), (key, value))
(keys, values) = ([], [])
for (k, v) in parseTokens(' <Temperature>Spicy</Temperature> <Protein>Shrimp</Protein> <Sauce>Poblano</Sauce>'):
keys.append(k)
values.append(v)
self.assertEquals(['Temperature', 'Protein', 'Sauce'], keys)
self.assertEquals(['Spicy', 'Shrimp', 'Poblano'], values)
|
See to it that extra white space is stripped between tokens
|
src/edrn.summarizer/edrn/summarizer/tests/test_dmccparser.py
|
testExtraSpace
|
EDRN/DMCCBackend
| 0
|
python
|
def testExtraSpace(self):
(key, value) = next(parseTokens(' <Temperature>Spicy</Temperature>'))
self.assertEquals(('Temperature', 'Spicy'), (key, value))
(key, value) = next(parseTokens('<Temperature>Spicy</Temperature> '))
self.assertEquals(('Temperature', 'Spicy'), (key, value))
(key, value) = next(parseTokens(' <Temperature>Spicy</Temperature> '))
self.assertEquals(('Temperature', 'Spicy'), (key, value))
(keys, values) = ([], [])
for (k, v) in parseTokens(' <Temperature>Spicy</Temperature> <Protein>Shrimp</Protein> <Sauce>Poblano</Sauce>'):
keys.append(k)
values.append(v)
self.assertEquals(['Temperature', 'Protein', 'Sauce'], keys)
self.assertEquals(['Spicy', 'Shrimp', 'Poblano'], values)
|
def testExtraSpace(self):
(key, value) = next(parseTokens(' <Temperature>Spicy</Temperature>'))
self.assertEquals(('Temperature', 'Spicy'), (key, value))
(key, value) = next(parseTokens('<Temperature>Spicy</Temperature> '))
self.assertEquals(('Temperature', 'Spicy'), (key, value))
(key, value) = next(parseTokens(' <Temperature>Spicy</Temperature> '))
self.assertEquals(('Temperature', 'Spicy'), (key, value))
(keys, values) = ([], [])
for (k, v) in parseTokens(' <Temperature>Spicy</Temperature> <Protein>Shrimp</Protein> <Sauce>Poblano</Sauce>'):
keys.append(k)
values.append(v)
self.assertEquals(['Temperature', 'Protein', 'Sauce'], keys)
self.assertEquals(['Spicy', 'Shrimp', 'Poblano'], values)<|docstring|>See to it that extra white space is stripped between tokens<|endoftext|>
|
c779ebfe2323b7b7b25d0e7cf5097f6b87fe7900fe7fddbab27ff66972602922
|
def testEmptyValues(self):
'Check if we can parse tokens with no values in them'
(key, value) = next(parseTokens('<EmptyKey></EmptyKey>'))
self.assertEquals(('EmptyKey', ''), (key, value))
|
Check if we can parse tokens with no values in them
|
src/edrn.summarizer/edrn/summarizer/tests/test_dmccparser.py
|
testEmptyValues
|
EDRN/DMCCBackend
| 0
|
python
|
def testEmptyValues(self):
(key, value) = next(parseTokens('<EmptyKey></EmptyKey>'))
self.assertEquals(('EmptyKey', ), (key, value))
|
def testEmptyValues(self):
(key, value) = next(parseTokens('<EmptyKey></EmptyKey>'))
self.assertEquals(('EmptyKey', ), (key, value))<|docstring|>Check if we can parse tokens with no values in them<|endoftext|>
|
7765b14ba9282eae46b357df3486eddc6c4a78888724f3155ceff57440e362f4
|
def testUnterminatedElements(self):
'Confirm we can handle badly formatted DMCC strings'
generator = parseTokens('<Unterminated>Value')
with self.assertRaises(ValueError):
next(generator)
|
Confirm we can handle badly formatted DMCC strings
|
src/edrn.summarizer/edrn/summarizer/tests/test_dmccparser.py
|
testUnterminatedElements
|
EDRN/DMCCBackend
| 0
|
python
|
def testUnterminatedElements(self):
generator = parseTokens('<Unterminated>Value')
with self.assertRaises(ValueError):
next(generator)
|
def testUnterminatedElements(self):
generator = parseTokens('<Unterminated>Value')
with self.assertRaises(ValueError):
next(generator)<|docstring|>Confirm we can handle badly formatted DMCC strings<|endoftext|>
|
e1a3ec6093f5e56b11e6aea8005153fc108625e7c0a38e3da4b3122683270c5b
|
def testMultilineValues(self):
'Assure we handle values with embedded newlines properly'
(k, v) = next(parseTokens('<msg>Hello,\nworld.</msg>'))
self.assertEquals('msg', k)
self.assertEquals('Hello,\nworld.', v)
|
Assure we handle values with embedded newlines properly
|
src/edrn.summarizer/edrn/summarizer/tests/test_dmccparser.py
|
testMultilineValues
|
EDRN/DMCCBackend
| 0
|
python
|
def testMultilineValues(self):
(k, v) = next(parseTokens('<msg>Hello,\nworld.</msg>'))
self.assertEquals('msg', k)
self.assertEquals('Hello,\nworld.', v)
|
def testMultilineValues(self):
(k, v) = next(parseTokens('<msg>Hello,\nworld.</msg>'))
self.assertEquals('msg', k)
self.assertEquals('Hello,\nworld.', v)<|docstring|>Assure we handle values with embedded newlines properly<|endoftext|>
|
40a2b4e28a4e61741259310b33e93e8e9222769c021a8c4ae6ac4e89a41c9a84
|
def circle_point(cx, cy, rx, ry, a):
'\n Translates polar coords to cartesian\n '
x = (cx + (rx * cos(a)))
y = (cy + (ry * sin(a)))
return (x, y)
|
Translates polar coords to cartesian
|
ppy_terminal/sketches/templates/template_standalone.py
|
circle_point
|
TechnologyClassroom/generative_art
| 1
|
python
|
def circle_point(cx, cy, rx, ry, a):
'\n \n '
x = (cx + (rx * cos(a)))
y = (cy + (ry * sin(a)))
return (x, y)
|
def circle_point(cx, cy, rx, ry, a):
'\n \n '
x = (cx + (rx * cos(a)))
y = (cy + (ry * sin(a)))
return (x, y)<|docstring|>Translates polar coords to cartesian<|endoftext|>
|
b311e2b84d8b38ec8419fd5a08c3a3f4146cc277f6194ed76c5457ac5affea48
|
def noise_loop(a, r, min_val, max_val, x_c=0, y_c=0):
'\n Samples 2D Perlin noise in a circle to make smooth noise loops\n Adapted from https://github.com/CodingTrain/website/blob/master/CodingChallenges/CC_136_Polar_Noise_Loop_2/P5/noiseLoop.js\n '
xoff = map(cos(a), (- 1), 1, x_c, (x_c + (2 * r)))
yoff = map(sin(a), (- 1), 1, y_c, (y_c + (2 * r)))
r = noise(xoff, yoff)
return map(r, 0, 1, min_val, max_val)
|
Samples 2D Perlin noise in a circle to make smooth noise loops
Adapted from https://github.com/CodingTrain/website/blob/master/CodingChallenges/CC_136_Polar_Noise_Loop_2/P5/noiseLoop.js
|
ppy_terminal/sketches/templates/template_standalone.py
|
noise_loop
|
TechnologyClassroom/generative_art
| 1
|
python
|
def noise_loop(a, r, min_val, max_val, x_c=0, y_c=0):
'\n Samples 2D Perlin noise in a circle to make smooth noise loops\n Adapted from https://github.com/CodingTrain/website/blob/master/CodingChallenges/CC_136_Polar_Noise_Loop_2/P5/noiseLoop.js\n '
xoff = map(cos(a), (- 1), 1, x_c, (x_c + (2 * r)))
yoff = map(sin(a), (- 1), 1, y_c, (y_c + (2 * r)))
r = noise(xoff, yoff)
return map(r, 0, 1, min_val, max_val)
|
def noise_loop(a, r, min_val, max_val, x_c=0, y_c=0):
'\n Samples 2D Perlin noise in a circle to make smooth noise loops\n Adapted from https://github.com/CodingTrain/website/blob/master/CodingChallenges/CC_136_Polar_Noise_Loop_2/P5/noiseLoop.js\n '
xoff = map(cos(a), (- 1), 1, x_c, (x_c + (2 * r)))
yoff = map(sin(a), (- 1), 1, y_c, (y_c + (2 * r)))
r = noise(xoff, yoff)
return map(r, 0, 1, min_val, max_val)<|docstring|>Samples 2D Perlin noise in a circle to make smooth noise loops
Adapted from https://github.com/CodingTrain/website/blob/master/CodingChallenges/CC_136_Polar_Noise_Loop_2/P5/noiseLoop.js<|endoftext|>
|
a03b48bd982cdd4b92a3c01892117f6041761bbc32806fa21494b4a6f415879f
|
def frange(start, end=None, increment=None):
'\n Adapted from http://code.activestate.com/recipes/66472\n '
if (end == None):
end = (start + 0.0)
start = 0.0
if (increment == None):
increment = 1.0
L = []
while 1:
next = (start + (len(L) * increment))
if ((increment > 0) and (next >= end)):
break
elif ((increment < 0) and (next <= end)):
break
L.append(next)
return L
|
Adapted from http://code.activestate.com/recipes/66472
|
ppy_terminal/sketches/templates/template_standalone.py
|
frange
|
TechnologyClassroom/generative_art
| 1
|
python
|
def frange(start, end=None, increment=None):
'\n \n '
if (end == None):
end = (start + 0.0)
start = 0.0
if (increment == None):
increment = 1.0
L = []
while 1:
next = (start + (len(L) * increment))
if ((increment > 0) and (next >= end)):
break
elif ((increment < 0) and (next <= end)):
break
L.append(next)
return L
|
def frange(start, end=None, increment=None):
'\n \n '
if (end == None):
end = (start + 0.0)
start = 0.0
if (increment == None):
increment = 1.0
L = []
while 1:
next = (start + (len(L) * increment))
if ((increment > 0) and (next >= end)):
break
elif ((increment < 0) and (next <= end)):
break
L.append(next)
return L<|docstring|>Adapted from http://code.activestate.com/recipes/66472<|endoftext|>
|
aff5be685eeb223dfaaf38c6e5a13ffa20a896d64431b48cd40b1024aa41e02a
|
def normals(depthmap, normalize=True, keep_dims=True):
'Calculate depth normals as normals = gF(x,y,z) = (-dF/dx, -dF/dy, 1)\n\n Args:\n depthmap (np.ndarray): depth map of any dtype, single channel, len(depthmap.shape) == 3\n normalize (bool, optional): if True, normals will be normalized to have unit-magnitude\n Default: True\n keep_dims (bool, optional):\n if True, normals shape will be equals to depthmap shape,\n if False, normals shape will be smaller than depthmap shape.\n Default: True\n\n Returns:\n Depth normals\n\n '
depthmap = np.asarray(depthmap, np.float32)
if (keep_dims is True):
mask = (depthmap != 0)
else:
mask = (depthmap[(1:(- 1), 1:(- 1))] != 0)
if (keep_dims is True):
normals = np.zeros((depthmap.shape[0], depthmap.shape[1], 3), dtype=np.float32)
normals[(1:(- 1), 1:(- 1), 0)] = ((- (depthmap[(2:, 1:(- 1))] - depthmap[(:(- 2), 1:(- 1))])) / 2)
normals[(1:(- 1), 1:(- 1), 1)] = ((- (depthmap[(1:(- 1), 2:)] - depthmap[(1:(- 1), :(- 2))])) / 2)
else:
normals = np.zeros(((depthmap.shape[0] - 2), (depthmap.shape[1] - 2), 3), dtype=np.float32)
normals[(:, :, 0)] = ((- (depthmap[(2:, 1:(- 1))] - depthmap[(:(- 2), 1:(- 1))])) / 2)
normals[(:, :, 1)] = ((- (depthmap[(1:(- 1), 2:)] - depthmap[(1:(- 1), :(- 2))])) / 2)
normals[(:, :, 2)] = 1
normals[(~ mask)] = [0, 0, 0]
if normalize:
div = (np.linalg.norm(normals[mask], ord=2, axis=(- 1), keepdims=True).repeat(3, axis=(- 1)) + 1e-12)
normals[mask] /= div
return normals
|
Calculate depth normals as normals = gF(x,y,z) = (-dF/dx, -dF/dy, 1)
Args:
depthmap (np.ndarray): depth map of any dtype, single channel, len(depthmap.shape) == 3
normalize (bool, optional): if True, normals will be normalized to have unit-magnitude
Default: True
keep_dims (bool, optional):
if True, normals shape will be equals to depthmap shape,
if False, normals shape will be smaller than depthmap shape.
Default: True
Returns:
Depth normals
|
src/datasets/utils/normals.py
|
normals
|
aimagelab/TransformerBasedGestureRecognition
| 15
|
python
|
def normals(depthmap, normalize=True, keep_dims=True):
'Calculate depth normals as normals = gF(x,y,z) = (-dF/dx, -dF/dy, 1)\n\n Args:\n depthmap (np.ndarray): depth map of any dtype, single channel, len(depthmap.shape) == 3\n normalize (bool, optional): if True, normals will be normalized to have unit-magnitude\n Default: True\n keep_dims (bool, optional):\n if True, normals shape will be equals to depthmap shape,\n if False, normals shape will be smaller than depthmap shape.\n Default: True\n\n Returns:\n Depth normals\n\n '
depthmap = np.asarray(depthmap, np.float32)
if (keep_dims is True):
mask = (depthmap != 0)
else:
mask = (depthmap[(1:(- 1), 1:(- 1))] != 0)
if (keep_dims is True):
normals = np.zeros((depthmap.shape[0], depthmap.shape[1], 3), dtype=np.float32)
normals[(1:(- 1), 1:(- 1), 0)] = ((- (depthmap[(2:, 1:(- 1))] - depthmap[(:(- 2), 1:(- 1))])) / 2)
normals[(1:(- 1), 1:(- 1), 1)] = ((- (depthmap[(1:(- 1), 2:)] - depthmap[(1:(- 1), :(- 2))])) / 2)
else:
normals = np.zeros(((depthmap.shape[0] - 2), (depthmap.shape[1] - 2), 3), dtype=np.float32)
normals[(:, :, 0)] = ((- (depthmap[(2:, 1:(- 1))] - depthmap[(:(- 2), 1:(- 1))])) / 2)
normals[(:, :, 1)] = ((- (depthmap[(1:(- 1), 2:)] - depthmap[(1:(- 1), :(- 2))])) / 2)
normals[(:, :, 2)] = 1
normals[(~ mask)] = [0, 0, 0]
if normalize:
div = (np.linalg.norm(normals[mask], ord=2, axis=(- 1), keepdims=True).repeat(3, axis=(- 1)) + 1e-12)
normals[mask] /= div
return normals
|
def normals(depthmap, normalize=True, keep_dims=True):
'Calculate depth normals as normals = gF(x,y,z) = (-dF/dx, -dF/dy, 1)\n\n Args:\n depthmap (np.ndarray): depth map of any dtype, single channel, len(depthmap.shape) == 3\n normalize (bool, optional): if True, normals will be normalized to have unit-magnitude\n Default: True\n keep_dims (bool, optional):\n if True, normals shape will be equals to depthmap shape,\n if False, normals shape will be smaller than depthmap shape.\n Default: True\n\n Returns:\n Depth normals\n\n '
depthmap = np.asarray(depthmap, np.float32)
if (keep_dims is True):
mask = (depthmap != 0)
else:
mask = (depthmap[(1:(- 1), 1:(- 1))] != 0)
if (keep_dims is True):
normals = np.zeros((depthmap.shape[0], depthmap.shape[1], 3), dtype=np.float32)
normals[(1:(- 1), 1:(- 1), 0)] = ((- (depthmap[(2:, 1:(- 1))] - depthmap[(:(- 2), 1:(- 1))])) / 2)
normals[(1:(- 1), 1:(- 1), 1)] = ((- (depthmap[(1:(- 1), 2:)] - depthmap[(1:(- 1), :(- 2))])) / 2)
else:
normals = np.zeros(((depthmap.shape[0] - 2), (depthmap.shape[1] - 2), 3), dtype=np.float32)
normals[(:, :, 0)] = ((- (depthmap[(2:, 1:(- 1))] - depthmap[(:(- 2), 1:(- 1))])) / 2)
normals[(:, :, 1)] = ((- (depthmap[(1:(- 1), 2:)] - depthmap[(1:(- 1), :(- 2))])) / 2)
normals[(:, :, 2)] = 1
normals[(~ mask)] = [0, 0, 0]
if normalize:
div = (np.linalg.norm(normals[mask], ord=2, axis=(- 1), keepdims=True).repeat(3, axis=(- 1)) + 1e-12)
normals[mask] /= div
return normals<|docstring|>Calculate depth normals as normals = gF(x,y,z) = (-dF/dx, -dF/dy, 1)
Args:
depthmap (np.ndarray): depth map of any dtype, single channel, len(depthmap.shape) == 3
normalize (bool, optional): if True, normals will be normalized to have unit-magnitude
Default: True
keep_dims (bool, optional):
if True, normals shape will be equals to depthmap shape,
if False, normals shape will be smaller than depthmap shape.
Default: True
Returns:
Depth normals<|endoftext|>
|
fc38f33069b17be7b3669370887316129c7bc008592a8539ef09f80ea0b04fac
|
def normals_multi(depthmaps, normalize=True, keep_dims=True):
'Calculate depth normals for multiple depthmaps inputs\n\n Args:\n depthmap (np.ndarray): multiple input depth maps\n normalize (bool, optional): if True, normals will be normalized to have unit-magnitude\n Default: True\n keep_dims (bool, optional):\n if True, normals shape will be equals to depthmap shape,\n if False, normals shape will be smaller than depthmap shape.\n Default: True\n\n Returns:\n Depth normals\n\n '
n_out = np.zeros((depthmaps.shape[0], depthmaps.shape[1], 3, depthmaps.shape[(- 1)]))
for i in range(depthmaps.shape[(- 1)]):
n_out[(..., i)] = normals(depthmaps[(..., 0, i)], normalize, keep_dims)
return n_out
|
Calculate depth normals for multiple depthmaps inputs
Args:
depthmap (np.ndarray): multiple input depth maps
normalize (bool, optional): if True, normals will be normalized to have unit-magnitude
Default: True
keep_dims (bool, optional):
if True, normals shape will be equals to depthmap shape,
if False, normals shape will be smaller than depthmap shape.
Default: True
Returns:
Depth normals
|
src/datasets/utils/normals.py
|
normals_multi
|
aimagelab/TransformerBasedGestureRecognition
| 15
|
python
|
def normals_multi(depthmaps, normalize=True, keep_dims=True):
'Calculate depth normals for multiple depthmaps inputs\n\n Args:\n depthmap (np.ndarray): multiple input depth maps\n normalize (bool, optional): if True, normals will be normalized to have unit-magnitude\n Default: True\n keep_dims (bool, optional):\n if True, normals shape will be equals to depthmap shape,\n if False, normals shape will be smaller than depthmap shape.\n Default: True\n\n Returns:\n Depth normals\n\n '
n_out = np.zeros((depthmaps.shape[0], depthmaps.shape[1], 3, depthmaps.shape[(- 1)]))
for i in range(depthmaps.shape[(- 1)]):
n_out[(..., i)] = normals(depthmaps[(..., 0, i)], normalize, keep_dims)
return n_out
|
def normals_multi(depthmaps, normalize=True, keep_dims=True):
'Calculate depth normals for multiple depthmaps inputs\n\n Args:\n depthmap (np.ndarray): multiple input depth maps\n normalize (bool, optional): if True, normals will be normalized to have unit-magnitude\n Default: True\n keep_dims (bool, optional):\n if True, normals shape will be equals to depthmap shape,\n if False, normals shape will be smaller than depthmap shape.\n Default: True\n\n Returns:\n Depth normals\n\n '
n_out = np.zeros((depthmaps.shape[0], depthmaps.shape[1], 3, depthmaps.shape[(- 1)]))
for i in range(depthmaps.shape[(- 1)]):
n_out[(..., i)] = normals(depthmaps[(..., 0, i)], normalize, keep_dims)
return n_out<|docstring|>Calculate depth normals for multiple depthmaps inputs
Args:
depthmap (np.ndarray): multiple input depth maps
normalize (bool, optional): if True, normals will be normalized to have unit-magnitude
Default: True
keep_dims (bool, optional):
if True, normals shape will be equals to depthmap shape,
if False, normals shape will be smaller than depthmap shape.
Default: True
Returns:
Depth normals<|endoftext|>
|
1e6c7a465871f299263e5e93d53a0be51cecbaa6752d1bcc24258f7b6cee9674
|
def makeXsecTable(compositeName, xsType, mgFlux, isotxs, headerFormat='$ xsecs for {}', tableFormat='\n{mcnpId} {nG:.5e} {nF:.5e} {n2n:.5e} {n3n:.5e} {nA:.5e} {nP:.5e}'):
"\n Make a cross section table for depletion physics input decks.\n\n Parameters\n ----------\n armiObject: armiObject\n an armi object -- batch or block --\n with a .p.xsType and a getMgFlux method\n activeNuclides: list\n a list of the nucNames of active isotopes\n isotxs: isotxs object\n headerFormat: string (optional)\n this is the format in which the elements of the header with be returned\n -- i.e. if you use a .format() call with the case name you'll return a\n formatted list of string elements\n tableFormat: string (optional)\n this is the format in which the elements of the table with be returned\n -- i.e. if you use a .format() call with mcnpId, nG, nF, n2n, n3n, nA,\n and nP you'll get the format you want. If you use a .format() call with the case name you'll return a\n formatted list of string elements\n Results\n -------\n output: list\n a list of string elements that together make a xsec card\n "
xsTable = CrossSectionTable()
if ((not xsType) or (not (sum(mgFlux) > 0))):
return []
xsTable.setName(compositeName)
totalFlux = sum(mgFlux)
for (nucLabel, nuc) in isotxs.items():
if (xsType != xsLibraries.getSuffixFromNuclideLabel(nucLabel)):
continue
nucName = nuc.name
nb = nuclideBases.byName[nucName]
if isinstance(nb, (nuclideBases.LumpNuclideBase, nuclideBases.DummyNuclideBase)):
continue
microMultiGroupXS = isotxs[nucLabel].micros
if (not isinstance(nb, nuclideBases.NaturalNuclideBase)):
xsTable.addMultiGroupXS(nucName, microMultiGroupXS, mgFlux, totalFlux)
return xsTable.getXsecTable(headerFormat=headerFormat, tableFormat=tableFormat)
|
Make a cross section table for depletion physics input decks.
Parameters
----------
armiObject: armiObject
an armi object -- batch or block --
with a .p.xsType and a getMgFlux method
activeNuclides: list
a list of the nucNames of active isotopes
isotxs: isotxs object
headerFormat: string (optional)
this is the format in which the elements of the header with be returned
-- i.e. if you use a .format() call with the case name you'll return a
formatted list of string elements
tableFormat: string (optional)
this is the format in which the elements of the table with be returned
-- i.e. if you use a .format() call with mcnpId, nG, nF, n2n, n3n, nA,
and nP you'll get the format you want. If you use a .format() call with the case name you'll return a
formatted list of string elements
Results
-------
output: list
a list of string elements that together make a xsec card
|
armi/physics/neutronics/isotopicDepletion/isotopicDepletionInterface.py
|
makeXsecTable
|
crisobg1/armi
| 1
|
python
|
def makeXsecTable(compositeName, xsType, mgFlux, isotxs, headerFormat='$ xsecs for {}', tableFormat='\n{mcnpId} {nG:.5e} {nF:.5e} {n2n:.5e} {n3n:.5e} {nA:.5e} {nP:.5e}'):
"\n Make a cross section table for depletion physics input decks.\n\n Parameters\n ----------\n armiObject: armiObject\n an armi object -- batch or block --\n with a .p.xsType and a getMgFlux method\n activeNuclides: list\n a list of the nucNames of active isotopes\n isotxs: isotxs object\n headerFormat: string (optional)\n this is the format in which the elements of the header with be returned\n -- i.e. if you use a .format() call with the case name you'll return a\n formatted list of string elements\n tableFormat: string (optional)\n this is the format in which the elements of the table with be returned\n -- i.e. if you use a .format() call with mcnpId, nG, nF, n2n, n3n, nA,\n and nP you'll get the format you want. If you use a .format() call with the case name you'll return a\n formatted list of string elements\n Results\n -------\n output: list\n a list of string elements that together make a xsec card\n "
xsTable = CrossSectionTable()
if ((not xsType) or (not (sum(mgFlux) > 0))):
return []
xsTable.setName(compositeName)
totalFlux = sum(mgFlux)
for (nucLabel, nuc) in isotxs.items():
if (xsType != xsLibraries.getSuffixFromNuclideLabel(nucLabel)):
continue
nucName = nuc.name
nb = nuclideBases.byName[nucName]
if isinstance(nb, (nuclideBases.LumpNuclideBase, nuclideBases.DummyNuclideBase)):
continue
microMultiGroupXS = isotxs[nucLabel].micros
if (not isinstance(nb, nuclideBases.NaturalNuclideBase)):
xsTable.addMultiGroupXS(nucName, microMultiGroupXS, mgFlux, totalFlux)
return xsTable.getXsecTable(headerFormat=headerFormat, tableFormat=tableFormat)
|
def makeXsecTable(compositeName, xsType, mgFlux, isotxs, headerFormat='$ xsecs for {}', tableFormat='\n{mcnpId} {nG:.5e} {nF:.5e} {n2n:.5e} {n3n:.5e} {nA:.5e} {nP:.5e}'):
"\n Make a cross section table for depletion physics input decks.\n\n Parameters\n ----------\n armiObject: armiObject\n an armi object -- batch or block --\n with a .p.xsType and a getMgFlux method\n activeNuclides: list\n a list of the nucNames of active isotopes\n isotxs: isotxs object\n headerFormat: string (optional)\n this is the format in which the elements of the header with be returned\n -- i.e. if you use a .format() call with the case name you'll return a\n formatted list of string elements\n tableFormat: string (optional)\n this is the format in which the elements of the table with be returned\n -- i.e. if you use a .format() call with mcnpId, nG, nF, n2n, n3n, nA,\n and nP you'll get the format you want. If you use a .format() call with the case name you'll return a\n formatted list of string elements\n Results\n -------\n output: list\n a list of string elements that together make a xsec card\n "
xsTable = CrossSectionTable()
if ((not xsType) or (not (sum(mgFlux) > 0))):
return []
xsTable.setName(compositeName)
totalFlux = sum(mgFlux)
for (nucLabel, nuc) in isotxs.items():
if (xsType != xsLibraries.getSuffixFromNuclideLabel(nucLabel)):
continue
nucName = nuc.name
nb = nuclideBases.byName[nucName]
if isinstance(nb, (nuclideBases.LumpNuclideBase, nuclideBases.DummyNuclideBase)):
continue
microMultiGroupXS = isotxs[nucLabel].micros
if (not isinstance(nb, nuclideBases.NaturalNuclideBase)):
xsTable.addMultiGroupXS(nucName, microMultiGroupXS, mgFlux, totalFlux)
return xsTable.getXsecTable(headerFormat=headerFormat, tableFormat=tableFormat)<|docstring|>Make a cross section table for depletion physics input decks.
Parameters
----------
armiObject: armiObject
an armi object -- batch or block --
with a .p.xsType and a getMgFlux method
activeNuclides: list
a list of the nucNames of active isotopes
isotxs: isotxs object
headerFormat: string (optional)
this is the format in which the elements of the header with be returned
-- i.e. if you use a .format() call with the case name you'll return a
formatted list of string elements
tableFormat: string (optional)
this is the format in which the elements of the table with be returned
-- i.e. if you use a .format() call with mcnpId, nG, nF, n2n, n3n, nA,
and nP you'll get the format you want. If you use a .format() call with the case name you'll return a
formatted list of string elements
Results
-------
output: list
a list of string elements that together make a xsec card<|endoftext|>
|
f44eb568ca6b665263e0a657537f1699fc92e5f6547557a281b87dd46fc29057
|
def addToDeplete(self, armiObj):
'Add the oject to the group of objects to be depleted.'
self._depleteByName[armiObj.getName()] = armiObj
|
Add the oject to the group of objects to be depleted.
|
armi/physics/neutronics/isotopicDepletion/isotopicDepletionInterface.py
|
addToDeplete
|
crisobg1/armi
| 1
|
python
|
def addToDeplete(self, armiObj):
self._depleteByName[armiObj.getName()] = armiObj
|
def addToDeplete(self, armiObj):
self._depleteByName[armiObj.getName()] = armiObj<|docstring|>Add the oject to the group of objects to be depleted.<|endoftext|>
|
4d48a8d6ebebac164e75633b726b7d3f3c570418e1a3dfca3fc0a791b8d910f3
|
def setToDeplete(self, armiObjects):
'Change the group of objects to deplete to the specified group.'
listOfTuples = [(obj.getName(), obj) for obj in armiObjects]
self._depleteByName = collections.OrderedDict(listOfTuples)
|
Change the group of objects to deplete to the specified group.
|
armi/physics/neutronics/isotopicDepletion/isotopicDepletionInterface.py
|
setToDeplete
|
crisobg1/armi
| 1
|
python
|
def setToDeplete(self, armiObjects):
listOfTuples = [(obj.getName(), obj) for obj in armiObjects]
self._depleteByName = collections.OrderedDict(listOfTuples)
|
def setToDeplete(self, armiObjects):
listOfTuples = [(obj.getName(), obj) for obj in armiObjects]
self._depleteByName = collections.OrderedDict(listOfTuples)<|docstring|>Change the group of objects to deplete to the specified group.<|endoftext|>
|
ab620b51ee55c56cb24826f9c6006c54188e3ebcaeb1fb79727c97e6d175a06a
|
def getToDeplete(self):
'Return objects to be depleted.'
return list(self._depleteByName.values())
|
Return objects to be depleted.
|
armi/physics/neutronics/isotopicDepletion/isotopicDepletionInterface.py
|
getToDeplete
|
crisobg1/armi
| 1
|
python
|
def getToDeplete(self):
return list(self._depleteByName.values())
|
def getToDeplete(self):
return list(self._depleteByName.values())<|docstring|>Return objects to be depleted.<|endoftext|>
|
e9f61fdadad4ebaa5bb1a4c92a719b454d5f8718e3c43f5d1aa4d2260492c53e
|
def run(self):
"\n Submit depletion case with external solver to the cluster.\n\n In addition to running the physics kernel, this method calls the waitForJob method\n to wait for it job to finish\n\n comm = MPI.COMM_SELF.Spawn(sys.executable,args=['cpi.py'],maxprocs=5)\n "
return NotImplementedError
|
Submit depletion case with external solver to the cluster.
In addition to running the physics kernel, this method calls the waitForJob method
to wait for it job to finish
comm = MPI.COMM_SELF.Spawn(sys.executable,args=['cpi.py'],maxprocs=5)
|
armi/physics/neutronics/isotopicDepletion/isotopicDepletionInterface.py
|
run
|
crisobg1/armi
| 1
|
python
|
def run(self):
"\n Submit depletion case with external solver to the cluster.\n\n In addition to running the physics kernel, this method calls the waitForJob method\n to wait for it job to finish\n\n comm = MPI.COMM_SELF.Spawn(sys.executable,args=['cpi.py'],maxprocs=5)\n "
return NotImplementedError
|
def run(self):
"\n Submit depletion case with external solver to the cluster.\n\n In addition to running the physics kernel, this method calls the waitForJob method\n to wait for it job to finish\n\n comm = MPI.COMM_SELF.Spawn(sys.executable,args=['cpi.py'],maxprocs=5)\n "
return NotImplementedError<|docstring|>Submit depletion case with external solver to the cluster.
In addition to running the physics kernel, this method calls the waitForJob method
to wait for it job to finish
comm = MPI.COMM_SELF.Spawn(sys.executable,args=['cpi.py'],maxprocs=5)<|endoftext|>
|
73440abdc5dd6bcb626cb357c5889d1636704f8663edba5af8a75c01db469281
|
def read(self):
'\n read a isotopic depletion Output File and applies results to armi objects in the ToDepletion attribute\n '
raise NotImplementedError
|
read a isotopic depletion Output File and applies results to armi objects in the ToDepletion attribute
|
armi/physics/neutronics/isotopicDepletion/isotopicDepletionInterface.py
|
read
|
crisobg1/armi
| 1
|
python
|
def read(self):
'\n \n '
raise NotImplementedError
|
def read(self):
'\n \n '
raise NotImplementedError<|docstring|>read a isotopic depletion Output File and applies results to armi objects in the ToDepletion attribute<|endoftext|>
|
9ea82b5481134de6c45d3fc7449c5d1d45550e8d48a9326b8a2c1ecb092dacde
|
def write(self):
'\n return a list of lines to write for a csrc card\n '
raise NotImplementedError
|
return a list of lines to write for a csrc card
|
armi/physics/neutronics/isotopicDepletion/isotopicDepletionInterface.py
|
write
|
crisobg1/armi
| 1
|
python
|
def write(self):
'\n \n '
raise NotImplementedError
|
def write(self):
'\n \n '
raise NotImplementedError<|docstring|>return a list of lines to write for a csrc card<|endoftext|>
|
699b3bded0188352bdbcbf08f8746e074be855503a080a7cccbe6fcc98f67ebf
|
def difference_delta(expr, n=None, step=1):
'Difference Operator.\n\n Discrete analogous to differential operator.\n\n Examples\n ========\n\n >>> from sympy import difference_delta as dd\n >>> from sympy.abc import n\n >>> dd(n*(n + 1), n)\n 2*n + 2\n >>> dd(n*(n + 1), n, 2)\n 4*n + 6\n\n References\n ==========\n\n .. [1] https://reference.wolfram.com/language/ref/DifferenceDelta.html\n '
expr = sympify(expr)
if (n is None):
f = expr.free_symbols
if (len(f) == 1):
n = f.pop()
elif (len(f) == 0):
return S.Zero
else:
raise ValueError(('Since there is more than one variable in the expression, a variable must be supplied to take the difference of %s' % expr))
step = sympify(step)
if (step.is_number is False):
raise ValueError('Step should be a number.')
elif (step in [S.Infinity, (- S.Infinity)]):
raise ValueError('Step should be bounded.')
if hasattr(expr, '_eval_difference_delta'):
result = expr._eval_difference_delta(n, step)
if result:
return result
return (expr.subs(n, (n + step)) - expr)
|
Difference Operator.
Discrete analogous to differential operator.
Examples
========
>>> from sympy import difference_delta as dd
>>> from sympy.abc import n
>>> dd(n*(n + 1), n)
2*n + 2
>>> dd(n*(n + 1), n, 2)
4*n + 6
References
==========
.. [1] https://reference.wolfram.com/language/ref/DifferenceDelta.html
|
sympy/series/limitseq.py
|
difference_delta
|
hacman/sympy
| 4
|
python
|
def difference_delta(expr, n=None, step=1):
'Difference Operator.\n\n Discrete analogous to differential operator.\n\n Examples\n ========\n\n >>> from sympy import difference_delta as dd\n >>> from sympy.abc import n\n >>> dd(n*(n + 1), n)\n 2*n + 2\n >>> dd(n*(n + 1), n, 2)\n 4*n + 6\n\n References\n ==========\n\n .. [1] https://reference.wolfram.com/language/ref/DifferenceDelta.html\n '
expr = sympify(expr)
if (n is None):
f = expr.free_symbols
if (len(f) == 1):
n = f.pop()
elif (len(f) == 0):
return S.Zero
else:
raise ValueError(('Since there is more than one variable in the expression, a variable must be supplied to take the difference of %s' % expr))
step = sympify(step)
if (step.is_number is False):
raise ValueError('Step should be a number.')
elif (step in [S.Infinity, (- S.Infinity)]):
raise ValueError('Step should be bounded.')
if hasattr(expr, '_eval_difference_delta'):
result = expr._eval_difference_delta(n, step)
if result:
return result
return (expr.subs(n, (n + step)) - expr)
|
def difference_delta(expr, n=None, step=1):
'Difference Operator.\n\n Discrete analogous to differential operator.\n\n Examples\n ========\n\n >>> from sympy import difference_delta as dd\n >>> from sympy.abc import n\n >>> dd(n*(n + 1), n)\n 2*n + 2\n >>> dd(n*(n + 1), n, 2)\n 4*n + 6\n\n References\n ==========\n\n .. [1] https://reference.wolfram.com/language/ref/DifferenceDelta.html\n '
expr = sympify(expr)
if (n is None):
f = expr.free_symbols
if (len(f) == 1):
n = f.pop()
elif (len(f) == 0):
return S.Zero
else:
raise ValueError(('Since there is more than one variable in the expression, a variable must be supplied to take the difference of %s' % expr))
step = sympify(step)
if (step.is_number is False):
raise ValueError('Step should be a number.')
elif (step in [S.Infinity, (- S.Infinity)]):
raise ValueError('Step should be bounded.')
if hasattr(expr, '_eval_difference_delta'):
result = expr._eval_difference_delta(n, step)
if result:
return result
return (expr.subs(n, (n + step)) - expr)<|docstring|>Difference Operator.
Discrete analogous to differential operator.
Examples
========
>>> from sympy import difference_delta as dd
>>> from sympy.abc import n
>>> dd(n*(n + 1), n)
2*n + 2
>>> dd(n*(n + 1), n, 2)
4*n + 6
References
==========
.. [1] https://reference.wolfram.com/language/ref/DifferenceDelta.html<|endoftext|>
|
4c58681a929d061d47d3298d96ae93a9de0d6a4f2218b2ecec4534727a47cf7f
|
def dominant(expr, n):
'Finds the most dominating term in an expression.\n\n if limit(a/b, n, oo) is oo then a dominates b.\n if limit(a/b, n, oo) is 0 then b dominates a.\n else a and b are comparable.\n\n returns the most dominant term.\n If no unique domiant term, then returns ``None``.\n\n Examples\n ========\n\n >>> from sympy import Sum\n >>> from sympy.series.limitseq import dominant\n >>> from sympy.abc import n, k\n >>> dominant(5*n**3 + 4*n**2 + n + 1, n)\n 5*n**3\n >>> dominant(2**n + Sum(k, (k, 0, n)), n)\n 2**n\n\n See Also\n ========\n\n sympy.series.limitseq.dominant\n '
terms = Add.make_args(expr.expand(func=True))
term0 = terms[(- 1)]
comp = [term0]
for t in terms[:(- 1)]:
e = (term0 / t).combsimp()
l = limit_seq(e, n)
if (l is S.Zero):
term0 = t
comp = [term0]
elif (l is None):
return None
elif (l not in [S.Infinity, (- S.Infinity)]):
comp.append(t)
if (len(comp) > 1):
return None
return term0
|
Finds the most dominating term in an expression.
if limit(a/b, n, oo) is oo then a dominates b.
if limit(a/b, n, oo) is 0 then b dominates a.
else a and b are comparable.
returns the most dominant term.
If no unique domiant term, then returns ``None``.
Examples
========
>>> from sympy import Sum
>>> from sympy.series.limitseq import dominant
>>> from sympy.abc import n, k
>>> dominant(5*n**3 + 4*n**2 + n + 1, n)
5*n**3
>>> dominant(2**n + Sum(k, (k, 0, n)), n)
2**n
See Also
========
sympy.series.limitseq.dominant
|
sympy/series/limitseq.py
|
dominant
|
hacman/sympy
| 4
|
python
|
def dominant(expr, n):
'Finds the most dominating term in an expression.\n\n if limit(a/b, n, oo) is oo then a dominates b.\n if limit(a/b, n, oo) is 0 then b dominates a.\n else a and b are comparable.\n\n returns the most dominant term.\n If no unique domiant term, then returns ``None``.\n\n Examples\n ========\n\n >>> from sympy import Sum\n >>> from sympy.series.limitseq import dominant\n >>> from sympy.abc import n, k\n >>> dominant(5*n**3 + 4*n**2 + n + 1, n)\n 5*n**3\n >>> dominant(2**n + Sum(k, (k, 0, n)), n)\n 2**n\n\n See Also\n ========\n\n sympy.series.limitseq.dominant\n '
terms = Add.make_args(expr.expand(func=True))
term0 = terms[(- 1)]
comp = [term0]
for t in terms[:(- 1)]:
e = (term0 / t).combsimp()
l = limit_seq(e, n)
if (l is S.Zero):
term0 = t
comp = [term0]
elif (l is None):
return None
elif (l not in [S.Infinity, (- S.Infinity)]):
comp.append(t)
if (len(comp) > 1):
return None
return term0
|
def dominant(expr, n):
'Finds the most dominating term in an expression.\n\n if limit(a/b, n, oo) is oo then a dominates b.\n if limit(a/b, n, oo) is 0 then b dominates a.\n else a and b are comparable.\n\n returns the most dominant term.\n If no unique domiant term, then returns ``None``.\n\n Examples\n ========\n\n >>> from sympy import Sum\n >>> from sympy.series.limitseq import dominant\n >>> from sympy.abc import n, k\n >>> dominant(5*n**3 + 4*n**2 + n + 1, n)\n 5*n**3\n >>> dominant(2**n + Sum(k, (k, 0, n)), n)\n 2**n\n\n See Also\n ========\n\n sympy.series.limitseq.dominant\n '
terms = Add.make_args(expr.expand(func=True))
term0 = terms[(- 1)]
comp = [term0]
for t in terms[:(- 1)]:
e = (term0 / t).combsimp()
l = limit_seq(e, n)
if (l is S.Zero):
term0 = t
comp = [term0]
elif (l is None):
return None
elif (l not in [S.Infinity, (- S.Infinity)]):
comp.append(t)
if (len(comp) > 1):
return None
return term0<|docstring|>Finds the most dominating term in an expression.
if limit(a/b, n, oo) is oo then a dominates b.
if limit(a/b, n, oo) is 0 then b dominates a.
else a and b are comparable.
returns the most dominant term.
If no unique domiant term, then returns ``None``.
Examples
========
>>> from sympy import Sum
>>> from sympy.series.limitseq import dominant
>>> from sympy.abc import n, k
>>> dominant(5*n**3 + 4*n**2 + n + 1, n)
5*n**3
>>> dominant(2**n + Sum(k, (k, 0, n)), n)
2**n
See Also
========
sympy.series.limitseq.dominant<|endoftext|>
|
d609599d2cba4e76c8c67997f4ea6c0a1154b21663f7c30c2d290156294649a3
|
def limit_seq(expr, n=None, trials=5):
'Finds limits of terms having sequences at infinity.\n\n Parameters\n ==========\n\n expr : Expr\n SymPy expression that is admissible (see section below).\n n : Symbol\n Find the limit wrt to n at infinity.\n trials: int, optional\n The algorithm is highly recursive. ``trials`` is a safeguard from\n infinite recursion incase limit is not easily computed by the\n algorithm. Try increasing ``trials`` if the algorithm returns ``None``.\n\n Admissible Terms\n ================\n\n The terms should be built from rational functions, indefinite sums,\n and indefinite products over an indeterminate n. A term is admissible\n if the scope of all product quantifiers are asymptotically positive.\n Every admissible term is asymptoticically monotonous.\n\n Examples\n ========\n\n >>> from sympy import limit_seq, Sum, binomial\n >>> from sympy.abc import n, k, m\n >>> limit_seq((5*n**3 + 3*n**2 + 4) / (3*n**3 + 4*n - 5), n)\n 5/3\n >>> limit_seq(binomial(2*n, n) / Sum(binomial(2*k, k), (k, 1, n)), n)\n 3/4\n >>> limit_seq(Sum(k**2 * Sum(2**m/m, (m, 1, k)), (k, 1, n)) / (2**n*n), n)\n 4\n\n See Also\n ========\n\n sympy.series.limitseq.dominant\n\n References\n ==========\n\n .. [1] Computing Limits of Sequences - Manuel Kauers\n '
from sympy.concrete.summations import Sum
if (n is None):
free = expr.free_symbols
if (len(free) == 1):
n = free.pop()
elif (not free):
return expr
else:
raise ValueError(('expr %s has more than one variables. Pleasespecify a variable.' % expr))
elif (n not in expr.free_symbols):
return expr
for i in range(trials):
if (not expr.has(Sum)):
result = _limit_inf(expr, n)
if (result is not None):
return result
(num, den) = expr.as_numer_denom()
if ((not den.has(n)) or (not num.has(n))):
result = _limit_inf(expr.doit(), n)
if (result is not None):
return result
return None
(num, den) = (difference_delta(t.expand(), n) for t in [num, den])
expr = (num / den).combsimp()
if (not expr.has(Sum)):
result = _limit_inf(expr, n)
if (result is not None):
return result
(num, den) = expr.as_numer_denom()
num = dominant(num, n)
if (num is None):
return None
den = dominant(den, n)
if (den is None):
return None
expr = (num / den).combsimp()
|
Finds limits of terms having sequences at infinity.
Parameters
==========
expr : Expr
SymPy expression that is admissible (see section below).
n : Symbol
Find the limit wrt to n at infinity.
trials: int, optional
The algorithm is highly recursive. ``trials`` is a safeguard from
infinite recursion incase limit is not easily computed by the
algorithm. Try increasing ``trials`` if the algorithm returns ``None``.
Admissible Terms
================
The terms should be built from rational functions, indefinite sums,
and indefinite products over an indeterminate n. A term is admissible
if the scope of all product quantifiers are asymptotically positive.
Every admissible term is asymptoticically monotonous.
Examples
========
>>> from sympy import limit_seq, Sum, binomial
>>> from sympy.abc import n, k, m
>>> limit_seq((5*n**3 + 3*n**2 + 4) / (3*n**3 + 4*n - 5), n)
5/3
>>> limit_seq(binomial(2*n, n) / Sum(binomial(2*k, k), (k, 1, n)), n)
3/4
>>> limit_seq(Sum(k**2 * Sum(2**m/m, (m, 1, k)), (k, 1, n)) / (2**n*n), n)
4
See Also
========
sympy.series.limitseq.dominant
References
==========
.. [1] Computing Limits of Sequences - Manuel Kauers
|
sympy/series/limitseq.py
|
limit_seq
|
hacman/sympy
| 4
|
python
|
def limit_seq(expr, n=None, trials=5):
'Finds limits of terms having sequences at infinity.\n\n Parameters\n ==========\n\n expr : Expr\n SymPy expression that is admissible (see section below).\n n : Symbol\n Find the limit wrt to n at infinity.\n trials: int, optional\n The algorithm is highly recursive. ``trials`` is a safeguard from\n infinite recursion incase limit is not easily computed by the\n algorithm. Try increasing ``trials`` if the algorithm returns ``None``.\n\n Admissible Terms\n ================\n\n The terms should be built from rational functions, indefinite sums,\n and indefinite products over an indeterminate n. A term is admissible\n if the scope of all product quantifiers are asymptotically positive.\n Every admissible term is asymptoticically monotonous.\n\n Examples\n ========\n\n >>> from sympy import limit_seq, Sum, binomial\n >>> from sympy.abc import n, k, m\n >>> limit_seq((5*n**3 + 3*n**2 + 4) / (3*n**3 + 4*n - 5), n)\n 5/3\n >>> limit_seq(binomial(2*n, n) / Sum(binomial(2*k, k), (k, 1, n)), n)\n 3/4\n >>> limit_seq(Sum(k**2 * Sum(2**m/m, (m, 1, k)), (k, 1, n)) / (2**n*n), n)\n 4\n\n See Also\n ========\n\n sympy.series.limitseq.dominant\n\n References\n ==========\n\n .. [1] Computing Limits of Sequences - Manuel Kauers\n '
from sympy.concrete.summations import Sum
if (n is None):
free = expr.free_symbols
if (len(free) == 1):
n = free.pop()
elif (not free):
return expr
else:
raise ValueError(('expr %s has more than one variables. Pleasespecify a variable.' % expr))
elif (n not in expr.free_symbols):
return expr
for i in range(trials):
if (not expr.has(Sum)):
result = _limit_inf(expr, n)
if (result is not None):
return result
(num, den) = expr.as_numer_denom()
if ((not den.has(n)) or (not num.has(n))):
result = _limit_inf(expr.doit(), n)
if (result is not None):
return result
return None
(num, den) = (difference_delta(t.expand(), n) for t in [num, den])
expr = (num / den).combsimp()
if (not expr.has(Sum)):
result = _limit_inf(expr, n)
if (result is not None):
return result
(num, den) = expr.as_numer_denom()
num = dominant(num, n)
if (num is None):
return None
den = dominant(den, n)
if (den is None):
return None
expr = (num / den).combsimp()
|
def limit_seq(expr, n=None, trials=5):
'Finds limits of terms having sequences at infinity.\n\n Parameters\n ==========\n\n expr : Expr\n SymPy expression that is admissible (see section below).\n n : Symbol\n Find the limit wrt to n at infinity.\n trials: int, optional\n The algorithm is highly recursive. ``trials`` is a safeguard from\n infinite recursion incase limit is not easily computed by the\n algorithm. Try increasing ``trials`` if the algorithm returns ``None``.\n\n Admissible Terms\n ================\n\n The terms should be built from rational functions, indefinite sums,\n and indefinite products over an indeterminate n. A term is admissible\n if the scope of all product quantifiers are asymptotically positive.\n Every admissible term is asymptoticically monotonous.\n\n Examples\n ========\n\n >>> from sympy import limit_seq, Sum, binomial\n >>> from sympy.abc import n, k, m\n >>> limit_seq((5*n**3 + 3*n**2 + 4) / (3*n**3 + 4*n - 5), n)\n 5/3\n >>> limit_seq(binomial(2*n, n) / Sum(binomial(2*k, k), (k, 1, n)), n)\n 3/4\n >>> limit_seq(Sum(k**2 * Sum(2**m/m, (m, 1, k)), (k, 1, n)) / (2**n*n), n)\n 4\n\n See Also\n ========\n\n sympy.series.limitseq.dominant\n\n References\n ==========\n\n .. [1] Computing Limits of Sequences - Manuel Kauers\n '
from sympy.concrete.summations import Sum
if (n is None):
free = expr.free_symbols
if (len(free) == 1):
n = free.pop()
elif (not free):
return expr
else:
raise ValueError(('expr %s has more than one variables. Pleasespecify a variable.' % expr))
elif (n not in expr.free_symbols):
return expr
for i in range(trials):
if (not expr.has(Sum)):
result = _limit_inf(expr, n)
if (result is not None):
return result
(num, den) = expr.as_numer_denom()
if ((not den.has(n)) or (not num.has(n))):
result = _limit_inf(expr.doit(), n)
if (result is not None):
return result
return None
(num, den) = (difference_delta(t.expand(), n) for t in [num, den])
expr = (num / den).combsimp()
if (not expr.has(Sum)):
result = _limit_inf(expr, n)
if (result is not None):
return result
(num, den) = expr.as_numer_denom()
num = dominant(num, n)
if (num is None):
return None
den = dominant(den, n)
if (den is None):
return None
expr = (num / den).combsimp()<|docstring|>Finds limits of terms having sequences at infinity.
Parameters
==========
expr : Expr
SymPy expression that is admissible (see section below).
n : Symbol
Find the limit wrt to n at infinity.
trials: int, optional
The algorithm is highly recursive. ``trials`` is a safeguard from
infinite recursion incase limit is not easily computed by the
algorithm. Try increasing ``trials`` if the algorithm returns ``None``.
Admissible Terms
================
The terms should be built from rational functions, indefinite sums,
and indefinite products over an indeterminate n. A term is admissible
if the scope of all product quantifiers are asymptotically positive.
Every admissible term is asymptoticically monotonous.
Examples
========
>>> from sympy import limit_seq, Sum, binomial
>>> from sympy.abc import n, k, m
>>> limit_seq((5*n**3 + 3*n**2 + 4) / (3*n**3 + 4*n - 5), n)
5/3
>>> limit_seq(binomial(2*n, n) / Sum(binomial(2*k, k), (k, 1, n)), n)
3/4
>>> limit_seq(Sum(k**2 * Sum(2**m/m, (m, 1, k)), (k, 1, n)) / (2**n*n), n)
4
See Also
========
sympy.series.limitseq.dominant
References
==========
.. [1] Computing Limits of Sequences - Manuel Kauers<|endoftext|>
|
5cf9c9c62d2ce08bc32cdf761c21d94985d58b27e9fe3b5e16b761b0d87d8bd1
|
def get_version() -> str:
'_Get version number for the package `{{cookiecutter.__project_name}}`._\n\n Returns:\n str: Version number taken from the installed package version or `version.py`.\n '
from importlib.metadata import PackageNotFoundError, version
__version__: str = 'unknown'
try:
__version__ = version('{{cookiecutter.__project_name}}')
except PackageNotFoundError:
from .version import __version__
finally:
del version, PackageNotFoundError
return __version__
|
_Get version number for the package `{{cookiecutter.__project_name}}`._
Returns:
str: Version number taken from the installed package version or `version.py`.
|
datajoint-workflow/{{cookiecutter.github_repo}}/src/{{cookiecutter.__pkg_import_name}}/__init__.py
|
get_version
|
Yambottle/dj-cookiecutter-1
| 0
|
python
|
def get_version() -> str:
'_Get version number for the package `{{cookiecutter.__project_name}}`._\n\n Returns:\n str: Version number taken from the installed package version or `version.py`.\n '
from importlib.metadata import PackageNotFoundError, version
__version__: str = 'unknown'
try:
__version__ = version('{{cookiecutter.__project_name}}')
except PackageNotFoundError:
from .version import __version__
finally:
del version, PackageNotFoundError
return __version__
|
def get_version() -> str:
'_Get version number for the package `{{cookiecutter.__project_name}}`._\n\n Returns:\n str: Version number taken from the installed package version or `version.py`.\n '
from importlib.metadata import PackageNotFoundError, version
__version__: str = 'unknown'
try:
__version__ = version('{{cookiecutter.__project_name}}')
except PackageNotFoundError:
from .version import __version__
finally:
del version, PackageNotFoundError
return __version__<|docstring|>_Get version number for the package `{{cookiecutter.__project_name}}`._
Returns:
str: Version number taken from the installed package version or `version.py`.<|endoftext|>
|
8b1b217efb7163128d51f49926f6374fc3e00949fc76fba30523cd6b94b18e0a
|
def forward(self, input):
'\n Input: (batch_size, data_length)'
x = self.spectrogram_extractor(input)
x = self.logmel_extractor(x)
x = x.transpose(1, 3)
x = self.bn0(x)
x = x.transpose(1, 3)
x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = torch.mean(x, dim=3)
attn_feats = x.transpose(1, 2)
(x1, _) = torch.max(x, dim=2)
x2 = torch.mean(x, dim=2)
x = (x1 + x2)
x = F.dropout(x, p=0.5, training=self.training)
x = F.relu_(self.fc1(x))
embedding = F.dropout(x, p=0.5, training=self.training)
clipwise_output = torch.sigmoid(self.fc_audioset(x))
output_dict = {'clipwise_output': clipwise_output, 'fc_feat': embedding, 'attn_feat': attn_feats}
return output_dict
|
Input: (batch_size, data_length)
|
data/extract_feature_panns.py
|
forward
|
ze-lin/AudioCaption
| 12
|
python
|
def forward(self, input):
'\n '
x = self.spectrogram_extractor(input)
x = self.logmel_extractor(x)
x = x.transpose(1, 3)
x = self.bn0(x)
x = x.transpose(1, 3)
x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = torch.mean(x, dim=3)
attn_feats = x.transpose(1, 2)
(x1, _) = torch.max(x, dim=2)
x2 = torch.mean(x, dim=2)
x = (x1 + x2)
x = F.dropout(x, p=0.5, training=self.training)
x = F.relu_(self.fc1(x))
embedding = F.dropout(x, p=0.5, training=self.training)
clipwise_output = torch.sigmoid(self.fc_audioset(x))
output_dict = {'clipwise_output': clipwise_output, 'fc_feat': embedding, 'attn_feat': attn_feats}
return output_dict
|
def forward(self, input):
'\n '
x = self.spectrogram_extractor(input)
x = self.logmel_extractor(x)
x = x.transpose(1, 3)
x = self.bn0(x)
x = x.transpose(1, 3)
x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = torch.mean(x, dim=3)
attn_feats = x.transpose(1, 2)
(x1, _) = torch.max(x, dim=2)
x2 = torch.mean(x, dim=2)
x = (x1 + x2)
x = F.dropout(x, p=0.5, training=self.training)
x = F.relu_(self.fc1(x))
embedding = F.dropout(x, p=0.5, training=self.training)
clipwise_output = torch.sigmoid(self.fc_audioset(x))
output_dict = {'clipwise_output': clipwise_output, 'fc_feat': embedding, 'attn_feat': attn_feats}
return output_dict<|docstring|>Input: (batch_size, data_length)<|endoftext|>
|
1fe3d7e5944b623e774ee2f1563a3f5883bd55cf8ef37ccc0d23c33e1ea43178
|
def forward(self, input):
'\n Input: (batch_size, data_length)'
x = self.spectrogram_extractor(input)
x = self.logmel_extractor(x)
x = x.transpose(1, 3)
x = self.bn0(x)
x = x.transpose(1, 3)
x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block5(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block6(x, pool_size=(1, 1), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = torch.mean(x, dim=3)
attn_feats = x.transpose(1, 2)
(x1, _) = torch.max(x, dim=2)
x2 = torch.mean(x, dim=2)
x = (x1 + x2)
x = F.dropout(x, p=0.5, training=self.training)
x = F.relu_(self.fc1(x))
embedding = F.dropout(x, p=0.5, training=self.training)
clipwise_output = torch.sigmoid(self.fc_audioset(x))
output_dict = {'clipwise_output': clipwise_output, 'fc_feat': embedding, 'attn_feat': attn_feats}
return output_dict
|
Input: (batch_size, data_length)
|
data/extract_feature_panns.py
|
forward
|
ze-lin/AudioCaption
| 12
|
python
|
def forward(self, input):
'\n '
x = self.spectrogram_extractor(input)
x = self.logmel_extractor(x)
x = x.transpose(1, 3)
x = self.bn0(x)
x = x.transpose(1, 3)
x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block5(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block6(x, pool_size=(1, 1), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = torch.mean(x, dim=3)
attn_feats = x.transpose(1, 2)
(x1, _) = torch.max(x, dim=2)
x2 = torch.mean(x, dim=2)
x = (x1 + x2)
x = F.dropout(x, p=0.5, training=self.training)
x = F.relu_(self.fc1(x))
embedding = F.dropout(x, p=0.5, training=self.training)
clipwise_output = torch.sigmoid(self.fc_audioset(x))
output_dict = {'clipwise_output': clipwise_output, 'fc_feat': embedding, 'attn_feat': attn_feats}
return output_dict
|
def forward(self, input):
'\n '
x = self.spectrogram_extractor(input)
x = self.logmel_extractor(x)
x = x.transpose(1, 3)
x = self.bn0(x)
x = x.transpose(1, 3)
x = self.conv_block1(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block2(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block3(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block4(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block5(x, pool_size=(2, 2), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = self.conv_block6(x, pool_size=(1, 1), pool_type='avg')
x = F.dropout(x, p=0.2, training=self.training)
x = torch.mean(x, dim=3)
attn_feats = x.transpose(1, 2)
(x1, _) = torch.max(x, dim=2)
x2 = torch.mean(x, dim=2)
x = (x1 + x2)
x = F.dropout(x, p=0.5, training=self.training)
x = F.relu_(self.fc1(x))
embedding = F.dropout(x, p=0.5, training=self.training)
clipwise_output = torch.sigmoid(self.fc_audioset(x))
output_dict = {'clipwise_output': clipwise_output, 'fc_feat': embedding, 'attn_feat': attn_feats}
return output_dict<|docstring|>Input: (batch_size, data_length)<|endoftext|>
|
dcc2cf66b1c9ca0398b21dbe4381da6a8cea99aa214eb409256719138fd6cb80
|
def compare_chord_labels(chord_label_1_path: str, chord_label_2_path: str):
'\n Compare two chord label sequences\n\n :param chord_label_1_path: Path to .lab file of one chord label sequence\n :param chord_label_2_path: Path to .lab file of other chord label sequence\n :return: CSR (overlap percentage between the two chord label sequences)\n '
return evaluator.evaluate(chord_label_1_path, chord_label_2_path)[0]
|
Compare two chord label sequences
:param chord_label_1_path: Path to .lab file of one chord label sequence
:param chord_label_2_path: Path to .lab file of other chord label sequence
:return: CSR (overlap percentage between the two chord label sequences)
|
decibel/evaluator/chord_label_comparator.py
|
compare_chord_labels
|
DaphneO/DECIBEL
| 13
|
python
|
def compare_chord_labels(chord_label_1_path: str, chord_label_2_path: str):
'\n Compare two chord label sequences\n\n :param chord_label_1_path: Path to .lab file of one chord label sequence\n :param chord_label_2_path: Path to .lab file of other chord label sequence\n :return: CSR (overlap percentage between the two chord label sequences)\n '
return evaluator.evaluate(chord_label_1_path, chord_label_2_path)[0]
|
def compare_chord_labels(chord_label_1_path: str, chord_label_2_path: str):
'\n Compare two chord label sequences\n\n :param chord_label_1_path: Path to .lab file of one chord label sequence\n :param chord_label_2_path: Path to .lab file of other chord label sequence\n :return: CSR (overlap percentage between the two chord label sequences)\n '
return evaluator.evaluate(chord_label_1_path, chord_label_2_path)[0]<|docstring|>Compare two chord label sequences
:param chord_label_1_path: Path to .lab file of one chord label sequence
:param chord_label_2_path: Path to .lab file of other chord label sequence
:return: CSR (overlap percentage between the two chord label sequences)<|endoftext|>
|
4e66ef1e656690bf925719e2d65a2013548d9f6d56848c3c786df55dd828feb2
|
def prefix_printer(prefix: Any, whitespace: int=0, stderr: bool=False, click: bool=False, upper: bool=True, frame_left: str='[', frame_right: str=']', prefix_end=':', counter_start: int=(- 1), global_counter: bool=False, text_color: str='', text_style: str='', text_bg_color: str='', prefix_color: str='', prefix_style: str='', prefix_bg_color: str='', format_frames: bool=True, *args, **kwargs) -> Callable[([str], None)]:
'\n Prefix printer is function factory for prefixing text.\n\n Args:\n prefix (Any): The prefix to use.\n whitespace (int, optional): The number of whitespaces to use.\n Defaults to 1.\n stderr (bool, optional):\n If True, the printer will print to sys.stderr instead of sys.stdout\n Defaults to False.\n click (bool, optional): If True, the printer will print to click.echo\n instead of sys.stdout. Defaults to False.\n upper (bool, optional): If True, the prefix will be printed in upper\n frame_left (str, optional): The left frame. Defaults to "[".\n frame_right (str, optional): The right frame. Defaults to "]".\n prefix_end (str, optional): The end of the prefix. Defaults to ":".\n counter_start (int, optional): The counter start value. Defaults to -1.\n global_counter (bool, optional): If True, the counter will be global.\n Defaults to False.\n text_color (str, optional): The text color. Defaults to "".\n text_style (str, optional): The text style. Defaults to "".\n text_bg_color (str, optional): The text background color.\n Defaults to "".\n prefix_color (str, optional): The prefix color. Defaults to "".\n prefix_style (str, optional): The prefix style. Defaults to "".\n prefix_bg_color (str, optional): The prefix background color.\n Defaults to "".\n format_frames (bool, optional): If True, the frames will be formatted.\n Defaults to True.\n format_frames (bool, optional): If True, the frames will be formatted.\n Defaults to True.\n\n Raises:\n _exceptions.PropertyError: Raised both stderr and click are True.\n\n Returns:\n Callable[[str], None]:\n A function that prints text prefixed with the prefix.\n '
local_count: Counter = Counter(n=(- 1))
if ((counter_start > (- 1)) and (not global_counter)):
local_count['n'] = counter_start
count = local_count
elif ((counter_start == (- 1)) and global_counter):
global_count['n'] = global_count['l']
count = global_count
elif ((counter_start > (- 1)) and global_counter):
global_count['n'] = global_count['l'] = counter_start
count = global_count
def prefixed_printer(text: str='', prefix: str=prefix, *args, **kwargs) -> None:
'\n Print text prefixed with the prefix.\n\n Args:\n text (str, optional): The text to print. Defaults to "".\n prefix (str, optional): The prefix to use. Defaults to prefix.\n\n Raises:\n _exceptions.PropertyError: Raised both stderr and click are True.\n '
text_fmt_start = f''
text_fmt_end = f''
prefix_fmt_start = f''
prefix_fmt_end = f''
if (text_color != ''):
text_fmt_start += f'{fg(text_color)}'
text_fmt_end += f"{fg('reset')}"
if (text_style != ''):
text_fmt_start += f'{font(text_style)}'
text_fmt_end += f"{font('reset')}"
if (text_bg_color != ''):
text_fmt_start += f'{bg(text_bg_color)}'
text_fmt_end += f"{bg('reset')}"
if (prefix_color != ''):
prefix_fmt_start += f'{fg(prefix_color)}'
prefix_fmt_end += f"{fg('reset')}"
if (prefix_style != ''):
prefix_fmt_start += f'{font(prefix_style)}'
prefix_fmt_end += f"{font('reset')}"
if (prefix_bg_color != ''):
prefix_fmt_start += f'{bg(prefix_bg_color)}'
prefix_fmt_end += f"{bg('reset')}"
if (upper and isinstance(prefix, str)):
prefix = prefix.upper()
if (not format_frames):
prefix = f'{prefix_fmt_start}{prefix}{prefix_fmt_end}'
if ((counter_start > (- 1)) and (not global_counter)):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
elif ((counter_start > (- 1)) and global_counter):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
global_count['l'] += 1
elif ((counter_start == (- 1)) and global_counter):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
else:
prefix = f'{frame_left}{prefix}{frame_right}'
if format_frames:
prefix = f'{prefix_fmt_start}{prefix}{prefix_fmt_end}'
if (stderr and click):
raise _exceptions.PropertyError('stderr and click cannot be True at the same time')
elif stderr:
print_func: ModuleType = err_print
elif click:
print_func: ModuleType = echo
else:
print_func: Callable[([str], None)] = print
if ('\n' in text):
lines = text.split('\n')
first_line_len = len(lines[0])
lines[0] = f"{prefix}{prefix_end} {(' ' * whitespace)}{text_fmt_start}{lines[0]}{text_fmt_end}"
indent_len = (((len(lines[0]) - first_line_len) - len(text_fmt_start)) - len(text_fmt_end))
print_func(lines[0], *args, **kwargs)
[print_func(((' ' * indent_len) + f'{text_fmt_start}{line}{text_fmt_end}')) for line in lines[1:]]
elif (not text):
print_func(f'{prefix}', *args, **kwargs)
else:
print_func(f"{prefix}{prefix_end} {(' ' * whitespace)}{text_fmt_start}{text}{text_fmt_end}", *args, **kwargs)
return prefixed_printer
|
Prefix printer is function factory for prefixing text.
Args:
prefix (Any): The prefix to use.
whitespace (int, optional): The number of whitespaces to use.
Defaults to 1.
stderr (bool, optional):
If True, the printer will print to sys.stderr instead of sys.stdout
Defaults to False.
click (bool, optional): If True, the printer will print to click.echo
instead of sys.stdout. Defaults to False.
upper (bool, optional): If True, the prefix will be printed in upper
frame_left (str, optional): The left frame. Defaults to "[".
frame_right (str, optional): The right frame. Defaults to "]".
prefix_end (str, optional): The end of the prefix. Defaults to ":".
counter_start (int, optional): The counter start value. Defaults to -1.
global_counter (bool, optional): If True, the counter will be global.
Defaults to False.
text_color (str, optional): The text color. Defaults to "".
text_style (str, optional): The text style. Defaults to "".
text_bg_color (str, optional): The text background color.
Defaults to "".
prefix_color (str, optional): The prefix color. Defaults to "".
prefix_style (str, optional): The prefix style. Defaults to "".
prefix_bg_color (str, optional): The prefix background color.
Defaults to "".
format_frames (bool, optional): If True, the frames will be formatted.
Defaults to True.
format_frames (bool, optional): If True, the frames will be formatted.
Defaults to True.
Raises:
_exceptions.PropertyError: Raised both stderr and click are True.
Returns:
Callable[[str], None]:
A function that prints text prefixed with the prefix.
|
confprint/prefix_printer.py
|
prefix_printer
|
lewiuberg/confprint
| 1
|
python
|
def prefix_printer(prefix: Any, whitespace: int=0, stderr: bool=False, click: bool=False, upper: bool=True, frame_left: str='[', frame_right: str=']', prefix_end=':', counter_start: int=(- 1), global_counter: bool=False, text_color: str=, text_style: str=, text_bg_color: str=, prefix_color: str=, prefix_style: str=, prefix_bg_color: str=, format_frames: bool=True, *args, **kwargs) -> Callable[([str], None)]:
'\n Prefix printer is function factory for prefixing text.\n\n Args:\n prefix (Any): The prefix to use.\n whitespace (int, optional): The number of whitespaces to use.\n Defaults to 1.\n stderr (bool, optional):\n If True, the printer will print to sys.stderr instead of sys.stdout\n Defaults to False.\n click (bool, optional): If True, the printer will print to click.echo\n instead of sys.stdout. Defaults to False.\n upper (bool, optional): If True, the prefix will be printed in upper\n frame_left (str, optional): The left frame. Defaults to "[".\n frame_right (str, optional): The right frame. Defaults to "]".\n prefix_end (str, optional): The end of the prefix. Defaults to ":".\n counter_start (int, optional): The counter start value. Defaults to -1.\n global_counter (bool, optional): If True, the counter will be global.\n Defaults to False.\n text_color (str, optional): The text color. Defaults to .\n text_style (str, optional): The text style. Defaults to .\n text_bg_color (str, optional): The text background color.\n Defaults to .\n prefix_color (str, optional): The prefix color. Defaults to .\n prefix_style (str, optional): The prefix style. Defaults to .\n prefix_bg_color (str, optional): The prefix background color.\n Defaults to .\n format_frames (bool, optional): If True, the frames will be formatted.\n Defaults to True.\n format_frames (bool, optional): If True, the frames will be formatted.\n Defaults to True.\n\n Raises:\n _exceptions.PropertyError: Raised both stderr and click are True.\n\n Returns:\n Callable[[str], None]:\n A function that prints text prefixed with the prefix.\n '
local_count: Counter = Counter(n=(- 1))
if ((counter_start > (- 1)) and (not global_counter)):
local_count['n'] = counter_start
count = local_count
elif ((counter_start == (- 1)) and global_counter):
global_count['n'] = global_count['l']
count = global_count
elif ((counter_start > (- 1)) and global_counter):
global_count['n'] = global_count['l'] = counter_start
count = global_count
def prefixed_printer(text: str=, prefix: str=prefix, *args, **kwargs) -> None:
'\n Print text prefixed with the prefix.\n\n Args:\n text (str, optional): The text to print. Defaults to .\n prefix (str, optional): The prefix to use. Defaults to prefix.\n\n Raises:\n _exceptions.PropertyError: Raised both stderr and click are True.\n '
text_fmt_start = f
text_fmt_end = f
prefix_fmt_start = f
prefix_fmt_end = f
if (text_color != ):
text_fmt_start += f'{fg(text_color)}'
text_fmt_end += f"{fg('reset')}"
if (text_style != ):
text_fmt_start += f'{font(text_style)}'
text_fmt_end += f"{font('reset')}"
if (text_bg_color != ):
text_fmt_start += f'{bg(text_bg_color)}'
text_fmt_end += f"{bg('reset')}"
if (prefix_color != ):
prefix_fmt_start += f'{fg(prefix_color)}'
prefix_fmt_end += f"{fg('reset')}"
if (prefix_style != ):
prefix_fmt_start += f'{font(prefix_style)}'
prefix_fmt_end += f"{font('reset')}"
if (prefix_bg_color != ):
prefix_fmt_start += f'{bg(prefix_bg_color)}'
prefix_fmt_end += f"{bg('reset')}"
if (upper and isinstance(prefix, str)):
prefix = prefix.upper()
if (not format_frames):
prefix = f'{prefix_fmt_start}{prefix}{prefix_fmt_end}'
if ((counter_start > (- 1)) and (not global_counter)):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
elif ((counter_start > (- 1)) and global_counter):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
global_count['l'] += 1
elif ((counter_start == (- 1)) and global_counter):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
else:
prefix = f'{frame_left}{prefix}{frame_right}'
if format_frames:
prefix = f'{prefix_fmt_start}{prefix}{prefix_fmt_end}'
if (stderr and click):
raise _exceptions.PropertyError('stderr and click cannot be True at the same time')
elif stderr:
print_func: ModuleType = err_print
elif click:
print_func: ModuleType = echo
else:
print_func: Callable[([str], None)] = print
if ('\n' in text):
lines = text.split('\n')
first_line_len = len(lines[0])
lines[0] = f"{prefix}{prefix_end} {(' ' * whitespace)}{text_fmt_start}{lines[0]}{text_fmt_end}"
indent_len = (((len(lines[0]) - first_line_len) - len(text_fmt_start)) - len(text_fmt_end))
print_func(lines[0], *args, **kwargs)
[print_func(((' ' * indent_len) + f'{text_fmt_start}{line}{text_fmt_end}')) for line in lines[1:]]
elif (not text):
print_func(f'{prefix}', *args, **kwargs)
else:
print_func(f"{prefix}{prefix_end} {(' ' * whitespace)}{text_fmt_start}{text}{text_fmt_end}", *args, **kwargs)
return prefixed_printer
|
def prefix_printer(prefix: Any, whitespace: int=0, stderr: bool=False, click: bool=False, upper: bool=True, frame_left: str='[', frame_right: str=']', prefix_end=':', counter_start: int=(- 1), global_counter: bool=False, text_color: str=, text_style: str=, text_bg_color: str=, prefix_color: str=, prefix_style: str=, prefix_bg_color: str=, format_frames: bool=True, *args, **kwargs) -> Callable[([str], None)]:
'\n Prefix printer is function factory for prefixing text.\n\n Args:\n prefix (Any): The prefix to use.\n whitespace (int, optional): The number of whitespaces to use.\n Defaults to 1.\n stderr (bool, optional):\n If True, the printer will print to sys.stderr instead of sys.stdout\n Defaults to False.\n click (bool, optional): If True, the printer will print to click.echo\n instead of sys.stdout. Defaults to False.\n upper (bool, optional): If True, the prefix will be printed in upper\n frame_left (str, optional): The left frame. Defaults to "[".\n frame_right (str, optional): The right frame. Defaults to "]".\n prefix_end (str, optional): The end of the prefix. Defaults to ":".\n counter_start (int, optional): The counter start value. Defaults to -1.\n global_counter (bool, optional): If True, the counter will be global.\n Defaults to False.\n text_color (str, optional): The text color. Defaults to .\n text_style (str, optional): The text style. Defaults to .\n text_bg_color (str, optional): The text background color.\n Defaults to .\n prefix_color (str, optional): The prefix color. Defaults to .\n prefix_style (str, optional): The prefix style. Defaults to .\n prefix_bg_color (str, optional): The prefix background color.\n Defaults to .\n format_frames (bool, optional): If True, the frames will be formatted.\n Defaults to True.\n format_frames (bool, optional): If True, the frames will be formatted.\n Defaults to True.\n\n Raises:\n _exceptions.PropertyError: Raised both stderr and click are True.\n\n Returns:\n Callable[[str], None]:\n A function that prints text prefixed with the prefix.\n '
local_count: Counter = Counter(n=(- 1))
if ((counter_start > (- 1)) and (not global_counter)):
local_count['n'] = counter_start
count = local_count
elif ((counter_start == (- 1)) and global_counter):
global_count['n'] = global_count['l']
count = global_count
elif ((counter_start > (- 1)) and global_counter):
global_count['n'] = global_count['l'] = counter_start
count = global_count
def prefixed_printer(text: str=, prefix: str=prefix, *args, **kwargs) -> None:
'\n Print text prefixed with the prefix.\n\n Args:\n text (str, optional): The text to print. Defaults to .\n prefix (str, optional): The prefix to use. Defaults to prefix.\n\n Raises:\n _exceptions.PropertyError: Raised both stderr and click are True.\n '
text_fmt_start = f
text_fmt_end = f
prefix_fmt_start = f
prefix_fmt_end = f
if (text_color != ):
text_fmt_start += f'{fg(text_color)}'
text_fmt_end += f"{fg('reset')}"
if (text_style != ):
text_fmt_start += f'{font(text_style)}'
text_fmt_end += f"{font('reset')}"
if (text_bg_color != ):
text_fmt_start += f'{bg(text_bg_color)}'
text_fmt_end += f"{bg('reset')}"
if (prefix_color != ):
prefix_fmt_start += f'{fg(prefix_color)}'
prefix_fmt_end += f"{fg('reset')}"
if (prefix_style != ):
prefix_fmt_start += f'{font(prefix_style)}'
prefix_fmt_end += f"{font('reset')}"
if (prefix_bg_color != ):
prefix_fmt_start += f'{bg(prefix_bg_color)}'
prefix_fmt_end += f"{bg('reset')}"
if (upper and isinstance(prefix, str)):
prefix = prefix.upper()
if (not format_frames):
prefix = f'{prefix_fmt_start}{prefix}{prefix_fmt_end}'
if ((counter_start > (- 1)) and (not global_counter)):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
elif ((counter_start > (- 1)) and global_counter):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
global_count['l'] += 1
elif ((counter_start == (- 1)) and global_counter):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
else:
prefix = f'{frame_left}{prefix}{frame_right}'
if format_frames:
prefix = f'{prefix_fmt_start}{prefix}{prefix_fmt_end}'
if (stderr and click):
raise _exceptions.PropertyError('stderr and click cannot be True at the same time')
elif stderr:
print_func: ModuleType = err_print
elif click:
print_func: ModuleType = echo
else:
print_func: Callable[([str], None)] = print
if ('\n' in text):
lines = text.split('\n')
first_line_len = len(lines[0])
lines[0] = f"{prefix}{prefix_end} {(' ' * whitespace)}{text_fmt_start}{lines[0]}{text_fmt_end}"
indent_len = (((len(lines[0]) - first_line_len) - len(text_fmt_start)) - len(text_fmt_end))
print_func(lines[0], *args, **kwargs)
[print_func(((' ' * indent_len) + f'{text_fmt_start}{line}{text_fmt_end}')) for line in lines[1:]]
elif (not text):
print_func(f'{prefix}', *args, **kwargs)
else:
print_func(f"{prefix}{prefix_end} {(' ' * whitespace)}{text_fmt_start}{text}{text_fmt_end}", *args, **kwargs)
return prefixed_printer<|docstring|>Prefix printer is function factory for prefixing text.
Args:
prefix (Any): The prefix to use.
whitespace (int, optional): The number of whitespaces to use.
Defaults to 1.
stderr (bool, optional):
If True, the printer will print to sys.stderr instead of sys.stdout
Defaults to False.
click (bool, optional): If True, the printer will print to click.echo
instead of sys.stdout. Defaults to False.
upper (bool, optional): If True, the prefix will be printed in upper
frame_left (str, optional): The left frame. Defaults to "[".
frame_right (str, optional): The right frame. Defaults to "]".
prefix_end (str, optional): The end of the prefix. Defaults to ":".
counter_start (int, optional): The counter start value. Defaults to -1.
global_counter (bool, optional): If True, the counter will be global.
Defaults to False.
text_color (str, optional): The text color. Defaults to "".
text_style (str, optional): The text style. Defaults to "".
text_bg_color (str, optional): The text background color.
Defaults to "".
prefix_color (str, optional): The prefix color. Defaults to "".
prefix_style (str, optional): The prefix style. Defaults to "".
prefix_bg_color (str, optional): The prefix background color.
Defaults to "".
format_frames (bool, optional): If True, the frames will be formatted.
Defaults to True.
format_frames (bool, optional): If True, the frames will be formatted.
Defaults to True.
Raises:
_exceptions.PropertyError: Raised both stderr and click are True.
Returns:
Callable[[str], None]:
A function that prints text prefixed with the prefix.<|endoftext|>
|
d4e67864e666fa979f40a5a961d3f4131379191f6835d6d5f64b20199962e521
|
def prefixed_printer(text: str='', prefix: str=prefix, *args, **kwargs) -> None:
'\n Print text prefixed with the prefix.\n\n Args:\n text (str, optional): The text to print. Defaults to "".\n prefix (str, optional): The prefix to use. Defaults to prefix.\n\n Raises:\n _exceptions.PropertyError: Raised both stderr and click are True.\n '
text_fmt_start = f''
text_fmt_end = f''
prefix_fmt_start = f''
prefix_fmt_end = f''
if (text_color != ''):
text_fmt_start += f'{fg(text_color)}'
text_fmt_end += f"{fg('reset')}"
if (text_style != ''):
text_fmt_start += f'{font(text_style)}'
text_fmt_end += f"{font('reset')}"
if (text_bg_color != ''):
text_fmt_start += f'{bg(text_bg_color)}'
text_fmt_end += f"{bg('reset')}"
if (prefix_color != ''):
prefix_fmt_start += f'{fg(prefix_color)}'
prefix_fmt_end += f"{fg('reset')}"
if (prefix_style != ''):
prefix_fmt_start += f'{font(prefix_style)}'
prefix_fmt_end += f"{font('reset')}"
if (prefix_bg_color != ''):
prefix_fmt_start += f'{bg(prefix_bg_color)}'
prefix_fmt_end += f"{bg('reset')}"
if (upper and isinstance(prefix, str)):
prefix = prefix.upper()
if (not format_frames):
prefix = f'{prefix_fmt_start}{prefix}{prefix_fmt_end}'
if ((counter_start > (- 1)) and (not global_counter)):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
elif ((counter_start > (- 1)) and global_counter):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
global_count['l'] += 1
elif ((counter_start == (- 1)) and global_counter):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
else:
prefix = f'{frame_left}{prefix}{frame_right}'
if format_frames:
prefix = f'{prefix_fmt_start}{prefix}{prefix_fmt_end}'
if (stderr and click):
raise _exceptions.PropertyError('stderr and click cannot be True at the same time')
elif stderr:
print_func: ModuleType = err_print
elif click:
print_func: ModuleType = echo
else:
print_func: Callable[([str], None)] = print
if ('\n' in text):
lines = text.split('\n')
first_line_len = len(lines[0])
lines[0] = f"{prefix}{prefix_end} {(' ' * whitespace)}{text_fmt_start}{lines[0]}{text_fmt_end}"
indent_len = (((len(lines[0]) - first_line_len) - len(text_fmt_start)) - len(text_fmt_end))
print_func(lines[0], *args, **kwargs)
[print_func(((' ' * indent_len) + f'{text_fmt_start}{line}{text_fmt_end}')) for line in lines[1:]]
elif (not text):
print_func(f'{prefix}', *args, **kwargs)
else:
print_func(f"{prefix}{prefix_end} {(' ' * whitespace)}{text_fmt_start}{text}{text_fmt_end}", *args, **kwargs)
|
Print text prefixed with the prefix.
Args:
text (str, optional): The text to print. Defaults to "".
prefix (str, optional): The prefix to use. Defaults to prefix.
Raises:
_exceptions.PropertyError: Raised both stderr and click are True.
|
confprint/prefix_printer.py
|
prefixed_printer
|
lewiuberg/confprint
| 1
|
python
|
def prefixed_printer(text: str=, prefix: str=prefix, *args, **kwargs) -> None:
'\n Print text prefixed with the prefix.\n\n Args:\n text (str, optional): The text to print. Defaults to .\n prefix (str, optional): The prefix to use. Defaults to prefix.\n\n Raises:\n _exceptions.PropertyError: Raised both stderr and click are True.\n '
text_fmt_start = f
text_fmt_end = f
prefix_fmt_start = f
prefix_fmt_end = f
if (text_color != ):
text_fmt_start += f'{fg(text_color)}'
text_fmt_end += f"{fg('reset')}"
if (text_style != ):
text_fmt_start += f'{font(text_style)}'
text_fmt_end += f"{font('reset')}"
if (text_bg_color != ):
text_fmt_start += f'{bg(text_bg_color)}'
text_fmt_end += f"{bg('reset')}"
if (prefix_color != ):
prefix_fmt_start += f'{fg(prefix_color)}'
prefix_fmt_end += f"{fg('reset')}"
if (prefix_style != ):
prefix_fmt_start += f'{font(prefix_style)}'
prefix_fmt_end += f"{font('reset')}"
if (prefix_bg_color != ):
prefix_fmt_start += f'{bg(prefix_bg_color)}'
prefix_fmt_end += f"{bg('reset')}"
if (upper and isinstance(prefix, str)):
prefix = prefix.upper()
if (not format_frames):
prefix = f'{prefix_fmt_start}{prefix}{prefix_fmt_end}'
if ((counter_start > (- 1)) and (not global_counter)):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
elif ((counter_start > (- 1)) and global_counter):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
global_count['l'] += 1
elif ((counter_start == (- 1)) and global_counter):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
else:
prefix = f'{frame_left}{prefix}{frame_right}'
if format_frames:
prefix = f'{prefix_fmt_start}{prefix}{prefix_fmt_end}'
if (stderr and click):
raise _exceptions.PropertyError('stderr and click cannot be True at the same time')
elif stderr:
print_func: ModuleType = err_print
elif click:
print_func: ModuleType = echo
else:
print_func: Callable[([str], None)] = print
if ('\n' in text):
lines = text.split('\n')
first_line_len = len(lines[0])
lines[0] = f"{prefix}{prefix_end} {(' ' * whitespace)}{text_fmt_start}{lines[0]}{text_fmt_end}"
indent_len = (((len(lines[0]) - first_line_len) - len(text_fmt_start)) - len(text_fmt_end))
print_func(lines[0], *args, **kwargs)
[print_func(((' ' * indent_len) + f'{text_fmt_start}{line}{text_fmt_end}')) for line in lines[1:]]
elif (not text):
print_func(f'{prefix}', *args, **kwargs)
else:
print_func(f"{prefix}{prefix_end} {(' ' * whitespace)}{text_fmt_start}{text}{text_fmt_end}", *args, **kwargs)
|
def prefixed_printer(text: str=, prefix: str=prefix, *args, **kwargs) -> None:
'\n Print text prefixed with the prefix.\n\n Args:\n text (str, optional): The text to print. Defaults to .\n prefix (str, optional): The prefix to use. Defaults to prefix.\n\n Raises:\n _exceptions.PropertyError: Raised both stderr and click are True.\n '
text_fmt_start = f
text_fmt_end = f
prefix_fmt_start = f
prefix_fmt_end = f
if (text_color != ):
text_fmt_start += f'{fg(text_color)}'
text_fmt_end += f"{fg('reset')}"
if (text_style != ):
text_fmt_start += f'{font(text_style)}'
text_fmt_end += f"{font('reset')}"
if (text_bg_color != ):
text_fmt_start += f'{bg(text_bg_color)}'
text_fmt_end += f"{bg('reset')}"
if (prefix_color != ):
prefix_fmt_start += f'{fg(prefix_color)}'
prefix_fmt_end += f"{fg('reset')}"
if (prefix_style != ):
prefix_fmt_start += f'{font(prefix_style)}'
prefix_fmt_end += f"{font('reset')}"
if (prefix_bg_color != ):
prefix_fmt_start += f'{bg(prefix_bg_color)}'
prefix_fmt_end += f"{bg('reset')}"
if (upper and isinstance(prefix, str)):
prefix = prefix.upper()
if (not format_frames):
prefix = f'{prefix_fmt_start}{prefix}{prefix_fmt_end}'
if ((counter_start > (- 1)) and (not global_counter)):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
elif ((counter_start > (- 1)) and global_counter):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
global_count['l'] += 1
elif ((counter_start == (- 1)) and global_counter):
prefix = f"{frame_left}{prefix}{prefix_end}{count['n']}{frame_right}"
count['n'] += 1
else:
prefix = f'{frame_left}{prefix}{frame_right}'
if format_frames:
prefix = f'{prefix_fmt_start}{prefix}{prefix_fmt_end}'
if (stderr and click):
raise _exceptions.PropertyError('stderr and click cannot be True at the same time')
elif stderr:
print_func: ModuleType = err_print
elif click:
print_func: ModuleType = echo
else:
print_func: Callable[([str], None)] = print
if ('\n' in text):
lines = text.split('\n')
first_line_len = len(lines[0])
lines[0] = f"{prefix}{prefix_end} {(' ' * whitespace)}{text_fmt_start}{lines[0]}{text_fmt_end}"
indent_len = (((len(lines[0]) - first_line_len) - len(text_fmt_start)) - len(text_fmt_end))
print_func(lines[0], *args, **kwargs)
[print_func(((' ' * indent_len) + f'{text_fmt_start}{line}{text_fmt_end}')) for line in lines[1:]]
elif (not text):
print_func(f'{prefix}', *args, **kwargs)
else:
print_func(f"{prefix}{prefix_end} {(' ' * whitespace)}{text_fmt_start}{text}{text_fmt_end}", *args, **kwargs)<|docstring|>Print text prefixed with the prefix.
Args:
text (str, optional): The text to print. Defaults to "".
prefix (str, optional): The prefix to use. Defaults to prefix.
Raises:
_exceptions.PropertyError: Raised both stderr and click are True.<|endoftext|>
|
540917996be078dad211e840736d8be6c0c09e9ea0362e9024afd1168a7e81d6
|
def list_syntaxes():
'Return a list of all loaded syntax definitions.\n\n Each item is a :class:`namedtuple` with the following properties:\n\n path\n The resource path to the syntax definition file.\n\n name\n The display name of the syntax definition.\n\n scope\n The top-level scope of the syntax.\n\n hidden\n Whether the syntax will appear in the syntax menus and the command palette.\n '
syntax_definition_paths = [path for path in ResourcePath.glob_resources('') if (path.suffix in SYNTAX_TYPES)]
return [get_syntax_metadata(path) for path in syntax_definition_paths if (not ((path.suffix in {'.tmLanguage', '.hidden-tmLanguage'}) and (path.with_suffix('.sublime-syntax') in syntax_definition_paths)))]
|
Return a list of all loaded syntax definitions.
Each item is a :class:`namedtuple` with the following properties:
path
The resource path to the syntax definition file.
name
The display name of the syntax definition.
scope
The top-level scope of the syntax.
hidden
Whether the syntax will appear in the syntax menus and the command palette.
|
Backup/20190721144404/sublime_lib/st3/sublime_lib/syntax.py
|
list_syntaxes
|
altundasbatu/SublimeTextSettings
| 0
|
python
|
def list_syntaxes():
'Return a list of all loaded syntax definitions.\n\n Each item is a :class:`namedtuple` with the following properties:\n\n path\n The resource path to the syntax definition file.\n\n name\n The display name of the syntax definition.\n\n scope\n The top-level scope of the syntax.\n\n hidden\n Whether the syntax will appear in the syntax menus and the command palette.\n '
syntax_definition_paths = [path for path in ResourcePath.glob_resources() if (path.suffix in SYNTAX_TYPES)]
return [get_syntax_metadata(path) for path in syntax_definition_paths if (not ((path.suffix in {'.tmLanguage', '.hidden-tmLanguage'}) and (path.with_suffix('.sublime-syntax') in syntax_definition_paths)))]
|
def list_syntaxes():
'Return a list of all loaded syntax definitions.\n\n Each item is a :class:`namedtuple` with the following properties:\n\n path\n The resource path to the syntax definition file.\n\n name\n The display name of the syntax definition.\n\n scope\n The top-level scope of the syntax.\n\n hidden\n Whether the syntax will appear in the syntax menus and the command palette.\n '
syntax_definition_paths = [path for path in ResourcePath.glob_resources() if (path.suffix in SYNTAX_TYPES)]
return [get_syntax_metadata(path) for path in syntax_definition_paths if (not ((path.suffix in {'.tmLanguage', '.hidden-tmLanguage'}) and (path.with_suffix('.sublime-syntax') in syntax_definition_paths)))]<|docstring|>Return a list of all loaded syntax definitions.
Each item is a :class:`namedtuple` with the following properties:
path
The resource path to the syntax definition file.
name
The display name of the syntax definition.
scope
The top-level scope of the syntax.
hidden
Whether the syntax will appear in the syntax menus and the command palette.<|endoftext|>
|
e7d230fef523e2e7c948cea4caad8f68def9117a44e7c01b3f94a8e6c13a64e8
|
def get_syntax_for_scope(scope):
'Returns the last syntax in load order that matches `scope`.'
return next((syntax.path for syntax in reversed(list_syntaxes()) if (syntax.scope == scope)), None)
|
Returns the last syntax in load order that matches `scope`.
|
Backup/20190721144404/sublime_lib/st3/sublime_lib/syntax.py
|
get_syntax_for_scope
|
altundasbatu/SublimeTextSettings
| 0
|
python
|
def get_syntax_for_scope(scope):
return next((syntax.path for syntax in reversed(list_syntaxes()) if (syntax.scope == scope)), None)
|
def get_syntax_for_scope(scope):
return next((syntax.path for syntax in reversed(list_syntaxes()) if (syntax.scope == scope)), None)<|docstring|>Returns the last syntax in load order that matches `scope`.<|endoftext|>
|
4eb235e3e6a96ace21a019e5941402e89bfa988c1574c1a363c3ef32f889c8e5
|
def SetConfigOptions():
'Set location of configuration flags.\n\n All GRR tools must use the same configuration files so they could all work\n together. This needs to happen even before the configuration subsystem is\n loaded so it must be bootstrapped by this code (all other options are\n tweakable via the configuration system).\n\n There are two main parts for the config system:\n\n 1) The main config file is shipped with the package and controls general\n parameters. Note that this file is highly dependent on the exact version of\n the grr package which is using it because it might have options which are\n not understood by another version. We typically always use the config file\n from package resources because in most cases this is the right thing to do\n as this file matches exactly the running version. If you really have a good\n reason you can override with the --config flag.\n\n 2) The writeback location. If any GRR component updates the configuration,\n changes will be written back to a different locally modified config\n file. This file specifies overrides of the main configuration file. The\n main reason is that typically the same locally written config file may be\n used with multiple versions of the GRR server because it specifies a very\n small and rarely changing set of options.\n\n '
config_opts = {}
flag_defaults = {}
if os.environ.get('GRR_CONFIG_FILE'):
flag_defaults['config'] = os.environ.get('GRR_CONFIG_FILE')
elif defaults.CONFIG_FILE:
flag_defaults['config'] = defaults.CONFIG_FILE
else:
flag_defaults['config'] = config_lib.Resource().Filter('install_data/etc/grr-server.yaml')
for (option, value) in config_opts.items():
config_lib.CONFIG.Set(option, value)
flags.PARSER.set_defaults(**flag_defaults)
|
Set location of configuration flags.
All GRR tools must use the same configuration files so they could all work
together. This needs to happen even before the configuration subsystem is
loaded so it must be bootstrapped by this code (all other options are
tweakable via the configuration system).
There are two main parts for the config system:
1) The main config file is shipped with the package and controls general
parameters. Note that this file is highly dependent on the exact version of
the grr package which is using it because it might have options which are
not understood by another version. We typically always use the config file
from package resources because in most cases this is the right thing to do
as this file matches exactly the running version. If you really have a good
reason you can override with the --config flag.
2) The writeback location. If any GRR component updates the configuration,
changes will be written back to a different locally modified config
file. This file specifies overrides of the main configuration file. The
main reason is that typically the same locally written config file may be
used with multiple versions of the GRR server because it specifies a very
small and rarely changing set of options.
|
grr/lib/distro_entry.py
|
SetConfigOptions
|
mikecb/grr
| 5
|
python
|
def SetConfigOptions():
'Set location of configuration flags.\n\n All GRR tools must use the same configuration files so they could all work\n together. This needs to happen even before the configuration subsystem is\n loaded so it must be bootstrapped by this code (all other options are\n tweakable via the configuration system).\n\n There are two main parts for the config system:\n\n 1) The main config file is shipped with the package and controls general\n parameters. Note that this file is highly dependent on the exact version of\n the grr package which is using it because it might have options which are\n not understood by another version. We typically always use the config file\n from package resources because in most cases this is the right thing to do\n as this file matches exactly the running version. If you really have a good\n reason you can override with the --config flag.\n\n 2) The writeback location. If any GRR component updates the configuration,\n changes will be written back to a different locally modified config\n file. This file specifies overrides of the main configuration file. The\n main reason is that typically the same locally written config file may be\n used with multiple versions of the GRR server because it specifies a very\n small and rarely changing set of options.\n\n '
config_opts = {}
flag_defaults = {}
if os.environ.get('GRR_CONFIG_FILE'):
flag_defaults['config'] = os.environ.get('GRR_CONFIG_FILE')
elif defaults.CONFIG_FILE:
flag_defaults['config'] = defaults.CONFIG_FILE
else:
flag_defaults['config'] = config_lib.Resource().Filter('install_data/etc/grr-server.yaml')
for (option, value) in config_opts.items():
config_lib.CONFIG.Set(option, value)
flags.PARSER.set_defaults(**flag_defaults)
|
def SetConfigOptions():
'Set location of configuration flags.\n\n All GRR tools must use the same configuration files so they could all work\n together. This needs to happen even before the configuration subsystem is\n loaded so it must be bootstrapped by this code (all other options are\n tweakable via the configuration system).\n\n There are two main parts for the config system:\n\n 1) The main config file is shipped with the package and controls general\n parameters. Note that this file is highly dependent on the exact version of\n the grr package which is using it because it might have options which are\n not understood by another version. We typically always use the config file\n from package resources because in most cases this is the right thing to do\n as this file matches exactly the running version. If you really have a good\n reason you can override with the --config flag.\n\n 2) The writeback location. If any GRR component updates the configuration,\n changes will be written back to a different locally modified config\n file. This file specifies overrides of the main configuration file. The\n main reason is that typically the same locally written config file may be\n used with multiple versions of the GRR server because it specifies a very\n small and rarely changing set of options.\n\n '
config_opts = {}
flag_defaults = {}
if os.environ.get('GRR_CONFIG_FILE'):
flag_defaults['config'] = os.environ.get('GRR_CONFIG_FILE')
elif defaults.CONFIG_FILE:
flag_defaults['config'] = defaults.CONFIG_FILE
else:
flag_defaults['config'] = config_lib.Resource().Filter('install_data/etc/grr-server.yaml')
for (option, value) in config_opts.items():
config_lib.CONFIG.Set(option, value)
flags.PARSER.set_defaults(**flag_defaults)<|docstring|>Set location of configuration flags.
All GRR tools must use the same configuration files so they could all work
together. This needs to happen even before the configuration subsystem is
loaded so it must be bootstrapped by this code (all other options are
tweakable via the configuration system).
There are two main parts for the config system:
1) The main config file is shipped with the package and controls general
parameters. Note that this file is highly dependent on the exact version of
the grr package which is using it because it might have options which are
not understood by another version. We typically always use the config file
from package resources because in most cases this is the right thing to do
as this file matches exactly the running version. If you really have a good
reason you can override with the --config flag.
2) The writeback location. If any GRR component updates the configuration,
changes will be written back to a different locally modified config
file. This file specifies overrides of the main configuration file. The
main reason is that typically the same locally written config file may be
used with multiple versions of the GRR server because it specifies a very
small and rarely changing set of options.<|endoftext|>
|
d19e5ee84830c35166e52bdeff8ddaa4b25dea8f0adc2c91bece4b76d5c2bbb9
|
def _run_cmd(cmd):
'Run an arbitrary command and check exit status'
try:
retcode = subprocess.call(cmd, shell=True)
if (retcode < 0):
sys.stderr.write(('command terminated by signal %s' % (- retcode)))
except OSError as e:
sys.stderr.write(('command execution failed: %s' % e))
|
Run an arbitrary command and check exit status
|
examples/tinycbor/source/conf.py
|
_run_cmd
|
jcarrano/antidox
| 1
|
python
|
def _run_cmd(cmd):
try:
retcode = subprocess.call(cmd, shell=True)
if (retcode < 0):
sys.stderr.write(('command terminated by signal %s' % (- retcode)))
except OSError as e:
sys.stderr.write(('command execution failed: %s' % e))
|
def _run_cmd(cmd):
try:
retcode = subprocess.call(cmd, shell=True)
if (retcode < 0):
sys.stderr.write(('command terminated by signal %s' % (- retcode)))
except OSError as e:
sys.stderr.write(('command execution failed: %s' % e))<|docstring|>Run an arbitrary command and check exit status<|endoftext|>
|
cec4ce2ad292c3d54c838bfedc87d9e18c577e127b592261022a19a39d36513e
|
def generate_doxygen(app, config):
"Run the doxygen make commands if we're on the ReadTheDocs server"
if read_the_docs_build:
_run_cmd('make -C {} xml'.format(pathlib.Path(this_dir, '..')))
|
Run the doxygen make commands if we're on the ReadTheDocs server
|
examples/tinycbor/source/conf.py
|
generate_doxygen
|
jcarrano/antidox
| 1
|
python
|
def generate_doxygen(app, config):
if read_the_docs_build:
_run_cmd('make -C {} xml'.format(pathlib.Path(this_dir, '..')))
|
def generate_doxygen(app, config):
if read_the_docs_build:
_run_cmd('make -C {} xml'.format(pathlib.Path(this_dir, '..')))<|docstring|>Run the doxygen make commands if we're on the ReadTheDocs server<|endoftext|>
|
60e1f677b6c2e1b6140f0171948e58e0ce7270460d26c280bfd75807ca7bcfd5
|
def setup(app):
'Add hook for building doxygen xml when needed'
app.connect('config-inited', generate_doxygen)
|
Add hook for building doxygen xml when needed
|
examples/tinycbor/source/conf.py
|
setup
|
jcarrano/antidox
| 1
|
python
|
def setup(app):
app.connect('config-inited', generate_doxygen)
|
def setup(app):
app.connect('config-inited', generate_doxygen)<|docstring|>Add hook for building doxygen xml when needed<|endoftext|>
|
582ed6f4f6b6e500e91651da04999216b9ba7f6a1310bd98b2435c35a0066990
|
@contextmanager
def current_function(f):
'Adds f to the module namespace as _rumble_current_function, then\n removes it when exiting this context.'
global _rumble_current_function
_rumble_current_function = f
(yield)
del _rumble_current_function
|
Adds f to the module namespace as _rumble_current_function, then
removes it when exiting this context.
|
rumble/rumble.py
|
current_function
|
mambocab/simpletimeit
| 3
|
python
|
@contextmanager
def current_function(f):
'Adds f to the module namespace as _rumble_current_function, then\n removes it when exiting this context.'
global _rumble_current_function
_rumble_current_function = f
(yield)
del _rumble_current_function
|
@contextmanager
def current_function(f):
'Adds f to the module namespace as _rumble_current_function, then\n removes it when exiting this context.'
global _rumble_current_function
_rumble_current_function = f
(yield)
del _rumble_current_function<|docstring|>Adds f to the module namespace as _rumble_current_function, then
removes it when exiting this context.<|endoftext|>
|
9b5b9c8b0b5f381cdee72891b3d0d3b93e60dd53149ee155a9e893368f7c321b
|
def __init__(self):
'Initializes a Rumble object.'
self._functions = []
self._args_setups = []
|
Initializes a Rumble object.
|
rumble/rumble.py
|
__init__
|
mambocab/simpletimeit
| 3
|
python
|
def __init__(self):
self._functions = []
self._args_setups = []
|
def __init__(self):
self._functions = []
self._args_setups = []<|docstring|>Initializes a Rumble object.<|endoftext|>
|
f56497c9b152b23cfa8b0ad18199645f4533d03b833d55c42196b74b4d390124
|
def arguments(self, *args, **kwargs):
'Resisters a string as the argument list to the functions\n to be called as part of the performance comparisons. For instance, if\n a Rumble is specified as follows:\n\n from rumble.rumble import Rumble\n\n r = Rumble()\n r.arguments(\'Eric\', 3, x=10)\n\n @r.contender\n foo(name, n, x=15):\n pass\n\n Then `r.run()` will call (the equivalent of)\n\n exec(\'foo({args})\'.format(args="\'Eric\', 3, x=10"))\n\n If \'args\' is not a string, `arguments` will try to "do the right\n thing" and convert it to a string. If that string, when executed, will\n not render value equal to \'args\', this method will throw an error. So,\n for instance, `10` and `{a: 10, b: 15}` will work because\n `10 == eval(\'10\')` and `{a: 10, b: 15} == eval(\'{a: 10, b: 15}\')`, but\n `range(10)` will not work because `range(10) != eval(\'range(10)\').\n\n Takes an optional \'_setup\' argument. This string or callable will be\n evaluated before the timing runs, as with the \'setup\' argument to\n Timer. This value is \'pass\' by default.\n '
_setup = kwargs.pop('_setup', 'pass')
_name = kwargs.pop('_name', None)
try:
arg_string = args_to_string(*args, **kwargs)
except ValueError:
raise ValueError('{args} will be passed to a format string, which will then be executed as Python code. Thus, arguments must either be a string to be evaluated as the arguments to the timed function, or be a value whose string representation constructs an identical object. see the `arguments` documentation for more details.'.format(args=args))
if (not (isinstance(_setup, six.string_types) or callable(_setup))):
raise ValueError("'_setup' argument must be a string or callable.")
self.arguments_string(arg_string, _setup, _name)
|
Resisters a string as the argument list to the functions
to be called as part of the performance comparisons. For instance, if
a Rumble is specified as follows:
from rumble.rumble import Rumble
r = Rumble()
r.arguments('Eric', 3, x=10)
@r.contender
foo(name, n, x=15):
pass
Then `r.run()` will call (the equivalent of)
exec('foo({args})'.format(args="'Eric', 3, x=10"))
If 'args' is not a string, `arguments` will try to "do the right
thing" and convert it to a string. If that string, when executed, will
not render value equal to 'args', this method will throw an error. So,
for instance, `10` and `{a: 10, b: 15}` will work because
`10 == eval('10')` and `{a: 10, b: 15} == eval('{a: 10, b: 15}')`, but
`range(10)` will not work because `range(10) != eval('range(10)').
Takes an optional '_setup' argument. This string or callable will be
evaluated before the timing runs, as with the 'setup' argument to
Timer. This value is 'pass' by default.
|
rumble/rumble.py
|
arguments
|
mambocab/simpletimeit
| 3
|
python
|
def arguments(self, *args, **kwargs):
'Resisters a string as the argument list to the functions\n to be called as part of the performance comparisons. For instance, if\n a Rumble is specified as follows:\n\n from rumble.rumble import Rumble\n\n r = Rumble()\n r.arguments(\'Eric\', 3, x=10)\n\n @r.contender\n foo(name, n, x=15):\n pass\n\n Then `r.run()` will call (the equivalent of)\n\n exec(\'foo({args})\'.format(args="\'Eric\', 3, x=10"))\n\n If \'args\' is not a string, `arguments` will try to "do the right\n thing" and convert it to a string. If that string, when executed, will\n not render value equal to \'args\', this method will throw an error. So,\n for instance, `10` and `{a: 10, b: 15}` will work because\n `10 == eval(\'10\')` and `{a: 10, b: 15} == eval(\'{a: 10, b: 15}\')`, but\n `range(10)` will not work because `range(10) != eval(\'range(10)\').\n\n Takes an optional \'_setup\' argument. This string or callable will be\n evaluated before the timing runs, as with the \'setup\' argument to\n Timer. This value is \'pass\' by default.\n '
_setup = kwargs.pop('_setup', 'pass')
_name = kwargs.pop('_name', None)
try:
arg_string = args_to_string(*args, **kwargs)
except ValueError:
raise ValueError('{args} will be passed to a format string, which will then be executed as Python code. Thus, arguments must either be a string to be evaluated as the arguments to the timed function, or be a value whose string representation constructs an identical object. see the `arguments` documentation for more details.'.format(args=args))
if (not (isinstance(_setup, six.string_types) or callable(_setup))):
raise ValueError("'_setup' argument must be a string or callable.")
self.arguments_string(arg_string, _setup, _name)
|
def arguments(self, *args, **kwargs):
'Resisters a string as the argument list to the functions\n to be called as part of the performance comparisons. For instance, if\n a Rumble is specified as follows:\n\n from rumble.rumble import Rumble\n\n r = Rumble()\n r.arguments(\'Eric\', 3, x=10)\n\n @r.contender\n foo(name, n, x=15):\n pass\n\n Then `r.run()` will call (the equivalent of)\n\n exec(\'foo({args})\'.format(args="\'Eric\', 3, x=10"))\n\n If \'args\' is not a string, `arguments` will try to "do the right\n thing" and convert it to a string. If that string, when executed, will\n not render value equal to \'args\', this method will throw an error. So,\n for instance, `10` and `{a: 10, b: 15}` will work because\n `10 == eval(\'10\')` and `{a: 10, b: 15} == eval(\'{a: 10, b: 15}\')`, but\n `range(10)` will not work because `range(10) != eval(\'range(10)\').\n\n Takes an optional \'_setup\' argument. This string or callable will be\n evaluated before the timing runs, as with the \'setup\' argument to\n Timer. This value is \'pass\' by default.\n '
_setup = kwargs.pop('_setup', 'pass')
_name = kwargs.pop('_name', None)
try:
arg_string = args_to_string(*args, **kwargs)
except ValueError:
raise ValueError('{args} will be passed to a format string, which will then be executed as Python code. Thus, arguments must either be a string to be evaluated as the arguments to the timed function, or be a value whose string representation constructs an identical object. see the `arguments` documentation for more details.'.format(args=args))
if (not (isinstance(_setup, six.string_types) or callable(_setup))):
raise ValueError("'_setup' argument must be a string or callable.")
self.arguments_string(arg_string, _setup, _name)<|docstring|>Resisters a string as the argument list to the functions
to be called as part of the performance comparisons. For instance, if
a Rumble is specified as follows:
from rumble.rumble import Rumble
r = Rumble()
r.arguments('Eric', 3, x=10)
@r.contender
foo(name, n, x=15):
pass
Then `r.run()` will call (the equivalent of)
exec('foo({args})'.format(args="'Eric', 3, x=10"))
If 'args' is not a string, `arguments` will try to "do the right
thing" and convert it to a string. If that string, when executed, will
not render value equal to 'args', this method will throw an error. So,
for instance, `10` and `{a: 10, b: 15}` will work because
`10 == eval('10')` and `{a: 10, b: 15} == eval('{a: 10, b: 15}')`, but
`range(10)` will not work because `range(10) != eval('range(10)').
Takes an optional '_setup' argument. This string or callable will be
evaluated before the timing runs, as with the 'setup' argument to
Timer. This value is 'pass' by default.<|endoftext|>
|
789eccd5fcca90ad64146fc3597dce2960c5ccfc49fccfd236833580720d79dc
|
def contender(self, f):
'A decorator. Registers the decorated function as a TimedFunction\n with this Rumble, leaving the function unchanged.\n '
self._functions.append(f)
return f
|
A decorator. Registers the decorated function as a TimedFunction
with this Rumble, leaving the function unchanged.
|
rumble/rumble.py
|
contender
|
mambocab/simpletimeit
| 3
|
python
|
def contender(self, f):
'A decorator. Registers the decorated function as a TimedFunction\n with this Rumble, leaving the function unchanged.\n '
self._functions.append(f)
return f
|
def contender(self, f):
'A decorator. Registers the decorated function as a TimedFunction\n with this Rumble, leaving the function unchanged.\n '
self._functions.append(f)
return f<|docstring|>A decorator. Registers the decorated function as a TimedFunction
with this Rumble, leaving the function unchanged.<|endoftext|>
|
fb0f45465929839db383bb79ecbb8e1bfff70ab1135dd4184e84b87208b803ec
|
def _prepared_setup(self, setup, func):
'Generates the setup routine for a given timing run.'
setup_template = 'from rumble.rumble import _rumble_current_function\n{setup}'
if isinstance(setup, six.string_types):
return setup_template.format(setup=setup)
elif callable(setup):
def prepared_setup_callable():
global _rumble_current_function
_rumble_current_function = func
setup()
return prepared_setup_callable
else:
raise ValueError("'setup' must be a string or callable")
|
Generates the setup routine for a given timing run.
|
rumble/rumble.py
|
_prepared_setup
|
mambocab/simpletimeit
| 3
|
python
|
def _prepared_setup(self, setup, func):
setup_template = 'from rumble.rumble import _rumble_current_function\n{setup}'
if isinstance(setup, six.string_types):
return setup_template.format(setup=setup)
elif callable(setup):
def prepared_setup_callable():
global _rumble_current_function
_rumble_current_function = func
setup()
return prepared_setup_callable
else:
raise ValueError("'setup' must be a string or callable")
|
def _prepared_setup(self, setup, func):
setup_template = 'from rumble.rumble import _rumble_current_function\n{setup}'
if isinstance(setup, six.string_types):
return setup_template.format(setup=setup)
elif callable(setup):
def prepared_setup_callable():
global _rumble_current_function
_rumble_current_function = func
setup()
return prepared_setup_callable
else:
raise ValueError("'setup' must be a string or callable")<|docstring|>Generates the setup routine for a given timing run.<|endoftext|>
|
dc16d5dd623ccda01ffd46b71e3147fc36a181c27486c290c7fed2733a3a5933
|
def run(self, report_function=generate_table, as_string=False):
'Runs each of the functions registered with this Rumble using\n each arguments-setup pair registered with this Rumble.\n\n report_function should take a list of objects conforming to the\n Report API and return a string reporting on the comparison.\n\n If as_string is True, this function returns the table or tables\n generated as a string. Otherwise, it prints the tables to stdout and\n returns None.'
out = (six.StringIO() if as_string else sys.stdout)
for x in self._args_setups:
results = tuple(self._get_results(x.args, x.setup))
title = (x.name or 'args: {0}'.format(x.args))
print((report_function(results, title=title) + '\n'), file=out)
return (out.getvalue() if as_string else None)
|
Runs each of the functions registered with this Rumble using
each arguments-setup pair registered with this Rumble.
report_function should take a list of objects conforming to the
Report API and return a string reporting on the comparison.
If as_string is True, this function returns the table or tables
generated as a string. Otherwise, it prints the tables to stdout and
returns None.
|
rumble/rumble.py
|
run
|
mambocab/simpletimeit
| 3
|
python
|
def run(self, report_function=generate_table, as_string=False):
'Runs each of the functions registered with this Rumble using\n each arguments-setup pair registered with this Rumble.\n\n report_function should take a list of objects conforming to the\n Report API and return a string reporting on the comparison.\n\n If as_string is True, this function returns the table or tables\n generated as a string. Otherwise, it prints the tables to stdout and\n returns None.'
out = (six.StringIO() if as_string else sys.stdout)
for x in self._args_setups:
results = tuple(self._get_results(x.args, x.setup))
title = (x.name or 'args: {0}'.format(x.args))
print((report_function(results, title=title) + '\n'), file=out)
return (out.getvalue() if as_string else None)
|
def run(self, report_function=generate_table, as_string=False):
'Runs each of the functions registered with this Rumble using\n each arguments-setup pair registered with this Rumble.\n\n report_function should take a list of objects conforming to the\n Report API and return a string reporting on the comparison.\n\n If as_string is True, this function returns the table or tables\n generated as a string. Otherwise, it prints the tables to stdout and\n returns None.'
out = (six.StringIO() if as_string else sys.stdout)
for x in self._args_setups:
results = tuple(self._get_results(x.args, x.setup))
title = (x.name or 'args: {0}'.format(x.args))
print((report_function(results, title=title) + '\n'), file=out)
return (out.getvalue() if as_string else None)<|docstring|>Runs each of the functions registered with this Rumble using
each arguments-setup pair registered with this Rumble.
report_function should take a list of objects conforming to the
Report API and return a string reporting on the comparison.
If as_string is True, this function returns the table or tables
generated as a string. Otherwise, it prints the tables to stdout and
returns None.<|endoftext|>
|
fe68decab13d91045cdce26600103776f8a7d4718fa5e25533feaad073463e9f
|
def normalize_lab(lab_img):
'\n Normalizes the LAB image to lie in range 0-1\n \n Args:\n lab_img : torch.Tensor img in lab space\n \n Returns:\n lab_img : torch.Tensor Normalized lab_img \n '
mean = torch.zeros(lab_img.size())
stds = torch.zeros(lab_img.size())
mean[(:, 0, :, :)] = 50
mean[(:, 1, :, :)] = 0
mean[(:, 2, :, :)] = 0
stds[(:, 0, :, :)] = 50
stds[(:, 1, :, :)] = 128
stds[(:, 2, :, :)] = 128
return ((lab_img.double() - mean.double()) / stds.double())
|
Normalizes the LAB image to lie in range 0-1
Args:
lab_img : torch.Tensor img in lab space
Returns:
lab_img : torch.Tensor Normalized lab_img
|
util/texture_transforms.py
|
normalize_lab
|
MHC-F2V-Research/Image-Reconstruction-Ref2
| 197
|
python
|
def normalize_lab(lab_img):
'\n Normalizes the LAB image to lie in range 0-1\n \n Args:\n lab_img : torch.Tensor img in lab space\n \n Returns:\n lab_img : torch.Tensor Normalized lab_img \n '
mean = torch.zeros(lab_img.size())
stds = torch.zeros(lab_img.size())
mean[(:, 0, :, :)] = 50
mean[(:, 1, :, :)] = 0
mean[(:, 2, :, :)] = 0
stds[(:, 0, :, :)] = 50
stds[(:, 1, :, :)] = 128
stds[(:, 2, :, :)] = 128
return ((lab_img.double() - mean.double()) / stds.double())
|
def normalize_lab(lab_img):
'\n Normalizes the LAB image to lie in range 0-1\n \n Args:\n lab_img : torch.Tensor img in lab space\n \n Returns:\n lab_img : torch.Tensor Normalized lab_img \n '
mean = torch.zeros(lab_img.size())
stds = torch.zeros(lab_img.size())
mean[(:, 0, :, :)] = 50
mean[(:, 1, :, :)] = 0
mean[(:, 2, :, :)] = 0
stds[(:, 0, :, :)] = 50
stds[(:, 1, :, :)] = 128
stds[(:, 2, :, :)] = 128
return ((lab_img.double() - mean.double()) / stds.double())<|docstring|>Normalizes the LAB image to lie in range 0-1
Args:
lab_img : torch.Tensor img in lab space
Returns:
lab_img : torch.Tensor Normalized lab_img<|endoftext|>
|
e34bcb0f0dce26a58372890fe7cf469b763d7c80fbfd5abe25e8fe232422e6d7
|
def normalize_seg(seg):
'\n Normalizes the LAB image to lie in range 0-1\n \n Args:\n lab_img : torch.Tensor img in lab space\n \n Returns:\n lab_img : torch.Tensor Normalized lab_img \n '
result = seg[(:, 0, :, :)]
if (torch.max(result) > 1):
result = (result / 100.0)
result = torch.round(result)
return result
|
Normalizes the LAB image to lie in range 0-1
Args:
lab_img : torch.Tensor img in lab space
Returns:
lab_img : torch.Tensor Normalized lab_img
|
util/texture_transforms.py
|
normalize_seg
|
MHC-F2V-Research/Image-Reconstruction-Ref2
| 197
|
python
|
def normalize_seg(seg):
'\n Normalizes the LAB image to lie in range 0-1\n \n Args:\n lab_img : torch.Tensor img in lab space\n \n Returns:\n lab_img : torch.Tensor Normalized lab_img \n '
result = seg[(:, 0, :, :)]
if (torch.max(result) > 1):
result = (result / 100.0)
result = torch.round(result)
return result
|
def normalize_seg(seg):
'\n Normalizes the LAB image to lie in range 0-1\n \n Args:\n lab_img : torch.Tensor img in lab space\n \n Returns:\n lab_img : torch.Tensor Normalized lab_img \n '
result = seg[(:, 0, :, :)]
if (torch.max(result) > 1):
result = (result / 100.0)
result = torch.round(result)
return result<|docstring|>Normalizes the LAB image to lie in range 0-1
Args:
lab_img : torch.Tensor img in lab space
Returns:
lab_img : torch.Tensor Normalized lab_img<|endoftext|>
|
7b0aec173f7d13c04a7784e060fc710fb251bc4063febacd819e202419597e31
|
def normalize_rgb(rgb_img):
'\n Normalizes the LAB image to lie in range 0-1\n \n Args:\n lab_img : torch.Tensor img in lab space\n \n Returns:\n lab_img : torch.Tensor Normalized lab_img \n '
mean = torch.zeros(rgb_img.size())
stds = torch.zeros(rgb_img.size())
mean[(:, 0, :, :)] = 0.485
mean[(:, 1, :, :)] = 0.456
mean[(:, 2, :, :)] = 0.406
stds[(:, 0, :, :)] = 0.229
stds[(:, 1, :, :)] = 0.224
stds[(:, 2, :, :)] = 0.225
return ((rgb_img.double() - mean.double()) / stds.double())
|
Normalizes the LAB image to lie in range 0-1
Args:
lab_img : torch.Tensor img in lab space
Returns:
lab_img : torch.Tensor Normalized lab_img
|
util/texture_transforms.py
|
normalize_rgb
|
MHC-F2V-Research/Image-Reconstruction-Ref2
| 197
|
python
|
def normalize_rgb(rgb_img):
'\n Normalizes the LAB image to lie in range 0-1\n \n Args:\n lab_img : torch.Tensor img in lab space\n \n Returns:\n lab_img : torch.Tensor Normalized lab_img \n '
mean = torch.zeros(rgb_img.size())
stds = torch.zeros(rgb_img.size())
mean[(:, 0, :, :)] = 0.485
mean[(:, 1, :, :)] = 0.456
mean[(:, 2, :, :)] = 0.406
stds[(:, 0, :, :)] = 0.229
stds[(:, 1, :, :)] = 0.224
stds[(:, 2, :, :)] = 0.225
return ((rgb_img.double() - mean.double()) / stds.double())
|
def normalize_rgb(rgb_img):
'\n Normalizes the LAB image to lie in range 0-1\n \n Args:\n lab_img : torch.Tensor img in lab space\n \n Returns:\n lab_img : torch.Tensor Normalized lab_img \n '
mean = torch.zeros(rgb_img.size())
stds = torch.zeros(rgb_img.size())
mean[(:, 0, :, :)] = 0.485
mean[(:, 1, :, :)] = 0.456
mean[(:, 2, :, :)] = 0.406
stds[(:, 0, :, :)] = 0.229
stds[(:, 1, :, :)] = 0.224
stds[(:, 2, :, :)] = 0.225
return ((rgb_img.double() - mean.double()) / stds.double())<|docstring|>Normalizes the LAB image to lie in range 0-1
Args:
lab_img : torch.Tensor img in lab space
Returns:
lab_img : torch.Tensor Normalized lab_img<|endoftext|>
|
9309fd7fc3ef53f7332cb3838bc71f54ad7661a42963eff2c3e66941a9869cd7
|
def denormalize_lab(lab_img):
'\n Normalizes the LAB image to lie in range 0-1\n \n Args:\n lab_img : torch.Tensor img in lab space\n \n Returns:\n lab_img : torch.Tensor Normalized lab_img \n '
mean = torch.zeros(lab_img.size())
stds = torch.zeros(lab_img.size())
mean[(:, 0, :, :)] = 50
mean[(:, 1, :, :)] = 0
mean[(:, 2, :, :)] = 0
stds[(:, 0, :, :)] = 50
stds[(:, 1, :, :)] = 128
stds[(:, 2, :, :)] = 128
return ((lab_img.double() * stds.double()) + mean.double())
|
Normalizes the LAB image to lie in range 0-1
Args:
lab_img : torch.Tensor img in lab space
Returns:
lab_img : torch.Tensor Normalized lab_img
|
util/texture_transforms.py
|
denormalize_lab
|
MHC-F2V-Research/Image-Reconstruction-Ref2
| 197
|
python
|
def denormalize_lab(lab_img):
'\n Normalizes the LAB image to lie in range 0-1\n \n Args:\n lab_img : torch.Tensor img in lab space\n \n Returns:\n lab_img : torch.Tensor Normalized lab_img \n '
mean = torch.zeros(lab_img.size())
stds = torch.zeros(lab_img.size())
mean[(:, 0, :, :)] = 50
mean[(:, 1, :, :)] = 0
mean[(:, 2, :, :)] = 0
stds[(:, 0, :, :)] = 50
stds[(:, 1, :, :)] = 128
stds[(:, 2, :, :)] = 128
return ((lab_img.double() * stds.double()) + mean.double())
|
def denormalize_lab(lab_img):
'\n Normalizes the LAB image to lie in range 0-1\n \n Args:\n lab_img : torch.Tensor img in lab space\n \n Returns:\n lab_img : torch.Tensor Normalized lab_img \n '
mean = torch.zeros(lab_img.size())
stds = torch.zeros(lab_img.size())
mean[(:, 0, :, :)] = 50
mean[(:, 1, :, :)] = 0
mean[(:, 2, :, :)] = 0
stds[(:, 0, :, :)] = 50
stds[(:, 1, :, :)] = 128
stds[(:, 2, :, :)] = 128
return ((lab_img.double() * stds.double()) + mean.double())<|docstring|>Normalizes the LAB image to lie in range 0-1
Args:
lab_img : torch.Tensor img in lab space
Returns:
lab_img : torch.Tensor Normalized lab_img<|endoftext|>
|
65b64c45d348ce8e0360c8b6772b7243109d60fec507f3b4f5c7c5ea2bd98023
|
def denormalize_rgb(rgb_img):
'\n Normalizes the LAB image to lie in range 0-1\n \n Args:\n lab_img : torch.Tensor img in lab space\n \n Returns:\n lab_img : torch.Tensor Normalized lab_img \n '
mean = torch.zeros(rgb_img.size())
stds = torch.zeros(rgb_img.size())
mean[(:, 0, :, :)] = 0.485
mean[(:, 1, :, :)] = 0.456
mean[(:, 2, :, :)] = 0.406
stds[(:, 0, :, :)] = 0.229
stds[(:, 1, :, :)] = 0.224
stds[(:, 2, :, :)] = 0.225
return ((rgb_img.double() * stds.double()) + mean.double())
|
Normalizes the LAB image to lie in range 0-1
Args:
lab_img : torch.Tensor img in lab space
Returns:
lab_img : torch.Tensor Normalized lab_img
|
util/texture_transforms.py
|
denormalize_rgb
|
MHC-F2V-Research/Image-Reconstruction-Ref2
| 197
|
python
|
def denormalize_rgb(rgb_img):
'\n Normalizes the LAB image to lie in range 0-1\n \n Args:\n lab_img : torch.Tensor img in lab space\n \n Returns:\n lab_img : torch.Tensor Normalized lab_img \n '
mean = torch.zeros(rgb_img.size())
stds = torch.zeros(rgb_img.size())
mean[(:, 0, :, :)] = 0.485
mean[(:, 1, :, :)] = 0.456
mean[(:, 2, :, :)] = 0.406
stds[(:, 0, :, :)] = 0.229
stds[(:, 1, :, :)] = 0.224
stds[(:, 2, :, :)] = 0.225
return ((rgb_img.double() * stds.double()) + mean.double())
|
def denormalize_rgb(rgb_img):
'\n Normalizes the LAB image to lie in range 0-1\n \n Args:\n lab_img : torch.Tensor img in lab space\n \n Returns:\n lab_img : torch.Tensor Normalized lab_img \n '
mean = torch.zeros(rgb_img.size())
stds = torch.zeros(rgb_img.size())
mean[(:, 0, :, :)] = 0.485
mean[(:, 1, :, :)] = 0.456
mean[(:, 2, :, :)] = 0.406
stds[(:, 0, :, :)] = 0.229
stds[(:, 1, :, :)] = 0.224
stds[(:, 2, :, :)] = 0.225
return ((rgb_img.double() * stds.double()) + mean.double())<|docstring|>Normalizes the LAB image to lie in range 0-1
Args:
lab_img : torch.Tensor img in lab space
Returns:
lab_img : torch.Tensor Normalized lab_img<|endoftext|>
|
bcc697034a3aaae42033a9043ecc30f2b2df198054f726c442f01411fb948bf0
|
def __call__(self, imgs):
'\n Args:\n imgs (list of PIL.Image): Images to be scaled.\n Returns:\n list of PIL.Image: Rescaled images.\n '
return [self.transform(img) for img in imgs]
|
Args:
imgs (list of PIL.Image): Images to be scaled.
Returns:
list of PIL.Image: Rescaled images.
|
util/texture_transforms.py
|
__call__
|
MHC-F2V-Research/Image-Reconstruction-Ref2
| 197
|
python
|
def __call__(self, imgs):
'\n Args:\n imgs (list of PIL.Image): Images to be scaled.\n Returns:\n list of PIL.Image: Rescaled images.\n '
return [self.transform(img) for img in imgs]
|
def __call__(self, imgs):
'\n Args:\n imgs (list of PIL.Image): Images to be scaled.\n Returns:\n list of PIL.Image: Rescaled images.\n '
return [self.transform(img) for img in imgs]<|docstring|>Args:
imgs (list of PIL.Image): Images to be scaled.
Returns:
list of PIL.Image: Rescaled images.<|endoftext|>
|
e65d84253597c991417afe79d6f53d4ad922a74dfb10c33342dcd438f3de8b0c
|
def __call__(self, imgs):
'\n Args:\n imgs (PIL.Image): Image to be cropped.\n Returns:\n PIL.Image: Cropped image.\n '
return [self.transform(img) for img in imgs]
|
Args:
imgs (PIL.Image): Image to be cropped.
Returns:
PIL.Image: Cropped image.
|
util/texture_transforms.py
|
__call__
|
MHC-F2V-Research/Image-Reconstruction-Ref2
| 197
|
python
|
def __call__(self, imgs):
'\n Args:\n imgs (PIL.Image): Image to be cropped.\n Returns:\n PIL.Image: Cropped image.\n '
return [self.transform(img) for img in imgs]
|
def __call__(self, imgs):
'\n Args:\n imgs (PIL.Image): Image to be cropped.\n Returns:\n PIL.Image: Cropped image.\n '
return [self.transform(img) for img in imgs]<|docstring|>Args:
imgs (PIL.Image): Image to be cropped.
Returns:
PIL.Image: Cropped image.<|endoftext|>
|
f201205baaba1398e0f6c9337081c3371d1262f0162483fe3c501ba83b263c43
|
def __call__(self, imgs):
'\n Args:\n img (PIL.Image): Image to be padded.\n Returns:\n PIL.Image: Padded image.\n '
return [self.transform(img) for img in imgs]
|
Args:
img (PIL.Image): Image to be padded.
Returns:
PIL.Image: Padded image.
|
util/texture_transforms.py
|
__call__
|
MHC-F2V-Research/Image-Reconstruction-Ref2
| 197
|
python
|
def __call__(self, imgs):
'\n Args:\n img (PIL.Image): Image to be padded.\n Returns:\n PIL.Image: Padded image.\n '
return [self.transform(img) for img in imgs]
|
def __call__(self, imgs):
'\n Args:\n img (PIL.Image): Image to be padded.\n Returns:\n PIL.Image: Padded image.\n '
return [self.transform(img) for img in imgs]<|docstring|>Args:
img (PIL.Image): Image to be padded.
Returns:
PIL.Image: Padded image.<|endoftext|>
|
8cc3091055ce1851c0ecad6378e8187b7fa1396b9d0f1fa735290aeeaeab95fc
|
def __call__(self, imgs):
'\n Args:\n img (PIL.Image): Image to be cropped.\n Returns:\n PIL.Image: Cropped image.\n '
if (self.padding > 0):
imgs = [ImageOps.expand(img, border=self.padding, fill=0) for img in imgs]
(w, h) = imgs[0].size
(th, tw) = self.size
if ((w == tw) and (h == th)):
return imgs
x1 = random.randint(0, (w - tw))
y1 = random.randint(0, (h - th))
return [img.crop((x1, y1, (x1 + tw), (y1 + th))) for img in imgs]
|
Args:
img (PIL.Image): Image to be cropped.
Returns:
PIL.Image: Cropped image.
|
util/texture_transforms.py
|
__call__
|
MHC-F2V-Research/Image-Reconstruction-Ref2
| 197
|
python
|
def __call__(self, imgs):
'\n Args:\n img (PIL.Image): Image to be cropped.\n Returns:\n PIL.Image: Cropped image.\n '
if (self.padding > 0):
imgs = [ImageOps.expand(img, border=self.padding, fill=0) for img in imgs]
(w, h) = imgs[0].size
(th, tw) = self.size
if ((w == tw) and (h == th)):
return imgs
x1 = random.randint(0, (w - tw))
y1 = random.randint(0, (h - th))
return [img.crop((x1, y1, (x1 + tw), (y1 + th))) for img in imgs]
|
def __call__(self, imgs):
'\n Args:\n img (PIL.Image): Image to be cropped.\n Returns:\n PIL.Image: Cropped image.\n '
if (self.padding > 0):
imgs = [ImageOps.expand(img, border=self.padding, fill=0) for img in imgs]
(w, h) = imgs[0].size
(th, tw) = self.size
if ((w == tw) and (h == th)):
return imgs
x1 = random.randint(0, (w - tw))
y1 = random.randint(0, (h - th))
return [img.crop((x1, y1, (x1 + tw), (y1 + th))) for img in imgs]<|docstring|>Args:
img (PIL.Image): Image to be cropped.
Returns:
PIL.Image: Cropped image.<|endoftext|>
|
1dd28691909431dceb9d7f4647b35eae3a6d3edb244889399e7abf3f4c2ed6de
|
def __call__(self, imgs):
'\n Args:\n img (PIL.Image): Image to be flipped.\n Returns:\n PIL.Image: Randomly flipped image.\n '
if (random.random() < 0.5):
return [img.transpose(Image.FLIP_LEFT_RIGHT) for img in imgs]
return imgs
|
Args:
img (PIL.Image): Image to be flipped.
Returns:
PIL.Image: Randomly flipped image.
|
util/texture_transforms.py
|
__call__
|
MHC-F2V-Research/Image-Reconstruction-Ref2
| 197
|
python
|
def __call__(self, imgs):
'\n Args:\n img (PIL.Image): Image to be flipped.\n Returns:\n PIL.Image: Randomly flipped image.\n '
if (random.random() < 0.5):
return [img.transpose(Image.FLIP_LEFT_RIGHT) for img in imgs]
return imgs
|
def __call__(self, imgs):
'\n Args:\n img (PIL.Image): Image to be flipped.\n Returns:\n PIL.Image: Randomly flipped image.\n '
if (random.random() < 0.5):
return [img.transpose(Image.FLIP_LEFT_RIGHT) for img in imgs]
return imgs<|docstring|>Args:
img (PIL.Image): Image to be flipped.
Returns:
PIL.Image: Randomly flipped image.<|endoftext|>
|
1e4eedc24239e4cbc0b1fa60e2a28be1cf4188d338ebbe7d0918f46e18cef9c7
|
def __init__(self, classifier, name: str, title: str, params: dict):
'\n params: model parameters to fit using cross validation\n '
SKLearnModel.__init__(self, classifier, name, title, params)
self.grid_search = None
self.best_parameters = None
|
params: model parameters to fit using cross validation
|
basic/models.py
|
__init__
|
scidatasoft/jaml
| 0
|
python
|
def __init__(self, classifier, name: str, title: str, params: dict):
'\n \n '
SKLearnModel.__init__(self, classifier, name, title, params)
self.grid_search = None
self.best_parameters = None
|
def __init__(self, classifier, name: str, title: str, params: dict):
'\n \n '
SKLearnModel.__init__(self, classifier, name, title, params)
self.grid_search = None
self.best_parameters = None<|docstring|>params: model parameters to fit using cross validation<|endoftext|>
|
b9d1fa71b2e175a1b7dae3ee970b1312914e52d76e9a6060918b7016ca2a659e
|
def fit(self, X_train, y_train, cv=None, callback=None, hyper_params=None) -> dict:
' performs a grid search over the model parameters '
hyper_search = GridSearchCV(self.estimator, self.params, cv=cv, scoring=(stats.regress_scoring if self.name.endswith('r') else stats.class_scoring), refit=('R2' if self.name.endswith('r') else 'AUC'))
hyper_search.fit((X_train.values if ('values' in dir(X_train)) else X_train), y_train)
self.grid_search = hyper_search
self.model = hyper_search.best_estimator_
self.best_parameters = hyper_search.best_params_
print(f'Best params {hyper_search.best_params_} out of {self.params}')
return self.get_metrics(X_train, y_train)
|
performs a grid search over the model parameters
|
basic/models.py
|
fit
|
scidatasoft/jaml
| 0
|
python
|
def fit(self, X_train, y_train, cv=None, callback=None, hyper_params=None) -> dict:
' '
hyper_search = GridSearchCV(self.estimator, self.params, cv=cv, scoring=(stats.regress_scoring if self.name.endswith('r') else stats.class_scoring), refit=('R2' if self.name.endswith('r') else 'AUC'))
hyper_search.fit((X_train.values if ('values' in dir(X_train)) else X_train), y_train)
self.grid_search = hyper_search
self.model = hyper_search.best_estimator_
self.best_parameters = hyper_search.best_params_
print(f'Best params {hyper_search.best_params_} out of {self.params}')
return self.get_metrics(X_train, y_train)
|
def fit(self, X_train, y_train, cv=None, callback=None, hyper_params=None) -> dict:
' '
hyper_search = GridSearchCV(self.estimator, self.params, cv=cv, scoring=(stats.regress_scoring if self.name.endswith('r') else stats.class_scoring), refit=('R2' if self.name.endswith('r') else 'AUC'))
hyper_search.fit((X_train.values if ('values' in dir(X_train)) else X_train), y_train)
self.grid_search = hyper_search
self.model = hyper_search.best_estimator_
self.best_parameters = hyper_search.best_params_
print(f'Best params {hyper_search.best_params_} out of {self.params}')
return self.get_metrics(X_train, y_train)<|docstring|>performs a grid search over the model parameters<|endoftext|>
|
f247fa02b8d751624b76ff826aa3ed9cc54ff866aced2236b961cb4460eb84a4
|
def fit(self, X_train, y_train, cv=None, callback=None, hyper_params=None) -> dict:
' calibrate the model '
self.model = CalibratedClassifierCV(self.estimator, cv=cv, method='isotonic').fit((X_train.values if ('values' in dir(X_train)) else X_train), y_train)
return self.get_metrics(X_train, y_train)
|
calibrate the model
|
basic/models.py
|
fit
|
scidatasoft/jaml
| 0
|
python
|
def fit(self, X_train, y_train, cv=None, callback=None, hyper_params=None) -> dict:
' '
self.model = CalibratedClassifierCV(self.estimator, cv=cv, method='isotonic').fit((X_train.values if ('values' in dir(X_train)) else X_train), y_train)
return self.get_metrics(X_train, y_train)
|
def fit(self, X_train, y_train, cv=None, callback=None, hyper_params=None) -> dict:
' '
self.model = CalibratedClassifierCV(self.estimator, cv=cv, method='isotonic').fit((X_train.values if ('values' in dir(X_train)) else X_train), y_train)
return self.get_metrics(X_train, y_train)<|docstring|>calibrate the model<|endoftext|>
|
4da12f8ed1d61fa632bd764f6938e988444ea44e4ba4b1114cbec230f6d96060
|
def __init__(self, name: str, title: str, params: dict=None):
'For DL actual classifier is built later, so None is passed to the base class'
SKLearnModel.__init__(self, None, name, title, params)
self.classes_ = None
|
For DL actual classifier is built later, so None is passed to the base class
|
basic/models.py
|
__init__
|
scidatasoft/jaml
| 0
|
python
|
def __init__(self, name: str, title: str, params: dict=None):
SKLearnModel.__init__(self, None, name, title, params)
self.classes_ = None
|
def __init__(self, name: str, title: str, params: dict=None):
SKLearnModel.__init__(self, None, name, title, params)
self.classes_ = None<|docstring|>For DL actual classifier is built later, so None is passed to the base class<|endoftext|>
|
9c33ef08edac524e4d2cd505545163307cdde85fe71f26f567e4ccd31b755fcd
|
def StartingParameters(fitmodel, peaks, xpeak=[0], ypeak=[0], i=0):
"Define starting parameters for different functions.\n\n The initial values of the fit depend on the maxima of the peaks but\n also on their line shapes. They have to be chosen carefully.\n In addition the borders of the fit parameters are set in this function.\n Supplementary to the fit parameters and parameters calculated from\n them provided by\n `lmfit <https://lmfit.github.io/lmfit-py/builtin_models.html#>`_\n the FWHM of the voigt-profile as well as the height and intensity\n of the breit-wigner-fano-profile are given.\n\n Parameters\n ----------\n fitmodel : class\n Model chosen in :func:`~starting_params.ChoosePeakType`.\n peaks : list, default: ['breit_wigner', 'lorentzian']\n Possible line shapes of the peaks to fit are\n 'breit_wigner', 'lorentzian', 'gaussian', and 'voigt'.\n xpeak array (float), default = 0\n Position of the peak's maxima (x-value).\n ypeak array (float), default = 0\n Height of the peak's maxima (y-value).\n i : int\n Integer between 0 and (N-1) to distinguish between N peaks of\n the same peaktype. It is used in the prefix.\n\n Returns\n -------\n fitmodel : class\n Model chosen in :func:`~starting_params.ChoosePeakType`\n including initial values for the fit (set_param_hint).\n "
fitmodel.set_param_hint('center', value=xpeak[i], min=(xpeak[i] - 50), max=(xpeak[i] + 50))
model = re.findall('\\((.*?),', fitmodel.name)
model = model[0]
if any(((model in peak) for peak in peaks)):
if (model == 'voigt'):
fitmodel.set_param_hint('sigma', value=10, min=0, max=100)
fitmodel.set_param_hint('gamma', value=5, min=0, max=100, vary=True, expr='')
fitmodel.set_param_hint('amplitude', value=(ypeak[i] * 20), min=0)
fitmodel.set_param_hint('height', value=ypeak[i])
fitmodel.set_param_hint('fwhm_g', expr=f'2 * {fitmodel.prefix}sigma* sqrt(2 * log(2))')
fitmodel.set_param_hint('fwhm_l', expr=f'2 * {fitmodel.prefix}gamma')
fitmodel.set_param_hint('fwhm', expr=f'0.5346 * {fitmodel.prefix}fwhm_l+ sqrt(0.2166* {fitmodel.prefix}fwhm_l**2+ {fitmodel.prefix}fwhm_g**2 )')
if (model == 'breit_wigner'):
fitmodel.set_param_hint('sigma', value=100, min=0, max=200)
fitmodel.set_param_hint('q', value=(- 5), min=(- 100), max=100)
fitmodel.set_param_hint('amplitude', value=(ypeak[i] / 50), min=0)
fitmodel.set_param_hint('height', expr=f'{fitmodel.prefix}amplitude* (({fitmodel.prefix}q )**2+1)')
fitmodel.set_param_hint('intensity', expr=f'{fitmodel.prefix}amplitude* ({fitmodel.prefix}q )**2')
if (model == 'lorentzian'):
fitmodel.set_param_hint('sigma', value=50, min=0, max=150)
fitmodel.set_param_hint('amplitude', value=20, min=0)
fitmodel.set_param_hint('height')
fitmodel.set_param_hint('fwhm')
if (model == 'gaussian'):
fitmodel.set_param_hint('sigma', value=1, min=0, max=150)
fitmodel.set_param_hint('amplitude', value=(ypeak[i] * 11), min=0)
fitmodel.set_param_hint('height')
fitmodel.set_param_hint('fwhm')
else:
print((('Used ' + model) + ' model is not in List'))
return fitmodel
|
Define starting parameters for different functions.
The initial values of the fit depend on the maxima of the peaks but
also on their line shapes. They have to be chosen carefully.
In addition the borders of the fit parameters are set in this function.
Supplementary to the fit parameters and parameters calculated from
them provided by
`lmfit <https://lmfit.github.io/lmfit-py/builtin_models.html#>`_
the FWHM of the voigt-profile as well as the height and intensity
of the breit-wigner-fano-profile are given.
Parameters
----------
fitmodel : class
Model chosen in :func:`~starting_params.ChoosePeakType`.
peaks : list, default: ['breit_wigner', 'lorentzian']
Possible line shapes of the peaks to fit are
'breit_wigner', 'lorentzian', 'gaussian', and 'voigt'.
xpeak array (float), default = 0
Position of the peak's maxima (x-value).
ypeak array (float), default = 0
Height of the peak's maxima (y-value).
i : int
Integer between 0 and (N-1) to distinguish between N peaks of
the same peaktype. It is used in the prefix.
Returns
-------
fitmodel : class
Model chosen in :func:`~starting_params.ChoosePeakType`
including initial values for the fit (set_param_hint).
|
lib/spectrum_analysis/starting_params.py
|
StartingParameters
|
hmoldenhauer/spectrum_analysis
| 1
|
python
|
def StartingParameters(fitmodel, peaks, xpeak=[0], ypeak=[0], i=0):
"Define starting parameters for different functions.\n\n The initial values of the fit depend on the maxima of the peaks but\n also on their line shapes. They have to be chosen carefully.\n In addition the borders of the fit parameters are set in this function.\n Supplementary to the fit parameters and parameters calculated from\n them provided by\n `lmfit <https://lmfit.github.io/lmfit-py/builtin_models.html#>`_\n the FWHM of the voigt-profile as well as the height and intensity\n of the breit-wigner-fano-profile are given.\n\n Parameters\n ----------\n fitmodel : class\n Model chosen in :func:`~starting_params.ChoosePeakType`.\n peaks : list, default: ['breit_wigner', 'lorentzian']\n Possible line shapes of the peaks to fit are\n 'breit_wigner', 'lorentzian', 'gaussian', and 'voigt'.\n xpeak array (float), default = 0\n Position of the peak's maxima (x-value).\n ypeak array (float), default = 0\n Height of the peak's maxima (y-value).\n i : int\n Integer between 0 and (N-1) to distinguish between N peaks of\n the same peaktype. It is used in the prefix.\n\n Returns\n -------\n fitmodel : class\n Model chosen in :func:`~starting_params.ChoosePeakType`\n including initial values for the fit (set_param_hint).\n "
fitmodel.set_param_hint('center', value=xpeak[i], min=(xpeak[i] - 50), max=(xpeak[i] + 50))
model = re.findall('\\((.*?),', fitmodel.name)
model = model[0]
if any(((model in peak) for peak in peaks)):
if (model == 'voigt'):
fitmodel.set_param_hint('sigma', value=10, min=0, max=100)
fitmodel.set_param_hint('gamma', value=5, min=0, max=100, vary=True, expr=)
fitmodel.set_param_hint('amplitude', value=(ypeak[i] * 20), min=0)
fitmodel.set_param_hint('height', value=ypeak[i])
fitmodel.set_param_hint('fwhm_g', expr=f'2 * {fitmodel.prefix}sigma* sqrt(2 * log(2))')
fitmodel.set_param_hint('fwhm_l', expr=f'2 * {fitmodel.prefix}gamma')
fitmodel.set_param_hint('fwhm', expr=f'0.5346 * {fitmodel.prefix}fwhm_l+ sqrt(0.2166* {fitmodel.prefix}fwhm_l**2+ {fitmodel.prefix}fwhm_g**2 )')
if (model == 'breit_wigner'):
fitmodel.set_param_hint('sigma', value=100, min=0, max=200)
fitmodel.set_param_hint('q', value=(- 5), min=(- 100), max=100)
fitmodel.set_param_hint('amplitude', value=(ypeak[i] / 50), min=0)
fitmodel.set_param_hint('height', expr=f'{fitmodel.prefix}amplitude* (({fitmodel.prefix}q )**2+1)')
fitmodel.set_param_hint('intensity', expr=f'{fitmodel.prefix}amplitude* ({fitmodel.prefix}q )**2')
if (model == 'lorentzian'):
fitmodel.set_param_hint('sigma', value=50, min=0, max=150)
fitmodel.set_param_hint('amplitude', value=20, min=0)
fitmodel.set_param_hint('height')
fitmodel.set_param_hint('fwhm')
if (model == 'gaussian'):
fitmodel.set_param_hint('sigma', value=1, min=0, max=150)
fitmodel.set_param_hint('amplitude', value=(ypeak[i] * 11), min=0)
fitmodel.set_param_hint('height')
fitmodel.set_param_hint('fwhm')
else:
print((('Used ' + model) + ' model is not in List'))
return fitmodel
|
def StartingParameters(fitmodel, peaks, xpeak=[0], ypeak=[0], i=0):
"Define starting parameters for different functions.\n\n The initial values of the fit depend on the maxima of the peaks but\n also on their line shapes. They have to be chosen carefully.\n In addition the borders of the fit parameters are set in this function.\n Supplementary to the fit parameters and parameters calculated from\n them provided by\n `lmfit <https://lmfit.github.io/lmfit-py/builtin_models.html#>`_\n the FWHM of the voigt-profile as well as the height and intensity\n of the breit-wigner-fano-profile are given.\n\n Parameters\n ----------\n fitmodel : class\n Model chosen in :func:`~starting_params.ChoosePeakType`.\n peaks : list, default: ['breit_wigner', 'lorentzian']\n Possible line shapes of the peaks to fit are\n 'breit_wigner', 'lorentzian', 'gaussian', and 'voigt'.\n xpeak array (float), default = 0\n Position of the peak's maxima (x-value).\n ypeak array (float), default = 0\n Height of the peak's maxima (y-value).\n i : int\n Integer between 0 and (N-1) to distinguish between N peaks of\n the same peaktype. It is used in the prefix.\n\n Returns\n -------\n fitmodel : class\n Model chosen in :func:`~starting_params.ChoosePeakType`\n including initial values for the fit (set_param_hint).\n "
fitmodel.set_param_hint('center', value=xpeak[i], min=(xpeak[i] - 50), max=(xpeak[i] + 50))
model = re.findall('\\((.*?),', fitmodel.name)
model = model[0]
if any(((model in peak) for peak in peaks)):
if (model == 'voigt'):
fitmodel.set_param_hint('sigma', value=10, min=0, max=100)
fitmodel.set_param_hint('gamma', value=5, min=0, max=100, vary=True, expr=)
fitmodel.set_param_hint('amplitude', value=(ypeak[i] * 20), min=0)
fitmodel.set_param_hint('height', value=ypeak[i])
fitmodel.set_param_hint('fwhm_g', expr=f'2 * {fitmodel.prefix}sigma* sqrt(2 * log(2))')
fitmodel.set_param_hint('fwhm_l', expr=f'2 * {fitmodel.prefix}gamma')
fitmodel.set_param_hint('fwhm', expr=f'0.5346 * {fitmodel.prefix}fwhm_l+ sqrt(0.2166* {fitmodel.prefix}fwhm_l**2+ {fitmodel.prefix}fwhm_g**2 )')
if (model == 'breit_wigner'):
fitmodel.set_param_hint('sigma', value=100, min=0, max=200)
fitmodel.set_param_hint('q', value=(- 5), min=(- 100), max=100)
fitmodel.set_param_hint('amplitude', value=(ypeak[i] / 50), min=0)
fitmodel.set_param_hint('height', expr=f'{fitmodel.prefix}amplitude* (({fitmodel.prefix}q )**2+1)')
fitmodel.set_param_hint('intensity', expr=f'{fitmodel.prefix}amplitude* ({fitmodel.prefix}q )**2')
if (model == 'lorentzian'):
fitmodel.set_param_hint('sigma', value=50, min=0, max=150)
fitmodel.set_param_hint('amplitude', value=20, min=0)
fitmodel.set_param_hint('height')
fitmodel.set_param_hint('fwhm')
if (model == 'gaussian'):
fitmodel.set_param_hint('sigma', value=1, min=0, max=150)
fitmodel.set_param_hint('amplitude', value=(ypeak[i] * 11), min=0)
fitmodel.set_param_hint('height')
fitmodel.set_param_hint('fwhm')
else:
print((('Used ' + model) + ' model is not in List'))
return fitmodel<|docstring|>Define starting parameters for different functions.
The initial values of the fit depend on the maxima of the peaks but
also on their line shapes. They have to be chosen carefully.
In addition the borders of the fit parameters are set in this function.
Supplementary to the fit parameters and parameters calculated from
them provided by
`lmfit <https://lmfit.github.io/lmfit-py/builtin_models.html#>`_
the FWHM of the voigt-profile as well as the height and intensity
of the breit-wigner-fano-profile are given.
Parameters
----------
fitmodel : class
Model chosen in :func:`~starting_params.ChoosePeakType`.
peaks : list, default: ['breit_wigner', 'lorentzian']
Possible line shapes of the peaks to fit are
'breit_wigner', 'lorentzian', 'gaussian', and 'voigt'.
xpeak array (float), default = 0
Position of the peak's maxima (x-value).
ypeak array (float), default = 0
Height of the peak's maxima (y-value).
i : int
Integer between 0 and (N-1) to distinguish between N peaks of
the same peaktype. It is used in the prefix.
Returns
-------
fitmodel : class
Model chosen in :func:`~starting_params.ChoosePeakType`
including initial values for the fit (set_param_hint).<|endoftext|>
|
089a1babfb4803a40736dcd9c0e43ad432547d3102899dc8f1a47934c5c1f0a6
|
def __init__(self, l1MDP, state_mapper, verbose=False, env_file=[], constraints={}, ap_maps={}):
'\n Args:\n l1MDP (CleanupMDP): lower domain\n state_mapper (AbstractGridWorldL1StateMapper): to map l0 states to l1 domain\n verbose (bool): debug mode\n '
self.domain = l1MDP
self.verbose = verbose
self.state_mapper = state_mapper
self.env_file = env_file
|
Args:
l1MDP (CleanupMDP): lower domain
state_mapper (AbstractGridWorldL1StateMapper): to map l0 states to l1 domain
verbose (bool): debug mode
|
simple_rl/apmdp/AP_MDP/cleanup/AbstractCleanupPolicyGeneratorClass.py
|
__init__
|
yoonseon-oh/simple_rl
| 2
|
python
|
def __init__(self, l1MDP, state_mapper, verbose=False, env_file=[], constraints={}, ap_maps={}):
'\n Args:\n l1MDP (CleanupMDP): lower domain\n state_mapper (AbstractGridWorldL1StateMapper): to map l0 states to l1 domain\n verbose (bool): debug mode\n '
self.domain = l1MDP
self.verbose = verbose
self.state_mapper = state_mapper
self.env_file = env_file
|
def __init__(self, l1MDP, state_mapper, verbose=False, env_file=[], constraints={}, ap_maps={}):
'\n Args:\n l1MDP (CleanupMDP): lower domain\n state_mapper (AbstractGridWorldL1StateMapper): to map l0 states to l1 domain\n verbose (bool): debug mode\n '
self.domain = l1MDP
self.verbose = verbose
self.state_mapper = state_mapper
self.env_file = env_file<|docstring|>Args:
l1MDP (CleanupMDP): lower domain
state_mapper (AbstractGridWorldL1StateMapper): to map l0 states to l1 domain
verbose (bool): debug mode<|endoftext|>
|
5c2c84587b534943cc074740e67cef17374ffb0ae10ccd388908da7d2b12fa10
|
def generate_policy(self, l2_state, grounded_action):
'\n Args:\n l1_state (CleanupL1State): generate policy in l1 domain starting from l1_state\n grounded_action (CleanupRootGroundedAction): TaskNode above defining the subgoal for current MDP\n '
mdp = CleanupL2MDP(init_state=l2_state, env_file=self.env_file, constraints=grounded_action.goal_constraints, ap_maps=grounded_action.ap_maps)
return self.get_policy(mdp, verbose=self.verbose, max_iterations=50, horizon=50)
|
Args:
l1_state (CleanupL1State): generate policy in l1 domain starting from l1_state
grounded_action (CleanupRootGroundedAction): TaskNode above defining the subgoal for current MDP
|
simple_rl/apmdp/AP_MDP/cleanup/AbstractCleanupPolicyGeneratorClass.py
|
generate_policy
|
yoonseon-oh/simple_rl
| 2
|
python
|
def generate_policy(self, l2_state, grounded_action):
'\n Args:\n l1_state (CleanupL1State): generate policy in l1 domain starting from l1_state\n grounded_action (CleanupRootGroundedAction): TaskNode above defining the subgoal for current MDP\n '
mdp = CleanupL2MDP(init_state=l2_state, env_file=self.env_file, constraints=grounded_action.goal_constraints, ap_maps=grounded_action.ap_maps)
return self.get_policy(mdp, verbose=self.verbose, max_iterations=50, horizon=50)
|
def generate_policy(self, l2_state, grounded_action):
'\n Args:\n l1_state (CleanupL1State): generate policy in l1 domain starting from l1_state\n grounded_action (CleanupRootGroundedAction): TaskNode above defining the subgoal for current MDP\n '
mdp = CleanupL2MDP(init_state=l2_state, env_file=self.env_file, constraints=grounded_action.goal_constraints, ap_maps=grounded_action.ap_maps)
return self.get_policy(mdp, verbose=self.verbose, max_iterations=50, horizon=50)<|docstring|>Args:
l1_state (CleanupL1State): generate policy in l1 domain starting from l1_state
grounded_action (CleanupRootGroundedAction): TaskNode above defining the subgoal for current MDP<|endoftext|>
|
dab992767574df2be86ef1dcccafc670fa2d39272fb7c953515be161d41a3a97
|
def __init__(self, l0MDP, state_mapper, verbose=False, env_file=[], constraints={}, ap_maps={}):
'\n Args:\n l0MDP (FourRoomMDP): lower domain\n state_mapper (AbstractGridWorldL1StateMapper): to map l0 states to l1 domain\n verbose (bool): debug mode\n '
self.domain = l0MDP
self.verbose = verbose
self.state_mapper = state_mapper
self.env_file = env_file
self.constraints = constraints
self.ap_maps = ap_maps
|
Args:
l0MDP (FourRoomMDP): lower domain
state_mapper (AbstractGridWorldL1StateMapper): to map l0 states to l1 domain
verbose (bool): debug mode
|
simple_rl/apmdp/AP_MDP/cleanup/AbstractCleanupPolicyGeneratorClass.py
|
__init__
|
yoonseon-oh/simple_rl
| 2
|
python
|
def __init__(self, l0MDP, state_mapper, verbose=False, env_file=[], constraints={}, ap_maps={}):
'\n Args:\n l0MDP (FourRoomMDP): lower domain\n state_mapper (AbstractGridWorldL1StateMapper): to map l0 states to l1 domain\n verbose (bool): debug mode\n '
self.domain = l0MDP
self.verbose = verbose
self.state_mapper = state_mapper
self.env_file = env_file
self.constraints = constraints
self.ap_maps = ap_maps
|
def __init__(self, l0MDP, state_mapper, verbose=False, env_file=[], constraints={}, ap_maps={}):
'\n Args:\n l0MDP (FourRoomMDP): lower domain\n state_mapper (AbstractGridWorldL1StateMapper): to map l0 states to l1 domain\n verbose (bool): debug mode\n '
self.domain = l0MDP
self.verbose = verbose
self.state_mapper = state_mapper
self.env_file = env_file
self.constraints = constraints
self.ap_maps = ap_maps<|docstring|>Args:
l0MDP (FourRoomMDP): lower domain
state_mapper (AbstractGridWorldL1StateMapper): to map l0 states to l1 domain
verbose (bool): debug mode<|endoftext|>
|
3e52f5507edbf99a85ed2feb3539b29b2a62e3c042296107c00211ef8d9ae30e
|
def generate_policy(self, l1_state, grounded_action):
'\n Args:\n l1_state (FourRoomL1State): generate policy in l1 domain starting from l1_state\n grounded_action (FourRoomRootGroundedAction): TaskNode above defining the subgoal for current MDP\n '
mdp = CleanupL1MDP(l1_state, env_file=self.env_file, constraints=grounded_action.goal_constraints, ap_maps=grounded_action.ap_maps)
return self.get_policy(mdp, verbose=self.verbose, max_iterations=50, horizon=50)
|
Args:
l1_state (FourRoomL1State): generate policy in l1 domain starting from l1_state
grounded_action (FourRoomRootGroundedAction): TaskNode above defining the subgoal for current MDP
|
simple_rl/apmdp/AP_MDP/cleanup/AbstractCleanupPolicyGeneratorClass.py
|
generate_policy
|
yoonseon-oh/simple_rl
| 2
|
python
|
def generate_policy(self, l1_state, grounded_action):
'\n Args:\n l1_state (FourRoomL1State): generate policy in l1 domain starting from l1_state\n grounded_action (FourRoomRootGroundedAction): TaskNode above defining the subgoal for current MDP\n '
mdp = CleanupL1MDP(l1_state, env_file=self.env_file, constraints=grounded_action.goal_constraints, ap_maps=grounded_action.ap_maps)
return self.get_policy(mdp, verbose=self.verbose, max_iterations=50, horizon=50)
|
def generate_policy(self, l1_state, grounded_action):
'\n Args:\n l1_state (FourRoomL1State): generate policy in l1 domain starting from l1_state\n grounded_action (FourRoomRootGroundedAction): TaskNode above defining the subgoal for current MDP\n '
mdp = CleanupL1MDP(l1_state, env_file=self.env_file, constraints=grounded_action.goal_constraints, ap_maps=grounded_action.ap_maps)
return self.get_policy(mdp, verbose=self.verbose, max_iterations=50, horizon=50)<|docstring|>Args:
l1_state (FourRoomL1State): generate policy in l1 domain starting from l1_state
grounded_action (FourRoomRootGroundedAction): TaskNode above defining the subgoal for current MDP<|endoftext|>
|
bd25276de2c46fe75fb831fd7c01802b90cd76e977c00d846c6f2a74bf6ab399
|
def generate_policy(self, state, grounded_task):
'\n Args:\n state (): plan in L0 starting from state\n grounded_task (FourRoomL1GroundedAction): L1 TaskNode defining L0 subgoal\n '
mdp = CleanupQMDP(init_state=state, env_file=self.env_file, constraints=grounded_task.goal_constraints, ap_maps=grounded_task.ap_maps)
return self.get_policy(mdp, verbose=self.verbose, max_iterations=50, horizon=100)
|
Args:
state (): plan in L0 starting from state
grounded_task (FourRoomL1GroundedAction): L1 TaskNode defining L0 subgoal
|
simple_rl/apmdp/AP_MDP/cleanup/AbstractCleanupPolicyGeneratorClass.py
|
generate_policy
|
yoonseon-oh/simple_rl
| 2
|
python
|
def generate_policy(self, state, grounded_task):
'\n Args:\n state (): plan in L0 starting from state\n grounded_task (FourRoomL1GroundedAction): L1 TaskNode defining L0 subgoal\n '
mdp = CleanupQMDP(init_state=state, env_file=self.env_file, constraints=grounded_task.goal_constraints, ap_maps=grounded_task.ap_maps)
return self.get_policy(mdp, verbose=self.verbose, max_iterations=50, horizon=100)
|
def generate_policy(self, state, grounded_task):
'\n Args:\n state (): plan in L0 starting from state\n grounded_task (FourRoomL1GroundedAction): L1 TaskNode defining L0 subgoal\n '
mdp = CleanupQMDP(init_state=state, env_file=self.env_file, constraints=grounded_task.goal_constraints, ap_maps=grounded_task.ap_maps)
return self.get_policy(mdp, verbose=self.verbose, max_iterations=50, horizon=100)<|docstring|>Args:
state (): plan in L0 starting from state
grounded_task (FourRoomL1GroundedAction): L1 TaskNode defining L0 subgoal<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.