signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def move(self, x, y): | self.x = x<EOL>self.y = y<EOL> | Move Rectangle to x,y coordinates
Arguments:
x (int, float): X coordinate
y (int, float): Y coordinate | f424:c4:m15 |
def contains(self, rect): | return (rect.y >= self.y andrect.x >= self.x andrect.y+rect.height <= self.y+self.height andrect.x+rect.width <= self.x+self.width)<EOL> | Tests if another rectangle is contained by this one
Arguments:
rect (Rectangle): The other rectangle
Returns:
bool: True if it is container, False otherwise | f424:c4:m16 |
def intersects(self, rect, edges=False): | <EOL>if (self.bottom > rect.top orself.top < rect.bottom orself.left > rect.right orself.right < rect.left):<EOL><INDENT>return False<EOL><DEDENT>if not edges:<EOL><INDENT>if (self.bottom == rect.top orself.top == rect.bottom orself.left == rect.right orself.right == rect.left):<EOL><INDENT>return False<EOL><DEDENT><DE... | Detect intersections between this rectangle and rect.
Args:
rect (Rectangle): Rectangle to test for intersections.
edges (bool): Accept edge touching rectangles as intersects or not
Returns:
bool: True if the rectangles intersect, False otherwise | f424:c4:m17 |
def intersection(self, rect, edges=False): | if not self.intersects(rect, edges=edges):<EOL><INDENT>return None<EOL><DEDENT>bottom = max(self.bottom, rect.bottom)<EOL>left = max(self.left, rect.left)<EOL>top = min(self.top, rect.top)<EOL>right = min(self.right, rect.right)<EOL>return Rectangle(left, bottom, right-left, top-bottom)<EOL> | Returns the rectangle resulting of the intersection between this and another
rectangle. If the rectangles are only touching by their edges, and the
argument 'edges' is True the rectangle returned will have an area of 0.
Returns None if there is no intersection.
Arguments:
rect (Rectangle): The other rectangle.
... | f424:c4:m18 |
def join(self, other): | if self.contains(other):<EOL><INDENT>return True<EOL><DEDENT>if other.contains(self):<EOL><INDENT>self.x = other.x<EOL>self.y = other.y<EOL>self.width = other.width<EOL>self.height = other.height<EOL>return True<EOL><DEDENT>if not self.intersects(other, edges=True):<EOL><INDENT>return False<EOL><DEDENT>if self.left ==... | Try to join a rectangle to this one, if the result is also a rectangle
and the operation is successful and this rectangle is modified to the union.
Arguments:
other (Rectangle): Rectangle to join
Returns:
bool: True when successfully joined, False otherwise | f424:c4:m19 |
def __init__(self, width, height, rot=True, merge=True, *args, **kwargs): | self._merge = merge<EOL>super(Guillotine, self).__init__(width, height, rot, *args, **kwargs)<EOL> | Arguments:
width (int, float):
height (int, float):
merge (bool): Optional keyword argument | f425:c0:m0 |
def _add_section(self, section): | section.rid = <NUM_LIT:0> <EOL>plen = <NUM_LIT:0><EOL>while self._merge and self._sections and plen != len(self._sections):<EOL><INDENT>plen = len(self._sections)<EOL>self._sections = [s for s in self._sections if not section.join(s)]<EOL><DEDENT>self._sections.append(section)<EOL> | Adds a new section to the free section list, but before that and if
section merge is enabled, tries to join the rectangle with all existing
sections, if successful the resulting section is again merged with the
remaining sections until the operation fails. The result is then
appended... | f425:c0:m1 |
def _split_horizontal(self, section, width, height): | <EOL>if height < section.height:<EOL><INDENT>self._add_section(Rectangle(section.x, section.y+height,<EOL>section.width, section.height-height))<EOL><DEDENT>if width < section.width:<EOL><INDENT>self._add_section(Rectangle(section.x+width, section.y,<EOL>section.width-width, height))<EOL><DEDENT> | For an horizontal split the rectangle is placed in the lower
left corner of the section (section's xy coordinates), the top
most side of the rectangle and its horizontal continuation,
marks the line of division for the split.
+-----------------+
| |
| ... | f425:c0:m2 |
def _split_vertical(self, section, width, height): | <EOL>if height < section.height:<EOL><INDENT>self._add_section(Rectangle(section.x, section.y+height,<EOL>width, section.height-height))<EOL><DEDENT>if width < section.width:<EOL><INDENT>self._add_section(Rectangle(section.x+width, section.y,<EOL>section.width-width, section.height))<EOL><DEDENT> | For a vertical split the rectangle is placed in the lower
left corner of the section (section's xy coordinates), the
right most side of the rectangle and its vertical continuation,
marks the line of division for the split.
+-------+---------+
| | |
| |... | f425:c0:m3 |
def _split(self, section, width, height): | raise NotImplementedError<EOL> | Selects the best split for a section, given a rectangle of dimmensions
width and height, then calls _split_vertical or _split_horizontal,
to do the dirty work.
Arguments:
section (Rectangle): Section to split
width (int, float): Rectangle width
height (int, float): Rectangle height | f425:c0:m4 |
def _section_fitness(self, section, width, height): | raise NotImplementedError<EOL> | The subclass for each one of the Guillotine selection methods,
BAF, BLSF.... will override this method, this is here only
to asure a valid value return if the worst happens. | f425:c0:m5 |
def add_rect(self, width, height, rid=None): | assert(width > <NUM_LIT:0> and height ><NUM_LIT:0>)<EOL>section, rotated = self._select_fittest_section(width, height)<EOL>if not section:<EOL><INDENT>return None<EOL><DEDENT>if rotated:<EOL><INDENT>width, height = height, width<EOL><DEDENT>self._sections.remove(section)<EOL>self._split(section, width, height)<EOL>rect... | Add rectangle of widthxheight dimensions.
Arguments:
width (int, float): Rectangle width
height (int, float): Rectangle height
rid: Optional rectangle user id
Returns:
Rectangle: Rectangle with placemente coordinates
None: If the rectangle couldn be placed. | f425:c0:m7 |
def fitness(self, width, height): | assert(width > <NUM_LIT:0> and height > <NUM_LIT:0>)<EOL>section, rotated = self._select_fittest_section(width, height)<EOL>if not section:<EOL><INDENT>return None<EOL><DEDENT>if rotated:<EOL><INDENT>return self._section_fitness(section, height, width)<EOL><DEDENT>else:<EOL><INDENT>return self._section_fitness(section,... | In guillotine algorithm case, returns the min of the fitness of all
free sections, for the given dimension, both normal and rotated
(if rotation enabled.) | f425:c0:m8 |
def __init__(self, width, height, rot=True, bid=None, *args, **kwargs): | self.width = width<EOL>self.height = height<EOL>self.rot = rot<EOL>self.rectangles = []<EOL>self.bid = bid<EOL>self._surface = Rectangle(<NUM_LIT:0>, <NUM_LIT:0>, width, height)<EOL>self.reset()<EOL> | Initialize packing algorithm
Arguments:
width (int, float): Packing surface width
height (int, float): Packing surface height
rot (bool): Rectangle rotation enabled or disabled
bid (string|int|...): Packing surface identification | f426:c0:m0 |
def _fits_surface(self, width, height): | assert(width > <NUM_LIT:0> and height > <NUM_LIT:0>)<EOL>if self.rot and (width > self.width or height > self.height):<EOL><INDENT>width, height = height, width<EOL><DEDENT>if width > self.width or height > self.height:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return True<EOL><DEDENT> | Test surface is big enough to place a rectangle
Arguments:
width (int, float): Rectangle width
height (int, float): Rectangle height
Returns:
boolean: True if it could be placed, False otherwise | f426:c0:m3 |
def __getitem__(self, key): | return self.rectangles[key]<EOL> | Return rectangle in selected position. | f426:c0:m4 |
def used_area(self): | return sum(r.area() for r in self)<EOL> | Total area of rectangles placed
Returns:
int, float: Area | f426:c0:m5 |
def fitness(self, width, height, rot = False): | raise NotImplementedError<EOL> | Metric used to rate how much space is wasted if a rectangle is placed.
Returns a value greater or equal to zero, the smaller the value the more
'fit' is the rectangle. If the rectangle can't be placed, returns None.
Arguments:
width (int, float): Rectangle width
height (int, float): Rectangle height
rot (... | f426:c0:m6 |
def add_rect(self, width, height, rid=None): | raise NotImplementedError<EOL> | Add rectangle of widthxheight dimensions.
Arguments:
width (int, float): Rectangle width
height (int, float): Rectangle height
rid: Optional rectangle user id
Returns:
Rectangle: Rectangle with placemente coordinates
None: If the rectangle couldn be placed. | f426:c0:m7 |
def rect_list(self): | rectangle_list = []<EOL>for r in self:<EOL><INDENT>rectangle_list.append((r.x, r.y, r.width, r.height, r.rid))<EOL><DEDENT>return rectangle_list<EOL> | Returns a list with all rectangles placed into the surface.
Returns:
List: Format [(rid, x, y, width, height), ...] | f426:c0:m8 |
def validate_packing(self): | surface = Rectangle(<NUM_LIT:0>, <NUM_LIT:0>, self.width, self.height)<EOL>for r in self:<EOL><INDENT>if not surface.contains(r):<EOL><INDENT>raise Exception("<STR_LIT>")<EOL><DEDENT><DEDENT>rectangles = [r for r in self]<EOL>if len(rectangles) <= <NUM_LIT:1>:<EOL><INDENT>return<EOL><DEDENT>for r1 in range(<NUM_LIT:0>,... | Check for collisions between rectangles, also check all are placed
inside surface. | f426:c0:m9 |
def __init__(self, rectangles=[], max_width=None, max_height=None, rotation=True): | <EOL>self._max_width = max_width<EOL>self._max_height = max_height<EOL>self._rotation = rotation<EOL>self._pack_algo = SkylineBlWm<EOL>self._rectangles = []<EOL>for r in rectangles:<EOL><INDENT>self.add_rect(*r)<EOL><DEDENT> | Arguments:
rectangles (list): Rectangle to be enveloped
[(width1, height1), (width2, height2), ...]
max_width (number|None): Enveloping rectangle max allowed width.
max_height (number|None): Enveloping rectangle max allowed height.
rotation (boolean): Enable/Disable rectangle rotation. | f428:c0:m0 |
def _container_candidates(self): | if not self._rectangles:<EOL><INDENT>return []<EOL><DEDENT>if self._rotation:<EOL><INDENT>sides = sorted(side for rect in self._rectangles for side in rect)<EOL>max_height = sum(max(r[<NUM_LIT:0>], r[<NUM_LIT:1>]) for r in self._rectangles)<EOL>min_width = max(min(r[<NUM_LIT:0>], r[<NUM_LIT:1>]) for r in self._rectangl... | Generate container candidate list
Returns:
tuple list: [(width1, height1), (width2, height2), ...] | f428:c0:m1 |
def _refine_candidate(self, width, height): | packer = newPacker(PackingMode.Offline, PackingBin.BFF, <EOL>pack_algo=self._pack_algo, sort_algo=SORT_LSIDE,<EOL>rotation=self._rotation)<EOL>packer.add_bin(width, height)<EOL>for r in self._rectangles:<EOL><INDENT>packer.add_rect(*r)<EOL><DEDENT>packer.pack()<EOL>if len(packer[<NUM_LIT:0>]) != len(self._rectangles):<... | Use bottom-left packing algorithm to find a lower height for the
container.
Arguments:
width
height
Returns:
tuple (width, height, PackingAlgorithm): | f428:c0:m2 |
def add_rect(self, width, height): | self._rectangles.append((width, height))<EOL> | Add anoter rectangle to be enclosed
Arguments:
width (number): Rectangle width
height (number): Rectangle height | f428:c0:m4 |
def add_waste(self, x, y, width, height): | self._add_section(Rectangle(x, y, width, height))<EOL> | Add new waste section | f429:c0:m1 |
def sub_dfs_by_size(df, size): | for i in range(<NUM_LIT:0>, len(df), size):<EOL><INDENT>yield (df.iloc[i:i + size])<EOL><DEDENT> | Get a generator yielding consecutive sub-dataframes of the given size.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
size : int
The size of each sub-dataframe.
Returns
-------
generator
A generator yielding consecutive sub-... | f432:m0 |
def sub_dfs_by_num(df, num): | size = len(df) / float(num)<EOL>for i in range(num):<EOL><INDENT>yield df.iloc[int(round(size * i)): int(round(size * (i + <NUM_LIT:1>)))]<EOL><DEDENT> | Get a generator yielding num consecutive sub-dataframes of the given df.
Arguments
---------
df : pandas.DataFrame
The dataframe for which to get sub-dataframes.
num : int
The number of sub-dataframe to divide the given dataframe into.
Returns
-------
generator
A ge... | f432:m1 |
@classmethod<EOL><INDENT>def by_name(cls, name):<DEDENT> | return cls.__NAME_TO_OBJ__[name]<EOL> | Returns a SerializationFormat object by the format name.
Parameters
----------
name : str
The name of the serialization format. E.g. 'csv' or 'feather'.
Returns
-------
SerializationFormat
An object representing the given serialization format.
... | f435:c0:m2 |
def get_keywords(): | <EOL>git_refnames = "<STR_LIT>"<EOL>git_full = "<STR_LIT>"<EOL>git_date = "<STR_LIT>"<EOL>keywords = {"<STR_LIT>": git_refnames, "<STR_LIT>": git_full, "<STR_LIT:date>": git_date}<EOL>return keywords<EOL> | Get the keywords needed to look up the version information. | f436:m0 |
def get_config(): | <EOL>cfg = VersioneerConfig()<EOL>cfg.VCS = "<STR_LIT>"<EOL>cfg.style = "<STR_LIT>"<EOL>cfg.tag_prefix = "<STR_LIT:v>"<EOL>cfg.parentdir_prefix = "<STR_LIT>"<EOL>cfg.versionfile_source = "<STR_LIT>"<EOL>cfg.verbose = False<EOL>return cfg<EOL> | Create, populate and return the VersioneerConfig() object. | f436:m1 |
def register_vcs_handler(vcs, method): | def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL> | Decorator to mark a method as the handler for a particular VCS. | f436:m2 |
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,<EOL>env=None): | assert isinstance(commands, list)<EOL>p = None<EOL>for c in commands:<EOL><INDENT>try:<EOL><INDENT>dispcmd = str([c] + args)<EOL>p = subprocess.Popen([c] + args, cwd=cwd, env=env,<EOL>stdout=subprocess.PIPE,<EOL>stderr=(subprocess.PIPE if hide_stderr<EOL>else None))<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><I... | Call the given command(s). | f436:m3 |
def versions_from_parentdir(parentdir_prefix, root, verbose): | rootdirs = []<EOL>for i in range(<NUM_LIT:3>):<EOL><INDENT>dirname = os.path.basename(root)<EOL>if dirname.startswith(parentdir_prefix):<EOL><INDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None, "<STR_LIT:date>": None}<EOL><DEDENT>e... | Try to determine the version from the parent directory name.
Source tarballs conventionally unpack into a directory that includes both
the project name and a version string. We will also support searching up
two directory levels for an appropriately named parent directory | f436:m4 |
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_get_keywords(versionfile_abs): | <EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().sta... | Extract version information from the given file. | f436:m5 |
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose): | if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>date = keywords.get("<STR_LIT:date>")<EOL>if date is not None:<EOL><INDENT>date = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL><DEDENT>refnames = keywords["<STR_LIT... | Get version information from git keywords. | f436:m6 |
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): | GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root,<EOL>hide_stderr=True)<EOL>if rc != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotTh... | Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside a checked out source tree. | f436:m7 |
def plus_or_dot(pieces): | if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL> | Return a + if we don't already have one, else return a . | f436:m8 |
def render_pep440(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><... | Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
Exceptions:
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] | f436:m9 |
def render_pep440_pre(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL> | TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE | f436:m10 |
def render_pep440_post(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces... | TAG[.postDISTANCE[.dev0]+gHEX] .
The ".dev0" means dirty. Note that .dev0 sorts backwards
(a dirty tree will appear "older" than the corresponding clean one),
but you shouldn't be releasing software with -dirty anyways.
Exceptions:
1: no tags. 0.postDISTANCE[.dev0] | f436:m11 |
def render_pep440_old(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<... | TAG[.postDISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.postDISTANCE[.dev0] | f436:m12 |
def render_git_describe(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL... | TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix) | f436:m13 |
def render_git_describe_long(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL> | TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix) | f436:m14 |
def render(pieces, style): | if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"],<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>" <E... | Render the given version pieces into the requested style. | f436:m15 |
def get_versions(): | <EOL>cfg = get_config()<EOL>verbose = cfg.verbose<EOL>try:<EOL><INDENT>return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,<EOL>verbose)<EOL><DEDENT>except NotThisMethod:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>root = os.path.realpath(__file__)<EOL>for i in cfg.versionfile_source.split('<STR_LIT:/>')... | Get version information or return default if unable to do so. | f436:m16 |
def x_y_by_col_lbl(df, y_col_lbl): | x_cols = [col for col in df.columns if col != y_col_lbl]<EOL>return df[x_cols], df[y_col_lbl]<EOL> | Returns an X dataframe and a y series by the given column name.
Parameters
----------
df : pandas.DataFrame
The dataframe to split.
y_col_lbl : object
The label of the y column.
Returns
-------
X, y : pandas.DataFrame, pandas.Series
A dataframe made up of all column... | f438:m0 |
def x_y_by_col_lbl_inplace(df, y_col_lbl): | y = df[y_col_lbl]<EOL>df.drop(<EOL>labels=y_col_lbl,<EOL>axis=<NUM_LIT:1>,<EOL>inplace=True,<EOL>)<EOL>return df, y<EOL> | Breaks the given dataframe into an X frame and a y series by the given
column name.
The original frame is returned, without the y series column, as the X
frame, so no new dataframes are created.
Parameters
----------
df : pandas.DataFrame
The dataframe to split.
y_col_lbl : object... | f438:m1 |
def or_by_masks(df, masks): | if len(masks) < <NUM_LIT:1>:<EOL><INDENT>return df<EOL><DEDENT>if len(masks) == <NUM_LIT:1>:<EOL><INDENT>return df[masks[<NUM_LIT:0>]]<EOL><DEDENT>overall_mask = masks[<NUM_LIT:0>] | masks[<NUM_LIT:1>]<EOL>for mask in masks[<NUM_LIT:2>:]:<EOL><INDENT>overall_mask = overall_mask | mask<EOL><DEDENT>return df[overall_mask... | Returns a sub-dataframe by the logical or over the given masks.
Parameters
----------
df : pandas.DataFrame
The dataframe to take a subframe of.
masks : list
A list of pandas.Series of dtype bool, indexed identically to the given
dataframe.
Returns
-------
pandas.Da... | f438:m2 |
def or_by_mask_conditions(df, mask_conditions): | return or_by_masks(df, [cond(df) for cond in mask_conditions])<EOL> | Returns a sub-dataframe by the logical-or over given mask conditions,
Parameters
----------
df : pandas.DataFrame
The dataframe to take a subframe of.
mask_conditions : list
A list of functions that, when applied to a dataframe, produce each a
pandas.Series of dtype bool, indexe... | f438:m3 |
def df_string(df, percentage_columns=(), format_map=None, **kwargs): | formatters_map = {}<EOL>for col, dtype in df.dtypes.iteritems():<EOL><INDENT>if col in percentage_columns:<EOL><INDENT>formatters_map[col] = '<STR_LIT>'.format<EOL><DEDENT>elif dtype == '<STR_LIT>':<EOL><INDENT>formatters_map[col] = '<STR_LIT>'.format<EOL><DEDENT><DEDENT>if format_map:<EOL><INDENT>for key in format_map... | Return a nicely formatted string for the given dataframe.
Arguments
---------
df : pandas.DataFrame
A dataframe object.
percentage_columns : iterable
A list of cloumn names to be displayed with a percentage sign.
Returns
-------
str
A nicely formatted string for the... | f440:m0 |
def big_dataframe_setup(): | pd.set_option('<STR_LIT>', sys.maxsize)<EOL>pd.set_option('<STR_LIT>', sys.maxsize)<EOL>pd.set_option('<STR_LIT>', sys.maxsize)<EOL>pd.set_option('<STR_LIT>', sys.maxsize)<EOL>pd.set_option('<STR_LIT>', '<STR_LIT>')<EOL>pd.set_option('<STR_LIT>', sys.maxsize)<EOL>pd.set_option('<STR_LIT>', sys.maxsize)<EOL>pd.set_optio... | Sets pandas to display really big data frames. | f440:m1 |
def df_to_html(df, percentage_columns=None): | big_dataframe_setup()<EOL>try:<EOL><INDENT>res = '<STR_LIT>'.format(df.name)<EOL><DEDENT>except AttributeError:<EOL><INDENT>res = '<STR_LIT>'<EOL><DEDENT>df.style.set_properties(**{'<STR_LIT>': '<STR_LIT>'})<EOL>res += df.to_html(formatters=_formatters_dict(<EOL>input_df=df,<EOL>percentage_columns=percentage_columns<EO... | Return a nicely formatted HTML code string for the given dataframe.
Arguments
---------
df : pandas.DataFrame
A dataframe object.
percentage_columns : iterable
A list of cloumn names to be displayed with a percentage sign.
Returns
-------
str
A nicely formatted stri... | f440:m4 |
def get_root(): | root = os.path.realpath(os.path.abspath(os.getcwd()))<EOL>setup_py = os.path.join(root, "<STR_LIT>")<EOL>versioneer_py = os.path.join(root, "<STR_LIT>")<EOL>if not (os.path.exists(setup_py) or os.path.exists(versioneer_py)):<EOL><INDENT>root = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[<NUM_LIT:0>])))<EO... | Get the project root directory.
We require that all commands are run from the project root, i.e. the
directory that contains setup.py, setup.cfg, and versioneer.py . | f443:m0 |
def get_config_from_root(root): | <EOL>setup_cfg = os.path.join(root, "<STR_LIT>")<EOL>parser = configparser.SafeConfigParser()<EOL>with open(setup_cfg, "<STR_LIT:r>") as f:<EOL><INDENT>parser.readfp(f)<EOL><DEDENT>VCS = parser.get("<STR_LIT>", "<STR_LIT>") <EOL>def get(parser, name):<EOL><INDENT>if parser.has_option("<STR_LIT>", name):<EOL><INDENT>re... | Read the project setup.cfg file to determine Versioneer config. | f443:m1 |
def register_vcs_handler(vcs, method): | def decorate(f):<EOL><INDENT>"""<STR_LIT>"""<EOL>if vcs not in HANDLERS:<EOL><INDENT>HANDLERS[vcs] = {}<EOL><DEDENT>HANDLERS[vcs][method] = f<EOL>return f<EOL><DEDENT>return decorate<EOL> | Decorator to mark a method as the handler for a particular VCS. | f443:m2 |
def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False,<EOL>env=None): | assert isinstance(commands, list)<EOL>p = None<EOL>for c in commands:<EOL><INDENT>try:<EOL><INDENT>dispcmd = str([c] + args)<EOL>p = subprocess.Popen([c] + args, cwd=cwd, env=env,<EOL>stdout=subprocess.PIPE,<EOL>stderr=(subprocess.PIPE if hide_stderr<EOL>else None))<EOL>break<EOL><DEDENT>except EnvironmentError:<EOL><I... | Call the given command(s). | f443:m3 |
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_get_keywords(versionfile_abs): | <EOL>keywords = {}<EOL>try:<EOL><INDENT>f = open(versionfile_abs, "<STR_LIT:r>")<EOL>for line in f.readlines():<EOL><INDENT>if line.strip().startswith("<STR_LIT>"):<EOL><INDENT>mo = re.search(r'<STR_LIT>', line)<EOL>if mo:<EOL><INDENT>keywords["<STR_LIT>"] = mo.group(<NUM_LIT:1>)<EOL><DEDENT><DEDENT>if line.strip().sta... | Extract version information from the given file. | f443:m4 |
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_versions_from_keywords(keywords, tag_prefix, verbose): | if not keywords:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>date = keywords.get("<STR_LIT:date>")<EOL>if date is not None:<EOL><INDENT>date = date.strip().replace("<STR_LIT:U+0020>", "<STR_LIT:T>", <NUM_LIT:1>).replace("<STR_LIT:U+0020>", "<STR_LIT>", <NUM_LIT:1>)<EOL><DEDENT>refnames = keywords["<STR_LIT... | Get version information from git keywords. | f443:m5 |
@register_vcs_handler("<STR_LIT>", "<STR_LIT>")<EOL>def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command): | GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>out, rc = run_command(GITS, ["<STR_LIT>", "<STR_LIT>"], cwd=root,<EOL>hide_stderr=True)<EOL>if rc != <NUM_LIT:0>:<EOL><INDENT>if verbose:<EOL><INDENT>print("<STR_LIT>" % root)<EOL><DEDENT>raise NotTh... | Get version from 'git describe' in the root of the source tree.
This only gets called if the git-archive 'subst' keywords were *not*
expanded, and _version.py hasn't already been rewritten with a short
version string, meaning we're inside a checked out source tree. | f443:m6 |
def do_vcs_install(manifest_in, versionfile_source, ipy): | GITS = ["<STR_LIT>"]<EOL>if sys.platform == "<STR_LIT:win32>":<EOL><INDENT>GITS = ["<STR_LIT>", "<STR_LIT>"]<EOL><DEDENT>files = [manifest_in, versionfile_source]<EOL>if ipy:<EOL><INDENT>files.append(ipy)<EOL><DEDENT>try:<EOL><INDENT>me = __file__<EOL>if me.endswith("<STR_LIT>") or me.endswith("<STR_LIT>"):<EOL><INDENT... | Git-specific installation logic for Versioneer.
For Git, this means creating/changing .gitattributes to mark _version.py
for export-subst keyword substitution. | f443:m7 |
def versions_from_parentdir(parentdir_prefix, root, verbose): | rootdirs = []<EOL>for i in range(<NUM_LIT:3>):<EOL><INDENT>dirname = os.path.basename(root)<EOL>if dirname.startswith(parentdir_prefix):<EOL><INDENT>return {"<STR_LIT:version>": dirname[len(parentdir_prefix):],<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT>": False, "<STR_LIT:error>": None, "<STR_LIT:date>": None}<EOL><DEDENT>e... | Try to determine the version from the parent directory name.
Source tarballs conventionally unpack into a directory that includes both
the project name and a version string. We will also support searching up
two directory levels for an appropriately named parent directory | f443:m8 |
def versions_from_file(filename): | try:<EOL><INDENT>with open(filename) as f:<EOL><INDENT>contents = f.read()<EOL><DEDENT><DEDENT>except EnvironmentError:<EOL><INDENT>raise NotThisMethod("<STR_LIT>")<EOL><DEDENT>mo = re.search(r"<STR_LIT>",<EOL>contents, re.M | re.S)<EOL>if not mo:<EOL><INDENT>mo = re.search(r"<STR_LIT>",<EOL>contents, re.M | re.S)<EOL>... | Try to determine the version from _version.py if present. | f443:m9 |
def write_to_version_file(filename, versions): | os.unlink(filename)<EOL>contents = json.dumps(versions, sort_keys=True,<EOL>indent=<NUM_LIT:1>, separators=("<STR_LIT:U+002C>", "<STR_LIT>"))<EOL>with open(filename, "<STR_LIT:w>") as f:<EOL><INDENT>f.write(SHORT_VERSION_PY % contents)<EOL><DEDENT>print("<STR_LIT>" % (filename, versions["<STR_LIT:version>"]))<EOL> | Write the given version number to the given _version.py file. | f443:m10 |
def plus_or_dot(pieces): | if "<STR_LIT:+>" in pieces.get("<STR_LIT>", "<STR_LIT>"):<EOL><INDENT>return "<STR_LIT:.>"<EOL><DEDENT>return "<STR_LIT:+>"<EOL> | Return a + if we don't already have one, else return a . | f443:m11 |
def render_pep440(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><... | Build up version string, with post-release "local version identifier".
Our goal: TAG[+DISTANCE.gHEX[.dirty]] . Note that if you
get a tagged build and then dirty it, you'll get TAG+0.gHEX.dirty
Exceptions:
1: no tags. git_describe was just HEX. 0+untagged.DISTANCE.gHEX[.dirty] | f443:m12 |
def render_pep440_pre(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<STR_LIT>"]<EOL><DEDENT>return rendered<EOL> | TAG[.post.devDISTANCE] -- No -dirty.
Exceptions:
1: no tags. 0.post.devDISTANCE | f443:m13 |
def render_pep440_post(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>rendered += plus_or_dot(pieces)<EOL>rendered += "<STR_LIT>" % pieces... | TAG[.postDISTANCE[.dev0]+gHEX] .
The ".dev0" means dirty. Note that .dev0 sorts backwards
(a dirty tree will appear "older" than the corresponding clean one),
but you shouldn't be releasing software with -dirty anyways.
Exceptions:
1: no tags. 0.postDISTANCE[.dev0] | f443:m14 |
def render_pep440_old(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"] or pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>rendered = "<STR_LIT>" % pieces["<... | TAG[.postDISTANCE[.dev0]] .
The ".dev0" means dirty.
Eexceptions:
1: no tags. 0.postDISTANCE[.dev0] | f443:m15 |
def render_git_describe(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL... | TAG[-DISTANCE-gHEX][-dirty].
Like 'git describe --tags --dirty --always'.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix) | f443:m16 |
def render_git_describe_long(pieces): | if pieces["<STR_LIT>"]:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL>rendered += "<STR_LIT>" % (pieces["<STR_LIT>"], pieces["<STR_LIT>"])<EOL><DEDENT>else:<EOL><INDENT>rendered = pieces["<STR_LIT>"]<EOL><DEDENT>if pieces["<STR_LIT>"]:<EOL><INDENT>rendered += "<STR_LIT>"<EOL><DEDENT>return rendered<EOL> | TAG-DISTANCE-gHEX[-dirty].
Like 'git describe --tags --dirty --always -long'.
The distance/hash is unconditional.
Exceptions:
1: no tags. HEX[-dirty] (note: no 'g' prefix) | f443:m17 |
def render(pieces, style): | if pieces["<STR_LIT:error>"]:<EOL><INDENT>return {"<STR_LIT:version>": "<STR_LIT>",<EOL>"<STR_LIT>": pieces.get("<STR_LIT>"),<EOL>"<STR_LIT>": None,<EOL>"<STR_LIT:error>": pieces["<STR_LIT:error>"],<EOL>"<STR_LIT:date>": None}<EOL><DEDENT>if not style or style == "<STR_LIT:default>":<EOL><INDENT>style = "<STR_LIT>" <E... | Render the given version pieces into the requested style. | f443:m18 |
def get_versions(verbose=False): | if "<STR_LIT>" in sys.modules:<EOL><INDENT>del sys.modules["<STR_LIT>"]<EOL><DEDENT>root = get_root()<EOL>cfg = get_config_from_root(root)<EOL>assert cfg.VCS is not None, "<STR_LIT>"<EOL>handlers = HANDLERS.get(cfg.VCS)<EOL>assert handlers, "<STR_LIT>" % cfg.VCS<EOL>verbose = verbose or cfg.verbose<EOL>assert cfg.versi... | Get the project version from whatever source is available.
Returns dict with two keys: 'version' and 'full'. | f443:m19 |
def get_version(): | return get_versions()["<STR_LIT:version>"]<EOL> | Get the short version string for this project. | f443:m20 |
def get_cmdclass(): | if "<STR_LIT>" in sys.modules:<EOL><INDENT>del sys.modules["<STR_LIT>"]<EOL><DEDENT>cmds = {}<EOL>from distutils.core import Command<EOL>class cmd_version(Command):<EOL><INDENT>description = "<STR_LIT>"<EOL>user_options = []<EOL>boolean_options = []<EOL>def initialize_options(self):<EOL><INDENT>pass<EOL><DEDENT>def fin... | Get the custom setuptools/distutils subclasses used by Versioneer. | f443:m21 |
def do_setup(): | root = get_root()<EOL>try:<EOL><INDENT>cfg = get_config_from_root(root)<EOL><DEDENT>except (EnvironmentError, configparser.NoSectionError,<EOL>configparser.NoOptionError) as e:<EOL><INDENT>if isinstance(e, (EnvironmentError, configparser.NoSectionError)):<EOL><INDENT>print("<STR_LIT>",<EOL>file=sys.stderr)<EOL>with ope... | Main VCS-independent setup function for installing Versioneer. | f443:m22 |
def scan_setup_py(): | found = set()<EOL>setters = False<EOL>errors = <NUM_LIT:0><EOL>with open("<STR_LIT>", "<STR_LIT:r>") as f:<EOL><INDENT>for line in f.readlines():<EOL><INDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in line:<EOL><INDENT>found.add("<STR_LIT>")<EOL><DEDENT>if "<STR_LIT>" in li... | Validate the contents of setup.py against Versioneer's expectations. | f443:m23 |
def parse_line(line): | if not line.startswith(b'<STR_LIT>'):<EOL><INDENT>raise exc.InvalidLine('<STR_LIT>', line)<EOL><DEDENT>if not line.endswith(CRLF):<EOL><INDENT>raise exc.InvalidLine('<STR_LIT>', line)<EOL><DEDENT>parts = line[:-len(CRLF)].split(b'<STR_LIT:U+0020>')<EOL>if len(parts) != <NUM_LIT:6>:<EOL><INDENT>raise exc.InvalidLine('<S... | Parses a byte string like:
PROXY TCP4 192.168.0.1 192.168.0.11 56324 443\r\n
to a `ProxyInfo`. | f445:m1 |
def proxy_authenticate(self, info): | return (info.destination_address, info.destination_port) == self.client_address<EOL> | Authentication hook for parsed proxy information. Defaults to ensuring
destination (i.e. proxy) is the peer.
:param info: Parsed ``ProxyInfo`` instance.
:returns: ``True`` if authenticated, otherwise ``False``. | f445:c0:m0 |
def proxy_protocol(self, error='<STR_LIT>', default=None, limit=None, authenticate=False): | if error not in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if not isinstance(self.request, SocketBuffer):<EOL><INDENT>self.request = SocketBuffer(self.request)<EOL><DEDENT>if default == '<STR_LIT>':<EOL><INDENT>default = ProxyInfo(<EOL>self.client_address[<NUM_LIT:0>], self.client... | Parses, and optionally authenticates, proxy protocol information from
request. Note that ``self.request`` is wrapped by ``SocketBuffer``.
:param error:
How read (``exc.ReadError``) and parse (``exc.ParseError``) errors
are handled. One of:
- "raise" to propagate.
- "unread" to suppress exceptions and u... | f445:c0:m1 |
def touch_model(self, model, **data): | instance, created = model.objects.get_or_create(**data)<EOL>if not created:<EOL><INDENT>if instance.updated < self.import_start_datetime:<EOL><INDENT>instance.save() <EOL><DEDENT><DEDENT>return (instance, created)<EOL> | This method create or look up a model with the given data
it saves the given model if it exists, updating its
updated field | f448:c0:m2 |
@transaction.atomic<EOL><INDENT>def manage_mep(self, mep_json):<DEDENT> | <EOL>responses = representative_pre_import.send(sender=self,<EOL>representative_data=mep_json)<EOL>for receiver, response in responses:<EOL><INDENT>if response is False:<EOL><INDENT>logger.debug(<EOL>'<STR_LIT>', mep_json['<STR_LIT:Name>']['<STR_LIT>'])<EOL>return<EOL><DEDENT><DEDENT>changed = False<EOL>slug = slugify(... | Import a mep as a representative from the json dict fetched from
parltrack | f448:c1:m2 |
def _get_path(dict_, path): | cur = dict_<EOL>for part in path.split('<STR_LIT:/>'):<EOL><INDENT>cur = cur[part]<EOL><DEDENT>return cur<EOL> | Get value at specific path in dictionary. Path is specified by slash-
separated string, eg _get_path(foo, 'bar/baz') returns foo['bar']['baz'] | f451:m3 |
def ensure_chambers(): | france = Country.objects.get(name="<STR_LIT>")<EOL>for key in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>variant = FranceDataVariants[key]<EOL>Chamber.objects.get_or_create(name=variant['<STR_LIT>'],<EOL>abbreviation=variant['<STR_LIT>'],<EOL>country=france)<EOL><DEDENT> | Ensures chambers are created | f451:m4 |
def touch_model(self, model, **data): | instance, created = model.objects.get_or_create(**data)<EOL>if not created:<EOL><INDENT>if instance.updated < self.import_start_datetime:<EOL><INDENT>instance.save() <EOL><DEDENT><DEDENT>return (instance, created)<EOL> | This method create or look up a model with the given data
it saves the given model if it exists, updating its
updated field | f451:c0:m1 |
@transaction.atomic<EOL><INDENT>def manage_rep(self, rep_json):<DEDENT> | <EOL>responses = representative_pre_import.send(sender=self,<EOL>representative_data=rep_json)<EOL>for receiver, response in responses:<EOL><INDENT>if response is False:<EOL><INDENT>logger.debug(<EOL>'<STR_LIT>', rep_json['<STR_LIT>'])<EOL>return<EOL><DEDENT><DEDENT>changed = False<EOL>slug = slugify('<STR_LIT>' % (<EO... | Import a rep as a representative from the json dict fetched from
FranceData (which comes from nosdeputes.fr) | f451:c1:m2 |
def add_mandates(self, representative, rep_json): | <EOL>if rep_json.get('<STR_LIT>'):<EOL><INDENT>constituency, _ = Constituency.objects.get_or_create(<EOL>name=rep_json.get('<STR_LIT>'), country=self.france)<EOL>group, _ = self.touch_model(model=Group,<EOL>abbreviation=self.france.code,<EOL>kind='<STR_LIT>',<EOL>name=self.france.name)<EOL>_create_mandate(representativ... | Create mandates from rep data based on variant configuration | f451:c1:m4 |
def update_slugs(apps, schema_editor): | <EOL>Representative = apps.get_model("<STR_LIT>", "<STR_LIT>")<EOL>for rep in Representative.objects.all():<EOL><INDENT>rep.slug = '<STR_LIT>' % (rep.slug, rep.birth_date)<EOL>rep.save()<EOL><DEDENT> | Include birthdate in slugs | f462:m0 |
def create_parl_websites(apps, schema_editor): | <EOL>Representative = apps.get_model("<STR_LIT>", "<STR_LIT>")<EOL>WebSite = apps.get_model("<STR_LIT>", "<STR_LIT>")<EOL>today = datetime.date.today()<EOL>ep_url = '<STR_LIT>'<EOL>qs = Representative.objects.filter(<EOL>models.Q(mandates__end_date__gte=today) |<EOL>models.Q(mandates__end_date__isnull=True),<EOL>mandat... | Prepare for remote_id removal by creating WebSite entities from it. | f462:m1 |
def migrate_constituencies(apps, schema_editor): | Constituency = apps.get_model("<STR_LIT>", "<STR_LIT>")<EOL>for c in Constituency.objects.all():<EOL><INDENT>c.save()<EOL><DEDENT> | Re-save constituencies to recompute fingerprints | f465:m0 |
def update_kinds(apps, schema_editor): | <EOL>Group = apps.get_model("<STR_LIT>", "<STR_LIT>")<EOL>qs = Group.objects.filter(<EOL>models.Q(name__iregex=r'<STR_LIT>') |<EOL>models.Q(name__iregex=r'<STR_LIT>')<EOL>)<EOL>for g in qs:<EOL><INDENT>g.kind = '<STR_LIT>'<EOL>g.save()<EOL><DEDENT> | Downgrade FR special committees to delegations | f466:m0 |
def update_abbreviations(apps, schema_editor): | <EOL>Group = apps.get_model("<STR_LIT>", "<STR_LIT>")<EOL>amap = {<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT>': '<STR_LIT>',<EOL>'<STR_LIT... | Migrate to new FR committee abbreviations | f466:m1 |
def unload_fixture(apps, schema_editor): | MyModel = apps.get_model("<STR_LIT>", "<STR_LIT>")<EOL>MyModel.objects.all().delete()<EOL> | Brutally deleting all entries for this model... | f474:m1 |
def calculate_hash(obj): | hashable_fields = {<EOL>'<STR_LIT>': ['<STR_LIT:name>', '<STR_LIT>', '<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT:name>'],<EOL>'<STR_LIT>': ['<STR_LIT:name>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>'],<EOL>'<STR_LIT>': ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>']<EOL>}<EOL>fingerprint = ... | Computes fingerprint for an object, this code is duplicated from
representatives.models.HashableModel because we don't have access to model
methods in a migration scenario. | f477:m0 |
def get_or_create(cls, **kwargs): | try:<EOL><INDENT>obj = cls.objects.get(**kwargs)<EOL>created = False<EOL><DEDENT>except cls.DoesNotExist:<EOL><INDENT>obj = cls(**kwargs)<EOL>created = True<EOL>calculate_hash(obj)<EOL>obj.save()<EOL><DEDENT>return (obj, created)<EOL> | Implements get_or_create logic for models that inherit from
representatives.models.HashableModel because we don't have access to model
methods in a migration scenario. | f477:m1 |
def request(identifier, namespace='<STR_LIT>', domain='<STR_LIT>', operation=None, output='<STR_LIT>', searchtype=None, **kwargs): | if not identifier:<EOL><INDENT>raise ValueError('<STR_LIT>')<EOL><DEDENT>if isinstance(identifier, int):<EOL><INDENT>identifier = str(identifier)<EOL><DEDENT>if not isinstance(identifier, text_types):<EOL><INDENT>identifier = '<STR_LIT:U+002C>'.join(str(x) for x in identifier)<EOL><DEDENT>kwargs = dict((k, v) for k, v ... | Construct API request from parameters and return the response.
Full specification at http://pubchem.ncbi.nlm.nih.gov/pug_rest/PUG_REST.html | f498:m0 |
def get(identifier, namespace='<STR_LIT>', domain='<STR_LIT>', operation=None, output='<STR_LIT>', searchtype=None, **kwargs): | if (searchtype and searchtype != '<STR_LIT>') or namespace in ['<STR_LIT>']:<EOL><INDENT>response = request(identifier, namespace, domain, None, '<STR_LIT>', searchtype, **kwargs).read()<EOL>status = json.loads(response.decode())<EOL>if '<STR_LIT>' in status and '<STR_LIT>' in status['<STR_LIT>']:<EOL><INDENT>identifie... | Request wrapper that automatically handles async requests. | f498:m1 |
def get_json(identifier, namespace='<STR_LIT>', domain='<STR_LIT>', operation=None, searchtype=None, **kwargs): | try:<EOL><INDENT>return json.loads(get(identifier, namespace, domain, operation, '<STR_LIT>', searchtype, **kwargs).decode())<EOL><DEDENT>except NotFoundError as e:<EOL><INDENT>log.info(e)<EOL>return None<EOL><DEDENT> | Request wrapper that automatically parses JSON response and supresses NotFoundError. | f498:m2 |
def get_sdf(identifier, namespace='<STR_LIT>', domain='<STR_LIT>',operation=None, searchtype=None, **kwargs): | try:<EOL><INDENT>return get(identifier, namespace, domain, operation, '<STR_LIT>', searchtype, **kwargs).decode()<EOL><DEDENT>except NotFoundError as e:<EOL><INDENT>log.info(e)<EOL>return None<EOL><DEDENT> | Request wrapper that automatically parses SDF response and supresses NotFoundError. | f498:m3 |
def get_compounds(identifier, namespace='<STR_LIT>', searchtype=None, as_dataframe=False, **kwargs): | results = get_json(identifier, namespace, searchtype=searchtype, **kwargs)<EOL>compounds = [Compound(r) for r in results['<STR_LIT>']] if results else []<EOL>if as_dataframe:<EOL><INDENT>return compounds_to_frame(compounds)<EOL><DEDENT>return compounds<EOL> | Retrieve the specified compound records from PubChem.
:param identifier: The compound identifier to use as a search query.
:param namespace: (optional) The identifier type, one of cid, name, smiles, sdf, inchi, inchikey or formula.
:param searchtype: (optional) The advanced search type, one of substructure... | f498:m4 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.