query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Searches the code line for the first ``////__CODEGEN`` identifier and adds the information to the codegen_map
def codegen_mapping(self, line: str, line_num: int): codegen_identifier = self.get_identifiers(line, findall=False) if codegen_identifier: codegen_debuginfo = codegen_identifier.split(';') self.codegen_map[line_num] = {'file': codegen_debuginfo[1], 'line': codegen_debuginfo[2]}
[ "def find_insertion_line(self, code):\n match = re.search(r\"^(def|class)\\s+\", code)\n if match is not None:\n code = code[: match.start()]\n try:\n pymodule = libutils.get_string_module(self.project, code)\n except exceptions.ModuleSyntaxError:\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of identifiers found in the code line
def get_identifiers(self, line: str, findall: bool = True): if findall: line_identifiers = re.findall(self.cpp_pattern, line) # The regex expression returns multiple groups (a tuple). # We are only interested in the first element of the tuple (the entire match). #...
[ "def identifiers(self):\n return [seq.identifier for seq in self]", "def get_line_identifier(self):", "def mbr_identifiers(self):\n return []", "def get_start_markers(self):\n starters = []\n for instr in self.instructions:\n i = instr.strip()\n if i.startswit...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Divide debuginfo into an array where each entry corresponds to the debuginfo of a diffrent sourcefile.
def divide(self): divided = [] for dbinfo in self.debuginfo: source = dbinfo['debuginfo']['filename'] exists = False for src_infos in divided: if len(src_infos) > 0 and src_infos[0]['debuginfo']['filename'] == source: src_infos.appe...
[ "def map_debuginfos(self):\n for rpm in self.rpms:\n if rpm.is_debuginfo:\n # print('calling map_debuginfo(%s)' % rpm.nevra)\n self.map_debuginfo(rpm)", "def _dump_debug_info(self):\r\n self._emitline('Contents of the .debug_info section:\\n')\r\n\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates the actual mapping by using the debuginfo list
def create_mapping(self, range_dict=None): for file_dbinfo in self.debuginfo: for node in file_dbinfo: src_file = node["debuginfo"]["filename"] if not src_file in self.map: self.map[src_file] = {} for line in range(node["debuginfo"]...
[ "def map_debuginfos(self):\n for rpm in self.rpms:\n if rpm.is_debuginfo:\n # print('calling map_debuginfo(%s)' % rpm.nevra)\n self.map_debuginfo(rpm)", "def makeMapping(globalMap):\n \n from memops.xml.Implementation import bool2str, str2bool\n\n # Set up top le...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add to Reports together
def __add__(self, other): merged_components = self.components + other.components new_report = Report() new_report.components = merged_components return new_report
[ "def merge(reports):\n report = reports[0]\n # merge other reports if any\n keys_report = list(reports[0].keys())\n for other_report in reports[1:]:\n for key in keys_report:\n report[key] += other_report[key]\n return report", "def add_report(self, tra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add component to report
def add_component(self, component): self.components.append(component)
[ "def __add__(self, other):\n merged_components = self.components + other.components\n new_report = Report()\n new_report.components = merged_components\n return new_report", "def add_component(self, component):\r\n self.subcomponents.append(component)", "def add_component(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add header1 to report
def add_header1(self, content): self.add_component(Header(content, 1))
[ "def addHeader1(self, str):\n self.add(\"<h1>\"+str+\"</h1>\")", "def append_header(self):\r\n # NOTE before everything\r\n # .TH title_upper section date source manual\r\n if self.header_written:\r\n return\r\n self.head.append(self.header())\r\n self.head.app...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add header2 to report
def add_header2(self, content): self.add_component(Header(content, 2))
[ "def addHeader2(self, str):\n self.add(\"<h2>\"+str+\"</h2>\")", "def add_header1(self, content):\n self.add_component(Header(content, 1))", "def add_header(self, *args, **kwargs):\r\n self.header = True\r\n self.add_row(ypos=0, *args, **kwargs)", "def append_header(self):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add header3 to report
def add_header3(self, content): self.add_component(Header(content, 3))
[ "def addHeader3(self, str):\n self.add(\"<h3>\"+str+\"</h3>\")", "def add_header(self, *args, **kwargs):\r\n self.header = True\r\n self.add_row(ypos=0, *args, **kwargs)", "def add_header4(self, content):\n self.add_component(Header(content, 4))", "def produce_header_footer():\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add header4 to report
def add_header4(self, content): self.add_component(Header(content, 4))
[ "def produce_header_footer():\n header = pl.PageStyle(\"header\", header_thickness=0.1)\n\n image_filename = get_image()\n with header.create(pl.Head(\"L\")) as logo:\n logo.append(pl.StandAloneGraphic(image_options=\"width=110px\", filename=image_filename))\n\n # Date\n with header.create(pl....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add paragraph to report
def add_paragraph(self, content): self.add_component(Paragraph(content))
[ "def paragraph(self, txt, color='black'):\r\n txt = f'<p style=\"color: {color}>{txt}</p>'\r\n append_content(txt)", "def createParagraph(c, text, x, y):\n style = getSampleStyleSheet()\n width, height = letter\n p = Paragraph(text, style=style[\"Normal\"])\n p.wrapOn(c, width, height)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add ordered_list to report
def add_ordered_list(self, content): self.add_component(OrderedList(content))
[ "def assignFields(self, order_list):\n order_list.append(\n {\"foid\": self.order.order_id,\n \"vip\": self.vip,\n \"book_id\": self.product_item_id,\n \"batch_id\": self.batch_id,\n \"order_number\": self.order_number,\n \"orig_order_num...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add unordered_list to report
def add_unordered_list(self, content): self.add_component(UnorderedList(content))
[ "def _create_asset_list_for_update_report(self):\n html_report = \"\"\n\n for asset_category in self.assets_grouped_by_cat:\n if self.assets_grouped_by_cat[asset_category]['assets']:\n # list the asset category first\n html_report += \"<p>\" \\\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add checkbox list to report
def add_checkbox_list(self, content): self.add_component(CheckboxList(content))
[ "def add_checkbutton( self, **kw ) :\n return self._add_widget( 'checkbutton', None, **kw )", "def gen_chk_btn(self):\n row = 0\n column = 0\n for index, name in enumerate(SETTINGS):\n if column % 3 == 0:\n row += 1\n column = 0\n var...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add table from pandas dataframe to report
def add_table(self, df): self.add_component(df)
[ "def add_table_from_df(self, df, style = \"Colorful Grid Accent 2\"):\n nrows, ncols = df.shape\n columns = df.columns.values\n table = self.document.add_table(rows=nrows+1, cols=ncols, style = style)\n\n header_cells = table.rows[0].cells\n i = 0\n for col in columns:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save Report to markdown format
def save_markdown(self, destination): destination = Path(destination) renderer = MarkdownRenderer() renderer.save(self, destination)
[ "def _dump_to_markdown(dump_infos, md_file=\"README.md\"):\n with open(md_file, \"w\") as f:\n title = os.path.basename(os.getcwd())\n f.write(\"# {} \".format(title))\n for dump_info_per_task in dump_infos:\n task_name = dump_info_per_task[\"task\"]\n tables = dump_in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the content of file. Existence of same file under app directory in user home overrides the default
def get_file_content(filename): # check if user have overridden anything filepath = "{}/{}/{}".format(USER_HOME, WK_BASE_DIR, filename) if os.path.exists(filepath): return open(filepath).read() # read default file content filepath = "{}/{}/{}".format(WK_SCRIPT_DIR, 'data', filename) if ...
[ "def _read_file(self):\n with open(self.file, 'r') as the_file:\n content = the_file.read()\n return content", "def content_file(self):\n return self._content_file", "def get_the_content_of_a_file(file_path):\r\n return open(file_path, encoding=\"utf8\").read()", "def readF...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
It generates the graph that presenting the Gold Standard (GS) snowballing and which GS items were found when analyzing the results.
def graph_snowballing(results_list): with open('/home/fuchs/Documentos/MESTRADO/Masters/Files-QGS/revisao-menezes/GS.csv', mode='r') as gs: # Skipping the GS.csv line written 'title' next(gs) # Creating a list where each element is the name of a GS article, without spaces, capital letters...
[ "def output_graphs(results):", "def plastic_package_graph():\n G = gt.Graph(directed=True)\n G.add_vertex(12)\n vid = G.new_vertex_property(\"string\")\n G.vertex_properties[\"id\"] = vid\n G.vp.id[0] = 'Farm'\n G.vp.id[1] = 'Packaging'\n G.vp.id[2] = 'Oil rig'\n G.vp.id[3] = 'Oil refinery...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove all contained plots.
def clear_all_plots(self): self.delete_plots(self.contained_plots) self.contained_plots = []
[ "def clear_elements(self):\n\n for child in self.ax.get_children(): # remove pie legend\n if 'legend' and 'anno' in str(child).lower():\n child.remove()\n\n for axes in self.fig.axes[1:]: # remove colorbar\n axes.remove()\n\n # remove pie charts\n t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Preprocess the list of plots so they can be embedded in manager. 1. Expand MultiConfigurators into a list of single plot configurators. 2. Convert Chaco containers and raw Configurators into descriptors.
def preprocess_plot_list(self, plot_list): from ..plotting.multi_plot_config import BaseMultiPlotConfigurator contained_plots = [] for i, desc in enumerate(plot_list): if isinstance(desc, BasePlotContainer): new_desc = embed_plot_in_desc(desc) contain...
[ "def _create_initial_plots_from_descriptions(self):\n for i, desc in enumerate(self.contained_plots):\n try:\n # Enforce the id since it will drive what plot gets removed and\n # replaced by the updated version:\n desc.id = str(i)\n # Set...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create or add one or more new Plots to the canvas. If a configurator is provided, the plot is generated from it, and added to the canvas. If a CUSTOM_PLOT_TYPE type is provided, a Chaco container is provided as the config_or_plot instead and it is wrapped in a PlotDescriptor and included in the canvas directly.
def add_new_plot(self, plot_type, config_or_plot, position=None, **kwargs): if plot_type.startswith("Multi"): self._add_new_plots(config_or_plot, position=position, **kwargs) elif plot_type == CUSTOM_PLOT_TYPE: if isinstance(config_or_plot, PlotDescriptor): desc =...
[ "def __init__(self, plot_type='graph'):\n \n # plot_type = {'graph', 'phase', 'both'}\n self.plot_type = plot_type\n self.cmap = cm.get_cmap('hsv')\n \n \n if self.plot_type in ['graph']:\n self.figure = plt.figure(figsize=1.5*plt.figaspect(1))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a (list of) plot(s). Clean up resources.
def delete_plots(self, plot_descriptions, container=None): if isinstance(plot_descriptions, PlotDescriptor): plot_descriptions = [plot_descriptions] for plot_desc in plot_descriptions: if plot_desc in self.contained_plots: self.contained_plots.remove(plot_desc) ...
[ "def RemovePlot(self, plt):\n if self.plots.count(plt)>0:\n self.plots.pop(self.plots.index(plt)).Delete()", "def clear_all_plots(self):\n self.delete_plots(self.contained_plots)\n self.contained_plots = []", "def remove(self):\r\n self.figure.delaxes(self.sub_plots[-1].ax...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize from list of plot descriptions (which gets serialized).
def _create_initial_plots_from_descriptions(self): for i, desc in enumerate(self.contained_plots): try: # Enforce the id since it will drive what plot gets removed and # replaced by the updated version: desc.id = str(i) # Set/sync confi...
[ "def __init__(self, axes_list):\r\n # Matplotlib artists that need to be updated.\r\n self.lines = []\r\n self.leglines = []\r\n self.legtexts = []\r\n \r\n for axes in axes_list:\r\n new_lines = [line for line in axes.get_lines()\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply the styler's range attributes to the created plot.
def _apply_style_ranges(self, config, plot, factory): style = config.plot_style # Override the plot by collecting the OverlayPlotContainer instance # which holds the axis instances to apply to: if isinstance(plot, HPlotContainer): for comp in plot.components: ...
[ "def setRange(self, min, max, label=''):\n self.min=min\n self.max=max\n self.label=label\n self.drawAxis()", "def _set_ranges(self):\n # ToDo: handle when only single dimension is provided\n\n extents = self._get_dim_extents()\n\n endx = extents['x_max']\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return plot factory capable of building a plot described by config.
def _factory_from_config(self, config): plot_type = config.plot_type plot_factory_klass = self.plot_factories[plot_type] return plot_factory_klass(**config.to_dict())
[ "def create(self, name):\n # Get plot data from config and validate it\n data = self.parse(name)\n config = self.validate(data)\n\n # Load plot class\n path = self.app.config.get('app.plots.path', 'plots')\n plots = find_files(self.app.root, path, name, '(plot|chart|graph)....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A factory requested its style to be edited. Launch dialog.
def action_edit_style_requested(self, manager, attr_name, new): desc = self._get_desc_for_menu_manager(manager) desc.edit_plot_style = True
[ "def edit(self):\n if self.dialog is None:\n self.create_dialog()\n\n # Reset the dialog, which will rectreate the PeriodicTable\n # widget\n self.reset_dialog()\n # And resize the dialog to fit...\n self.fit_dialog()\n\n super().edit()", "def openDialog...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notify all inspector tools that selection has changed, except if plot is frozen.
def sync_all_inspectors(self): for desc_id, inspector in self.inspectors.items(): if self.contained_plot_map[desc_id].frozen: continue tool = inspector[0] current_selection = tool.component.index.metadata[ SELECTION_METADATA_NAME ]...
[ "def OnUpdate(self, comps=None):\n #nps = self.selection.GetNodePaths()\n self.gizmoMgr.AttachNodePaths(self.selection.node_paths)\n self.gizmoMgr.RefreshActiveGizmo()\n self.selection.update()", "def toolChanged(self, tool: ghidra.framework.plugintool.PluginTool) -> None:\n ......
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract OverlayPlotContainer corresponding to provided descriptor.
def _get_overlay_plot_cont_from_desc(self, plot_desc): if plot_desc.plot_type in CMAP_PLOT_TYPES: # Unpack it from the HPlotContainer it's in: return plot_desc.plot.components[0] else: return plot_desc.plot
[ "def get_overlay(self, overlay_name):\n logger.debug(\"Getting overlay: {} {}\".format(overlay_name, self))\n overlay_key = self.get_overlay_key(overlay_name)\n text = self.get_text(overlay_key)\n return json.loads(text)", "def widget(self):\n return self.overlay.widget", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Embed chaco plot in PlotDescriptor so it can be displayed in DFPlotter.
def embed_plot_in_desc(plot): if isinstance(plot, Plot): desc = PlotDescriptor( plot_type=CUSTOM_PLOT_TYPE, plot=plot, plot_config=BaseSinglePlotConfigurator(), plot_title=plot.title, x_axis_title=plot.x_axis.title, y_axis_title=plot.y_...
[ "def dispersion(x_axis, y_axis, x_axis_label, y_axis_label, show_plot=True):\n # List that store the figure handler\n list_figures_1 = []\n\n # Plotting of Tachogram\n list_figures_1.append(figure(x_axis_label=x_axis_label, y_axis_label=y_axis_label,\n **opensignals_kwarg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a Local Weblog publisher.
def manage_add_local_weblog_publisher_edit(self, id=None, title='', REQUEST=None): if id is None: id = self.get_unique_id() local_weblog_publisher_ = local_weblog_publisher(id, title, creator=self.get_user().get_id(), owner=self.get_user().get_id()) self._setObj...
[ "def get_publisher(self, log_path):\n if log_path not in self.http_publishers:\n self.log.debug(\"Creating a Http Log publisher for path \\\"%s\\\"\" % log_path)\n self.http_publishers[log_path] = HttpLogPublisher(\n log_path,\n self.tenant_id,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all the enclosures within the issue.
def get_enclosures(self, issue): issues_ = [] if issue.format == 'file': issues_.append(issue) for id in issue.get_referenced_ids(): issues_.append(self.get_object(id)) issues = [] for issue in issues_: file = getattr(issue, issue.filename) ...
[ "def get_enclosures(self, entry):\n enclosures = []\n for enclosure in getattr(entry, 'enclosures', []):\n href = getattr(enclosure, 'href', None)\n type = getattr(enclosure, 'type', None)\n if href is None or type is None:\n # Example feed with fully em...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns all category issues.
def get_category_issues(self, parent_level=-1): categories = [] categories_ = [] contained = {} for issue in self.get_published_issues(): issue = issue['issue'] parent = issue.get_parent_ids[-parent_level] if issue.get_parent_meta_types[1] != 'Issue De...
[ "def get_weblog_issues(self, start=0, size=15, category=''):\n if category:\n issues = self.catalog_search(published_in=self.id, get_parent_ids=category, sort_on='modified', sort_order='reverse')[start:start+size]\n issues_ = []\n for issue in issues:\n relatio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the weblog host.
def get_weblog_host(self): return urllib.splithost(urllib.splittype(self.get_weblog_url())[1])[0].split(':')[0]
[ "def get_host(self):\n return self._host", "def get_host_name(self):\n return self.__get_value(\"agentLevelParams/hostname\")", "def host(self):\n return self.socket.getsockname()[0]", "def hostname(self):\n return self.__urlsplit.hostname", "def host_name(self):\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the weblog URL.
def get_weblog_url(self): if self.weblog_url: return self.weblog_url else: return self.absolute_url()
[ "def get_weblog_host(self):\n return urllib.splithost(urllib.splittype(self.get_weblog_url())[1])[0].split(':')[0]", "def get_logs_url(self):\n return '{}?key={}'.format(config.BUILD_LOGS_API_ENDPOINT, quote_plus(self._get_logs_key()))", "def getWeblog():", "def getArchiveURLFor(weblogentry):", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders a widget for selecting timezones.
def render_timezone_widget(self): html = "<select name='timezone'>" for timezone in self.get_timezones(): if timezone == self.timezone: html += "<option selected='selected'>%s</option>" % timezone else: html += "<option>%s</option>" % timezone ...
[ "def html_render_timezones(\n select_name: str,\n current_selected: str | None = None,\n user_ip: str | None = None,\n first_entry: str = \"Select your timezone\",\n force_current_selected: bool = False,\n select_id: Any = None,\n default_timezone: str | None = None,\n) -> str:\n\n # Makes i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the issue title. This is a security hack.
def get_issue_title(self, issue): if self.been_published(issue): if callable(issue.get_title): return issue.get_title() else: return issue.get_title else: raise 'Unauthorized'
[ "def issuetitle(self):\n return self._head.get('source', {}).get('issuetitle')", "def get_title(self):\n return self._title", "def get_report_title(self):\n return None", "def title(self):\n tmp = c.namemap_lookup(self.id) if c.namemap_lookup(self.id) is not None else self._title\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the issue contents. This is a security hack.
def render_issue_contents(self, issue, unlinked=0): if issue.id in self.get_published_ids(): return functions.render_contents_weblog(issue, unlinked=unlinked) else: raise 'Unauthorized'
[ "def render_issue_response(self, request, context):\n return render(request, self.response_template, context)", "def render(self, user):\n self._render_text = self.content.replace('\\n', '<br>')\n return render_str(\"post.html\", p=self, user=user)", "def show_issue(self, msg, issue_id):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the issue creation date.
def render_issue_created(self, issue): return issue.created.toZone(self.timezone).strftime('%d %h %H:%M')
[ "def _creation_date(self) -> str:\n return maya.parse(self.metadata.get(\"creationDate\")).iso8601().replace(\":\", \"\")", "def creation_date(context: dict) -> str:\n return datetime.fromtimestamp(os.path.getctime(context['item_path'])).strftime('%Y-%m-%d %H:%M')", "def issue_date(self):\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the issue category.
def render_issue_category_link(self, issue): id = issue.get_parent_ids[1] title = issue.get_parent_titles[1] meta_type = issue.get_parent_meta_types[1] if meta_type == 'Issue Dealer': title = "All" return """<a href="%s/search?category=%s">%s</a>""" % \ (sel...
[ "def handle_category_action(args):\n category = args.category\n return {'issue': issue, 'pr': pr}.get(category, issue)", "def project_category(nd, project_no):\n return render_template('p_category.html',\n nd=nd,\n formal_name=db_helper.get_formal_name(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of published issues for the weblog.
def get_weblog_issues(self, start=0, size=15, category=''): if category: issues = self.catalog_search(published_in=self.id, get_parent_ids=category, sort_on='modified', sort_order='reverse')[start:start+size] issues_ = [] for issue in issues: relation = self.c...
[ "def issues(self):\n return self.properties.get('issues',\n EntityCollection(self.context, ServiceHealthIssue,\n ResourcePath(\"issues\", self.resource_path)))", "def issue_urls(self):\n return self._issue_urls", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Publishes the issue to the weblog.
def publish_issue(self, issue): relation = mixins.relation_publisher.publish_issue.im_func(self, issue) if self.ping: try: remoteServer = xmlrpclib.Server("http://rpc.pingomatic.com") thread.start_new_thread(remoteServer.weblogUpdates.ping, ...
[ "def notify(self):\n\n if self.send_to_sns:\n publish_to_sns('SO0111-SHARR_Topic', self.severity + ':' + self.message, AWS_REGION)\n\n self.applogger.add_message(\n self.severity + ': ' + self.message\n )\n if self.logdata:\n for line in self.logdata:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Edits the blog style.
def admin_edit_style(self, blog_style='', REQUEST=None): self.blog_style = blog_style self.modified = DateTime() self.index_object() if REQUEST: REQUEST.RESPONSE.redirect(self.get_admin_url())
[ "def apply(self, style):\n style = str(style)\n for styledef in style.split():\n if styledef == 'noinherit':\n self.inherit = False\n elif styledef == 'bold':\n self.bold = True\n elif styledef == 'nobold':\n self.bold = Fal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an image related to the published issue.
def image(self, id=None, REQUEST=None, RESPONSE=None): result = self.catalog_search(id=self.get_published_ids(), get_local_image_ids=id, meta_type='Issue') if result: return base.base.image.im_func(self, id=id, REQUEST=REQUEST, RESPONSE=RESPONSE) else: raise 'Un...
[ "def getArtifactImage(self, msg):\n if self.displayed_artifact_id == None:\n g = GuiMessage()\n g.data = \"No artifact selected. No image to display.\"\n g.color = g.COLOR_ORANGE\n self.message_pub.publish(g)\n return\n\n # display a black image ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the next issue, or none if there aren't any.
def get_next(self, issue): try: published = self.get_published_ids() return self.get_object(published[published.index(issue) + 1]) except IndexError: return None except ValueError: return None
[ "def getIssue(self, index):\r\n # type: (int) -> Issue\r\n if 0 <= index < len(self.issues):\r\n return self.issues[index]\r\n return self.issues[0]", "def get_issue(key, issues):\n return filter((lambda issue: issue.key == key), issues)[0]", "def queue_next():\n #CD.object...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the previous issue, or none if there aren't any.
def get_previous(self, issue): try: published = self.get_published_ids() return self.get_object(published[published.index(issue) - 1]) except IndexError: return None except ValueError: return None
[ "def get_previous(self):\n song_list = list(self.artist.song_set.all())\n index = song_list.index(self)\n if index > 0:\n return song_list[index - 1]\n return None", "def previous(self):\n try:\n obj = self.get_previous_by_created(hidden=False)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renders the given date in a W3C Date and Time Format.
def render_as_W3CDTF(self, date): return utilities.render_as_W3CDTF(date)
[ "def draw_time_date(self):\n\n now = self.current_time()\n time_str = now.strftime(\"%H:%M:%S\")\n date_str = now.strftime(\"%y-%m-%d\")\n self.graphics.DrawText(self.canvas, self.font, 0, 12, self.time_color, time_str)\n self.graphics.DrawText(self.canvas, self.font, 0, 31, self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Saves contents of template.
def save_template(self, id, template): getattr(self.aq_base, id).pt_edit(template, '') self.get_response().redirect(self.absolute_url() + '/templates')
[ "def _update_template(self, content):\r\n t, created = Template.objects.get_or_create(resource=self.resource)\r\n t.content = content\r\n t.save()", "def save(self, page, basename, *args, **kwargs):\n form = self._form(*args, **kwargs)\n if form.is_valid():\n return f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Restores the given template.
def restore_template(self, id): self.manage_delObjects(ids=['custom_' + id]) self.get_response().redirect(self.absolute_url() + '/templates')
[ "def reset(self):\n self.__template = None", "def template_loaded(self, template):\n self.template = template", "def restoreContent(self):\n ...", "def _update_template(self, content):\r\n t, created = Template.objects.get_or_create(resource=self.resource)\r\n t.content = co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a scaling transformation matrix. If sy is None, sy = sx, and if sz is None sz = sx.
def scale(cls, sx, sy=None, sz=None): if sy is None: sy = sx if sz is None: sz = sx return cls([ float(sx), 0., 0., 0., 0., float(sy), 0., 0., 0., 0., float(sz), 0., 0., 0., 0., 1. ])
[ "def scaling(sx,sy,mat2):\n\n\tmat1=[[sx,0,0],[0,sy,0],[0,0,1]]\n\tscaled=matrix_multiplication(mat1,mat2)\n\treturn scaled", "def scaling_matrix(s0, s1, s2):\n m = identity()\n matrix_elem(m, 0, 0, s0)\n matrix_elem(m, 1, 1, s1)\n matrix_elem(m, 2, 2, s2)\n return m", "def getScaleSpaceMatrix(self, mat: '...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a translation matrix to (x, y, z).
def translate(cls, x, y, z): return cls([ 1., 0., 0., 0., 0., 1., 0., 0., 0., 0., 1., 0., float(x), float(y), float(z), 1. ])
[ "def translation(x=0, y=0, z=0):\n m = np.array([[1, 0, 0, x],\n [0, 1, 0, y],\n [0, 0, 1, z],\n [0, 0, 0, 1]], dtype=float)\n return m", "def getTranslationMatrix(t):\n mat = np.zeros((4,4))\n mat[0, 0] = 1\n mat[1, 1] = 1\n mat[2, 2] = 1\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compose a transformation matrix from one or more matrices.
def chain(*matrices): transformation = Matrix44() for matrix in matrices: transformation *= matrix return transformation
[ "def combine_transforms(transforms):\n t = transforms[0]\n for i in range(1, len(transforms)):\n t = np.dot(t, transforms[i])\n return t", "def geometryTransformMatrix(*args, **kwargs):\n \n pass", "def get_matrix_transformation(self, matrix: np.ndarray | list | tuple):\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Iterates over all matrix values.
def __iter__(self): return iter(self.matrix)
[ "def __iter__(self):\n for value in self.cells:\n yield value", "def getValues(self, i = 0):\n return _coin.SoMFMatrix_getValues(self, i)", "def iterator(self):\n return _core.MatrixXdVec_iterator(self)", "def values(self):\n for item in self.table:\n if item:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Multiplies this matrix with other matrix. Assumes that both matrices have a right column of (0, 0, 0, 1). This is True for matrices composed of rotations, translations and scales. fast_mul is approximately 25% quicker than the = operator.
def fast_mul(self, other): m1 = self.matrix m2 = other.matrix self.matrix = [ m1[0] * m2[0] + m1[1] * m2[4] + m1[2] * m2[8], m1[0] * m2[1] + m1[1] * m2[5] + m1[2] * m2[9], m1[0] * m2[2] + m1[1] * m2[6] + m1[2] * m2[10], 0.0, m1[4] * m2...
[ "def matmul(\n inp1: Tensor,\n inp2: Tensor,\n transpose_a=False,\n transpose_b=False,\n compute_mode=\"default\",\n) -> Tensor:\n return _matmul(inp1, inp2, transpose_a, transpose_b, compute_mode)", "def mul(self, matrix):", "def _matmul_kronecker_product(self, other, shape_hint):\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of transformed vectors.
def transform_vectors(self, vectors): result = [] m0, m1, m2, m3, m4, m5, m6, m7, m8, m9, m10, m11, m12, m13, m14, m15 = self.matrix for vector in vectors: x, y, z = vector result.append(( x * m0 + y * m4 + z * m8 + m12, x * m1 + y * m5 + z...
[ "def transformations(self):\n\t\treturn [ [n.a.t.v,n.a.r.v] for n in self.nodes ]", "def transform(self, corpus, remove_oov=False, norm=False):\n return [self.vectorize(s, remove_oov=remove_oov, norm=norm) for s in corpus]", "def toVector(self, *args):\n return _almathswig.Transform_toVector(self,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generates a set of RGB colors corresponding to the visible spectrum (i.e. the rainbow). These colors can be used by Matplotlib, PyQtGraph, Qt, and other plotting/graphics libraries.
def spectrum_colors(num_colors): if isinstance(num_colors, int): num_colors = range(num_colors) num_colors = list(num_colors) if len(num_colors) == 1: hue_values = [0] else: mi = min(num_colors) ma = max(num_colors) - mi hue_values = reversed([(n - mi) / ma for n...
[ "def colorGenerator():\n import colorsys\n while True:\n for luma in (0.8, 0.5):\n for hue in (0.66, 0, 0.33, 0.75, 0.15):\n yield rrd.Color(hsv=(hue,1,luma))", "def gen_color():\n import colorsys\n golden_ratio = 0.618033988749895\n h = 0.22717784590367374\n\n w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a set of RGB colors as a linear sweep between two RGB colors `source` and `dest`. These colors can be used by Matplotlib, PyQtGraph, Qt, and other plotting/graphics libraries.
def rgb_sweep(num_colors, source, dest): if isinstance(source, str): source = _hex_to_rgb(source) if isinstance(dest, str): dest = _hex_to_rgb(dest) yield from multilinspace(source, dest, num=num_colors)
[ "def interpolate_colors(c1, c2, distance):\n c1, c2 = parse_color(c1), parse_color(c2)\n\n r = c1.red + distance * (c2.red - c1.red)\n g = c1.green + distance * (c2.green - c1.green)\n b = c1.blue + distance * (c2.blue - c1.blue)\n\n return gtk.gdk.Color(red=int(r), green=int(g), blue=int(b))", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes string msg and an integer shift returns new string which is an encrypted version of the message str, int > str print(encrypt('John', 15)) > 'YDwC' print(encrypt(' ', 6)) > 'b'
def encrypt(msg, shift): # the body of function encrypted_msg='' new_index=0 for i in msg: index=ALPHABET.find(i) alpha_index=index+shift if abs(alpha_index)>=len(ALPHABET): new_index = alpha_index%len(ALPHABET) else:...
[ "def encrypt(msg, shift):\n # remove this pass statement and write the body of your function\n newStr = ''\n for i in range(len(msg)):\n for j in range(len(ALPHABET)):\n if msg[i]==ALPHABET[j]:\n index = j\n break\n newStr += ALPHABET[(index + shift) %...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes string encrypted_msg and an integer shift returns new string which is a decrypted version of the message str, int > str print(decrypt('eDUHM', 25)) > Kevin print(decrypt('j.GT', 10000)) > Ivan
def decrypt(encrypted_msg, shift): # the body of function decrypted_msg='' new_index=0 for i in encrypted_msg: index=ALPHABET.find(i) alpha_index=index-shift if abs(alpha_index)>=len(ALPHABET): new_index = alpha...
[ "def decrypt(encrypted_msg, shift):\n # remove this pass statement and write the body of your function\n newStr = ''\n for i in range(len(encrypted_msg)):\n for j in range(len(ALPHABET)):\n if encrypted_msg[i]==ALPHABET[j]:\n index = j\n break\n newStr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a csv file as input and returns a dictionary with lists of data for each column whose names are the keys
def csv2dict(file: str, newline_symbol:str='\n', delimiter_symbol:str=',')-> dict: #initializes an empty dictionary data={} #Creates one key per column of the csv file with open(file, newline=newline_symbol) as csvfile: filereader = csv.reader(csvfile, delimiter=',') names_...
[ "def csv_to_dict_list(csv_path):\n new_list = []\n\n with open(csv_path, 'r') as csvFile:\n reader = csv.reader(csvFile)\n headers = next(reader, None)\n for row in reader:\n element = {}\n for i in range(len(headers)):\n element[headers[i]] = row[i]\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Controls displaying/hiding the advanced run fields on radio button toggle.
def toggle_advanced(self): rbutton = self.sender() if rbutton.isChecked(): self.adv_run_fields.show() else: self.adv_run_fields.hide()
[ "def configure_boxes_for_design_parameters(self):\n if self.ui.radioButton_NWn.isChecked():\n self.ui.label_opt1.setText(\"N: \")\n self.ui.label_opt2.setText(\"Freq. (Hz): \")\n self.ui.label_opt3.hide()\n self.ui.label_opt4.hide()\n self.ui.plainTextEd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The Bernstein polynomial of n, i as a function of t
def bernstein_poly(i, n, t): return comb(n, i) * (t**(n-i)) * (1 - t)**i
[ "def bernstein_poly(self, i, n, t):\n return comb(n, i) * ( t**(n-i) ) * (1 - t)**i", "def bernsteinbasis(i, n):\n bc = binomialcoefficient(n, i)\n n_less_i = n - i\n def bernie(t):\n return bc * t**i * (1 - t)**n_less_i\n return bernie", "def binomial(k, n):\r\n P = (Polynome ([1,1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a set of control points, return the bezier curve defined by the control points. points should be a list of lists, or list of tuples such as [ [1,1], [2,3], [4,5], ..[Xn, Yn] ] nTimes is the number of time steps, defaults to 1000
def bezier_curve(points, nTimes=1000): nPoints = len(points) xPoints = np.array([p[0] for p in points]) yPoints = np.array([p[1] for p in points]) t = np.linspace(0.0, 1.0, nTimes) polynomial_array = np.array([bernstein_poly(i, nPoints-1, t) for i in range(0, nPoints)]) # Array comes out in ...
[ "def bezier_curve(self, points, nTimes=1000):\n nPoints = len(points)\n xPoints = np.array([p[0] for p in points])\n yPoints = np.array([p[1] for p in points])\n\n t = np.linspace(0.0, 1.0, nTimes)\n\n polynomial_array = np.array([ self.bernstein_poly(i, nPoints-1, t) for i in ran...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes set of ordered xy coordinates equidistant N is desired point distance along curve
def make_equidistant(x, y, N): xvals = np.expand_dims(x[0], axis=0) yvals = np.expand_dims(y[0], axis=0) eucdist = 0.0 for i in range(1, len(x)): eucdist += np.sqrt((x[i] - x[i-1])**2 + (y[i] - y[i-1])**2) if eucdist >= N: xvals = np.append(xvals, x[i]) yvals = np...
[ "def ordinary_points(n):\n return [(x, y) for x in range(n) for y in range(n)]", "def _hemPoints(v, n):\n v = g.normalize(v)\n north, east = g.northEast(v)\n points = []\n for i in xrange(n):\n z = -1.0\n while z < 0.0:\n x = random.uniform(-1.0 + 1.0e-7, 1.0 - 1.0e-7)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this test executes a simple decision and validates the results
def test_execute_simple_decision(): print('testing a simple decision') _rule_name = "eligibility_criteria" _body = { "facts": { "cibil_score": 700, "marital_status": "Married", "business_ownership": "Owned by Self" } } print(_rule_...
[ "def test_create_checker_result(self):\n pass", "def test_evaluate(self):\n\t\tpass", "def test_get_checker_result(self):\n pass", "def test6_evaluation(self):\n self.data = clam.common.data.ParameterCondition(x=True,\n then=clam.common.data.SetMetaField('x','yes'),\n )\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get a list of Events for a given list of Event UIDs. If one or more provided uid(s) do not exist, it will be ignored.
async def get_list_of_events( event_uids: List[str], username=Depends(auth_handler.auth_wrapper) ): logger.debug(f"User({username}) fetching a list of events info") event_info_list: List[dict] = [] event_uids = list(set(event_uids)) try: for uid in event_uids: if isinstance(uid,...
[ "def getEventListByOwner(ownerUserID):\n\tquery = Event.query(Event.ownerid==ownerUserID)\n\treturn _fetchEventList(query)", "def get_events_by_ids(self, event_ids):\n return # osid.calendaring.EventList", "def get_user_events(username, start, count):\n return _get_events(username, start, count)"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sign a list of Students up for a specific event This is done by student themselves, hence, len(student_id_list) == 1
async def register_students_for_event( uid: str, student_id_list: List[str], username=Depends(auth_handler.auth_wrapper) ): logger.debug(f"User({username}) trying to sign up Event({uid}).") permission_ok = False if len(student_id_list) == 1: permission_ok = student_id_list[0] == username if...
[ "async def deregister_students_for_event(\n uid: str, student_id_list: List[str], username=Depends(auth_handler.auth_wrapper)\n):\n logger.debug(f\"User({username}) trying to de-register Event({uid}).\")\n permission_ok = False\n if len(student_id_list) == 1:\n permission_ok = student_id_list[0] ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
deregister a list of Students for a specific event This can be done by self, adminwrite, usually len(student_id_list) == 1
async def deregister_students_for_event( uid: str, student_id_list: List[str], username=Depends(auth_handler.auth_wrapper) ): logger.debug(f"User({username}) trying to de-register Event({uid}).") permission_ok = False if len(student_id_list) == 1: permission_ok = student_id_list[0] == username ...
[ "def remove_student(self, student_name) -> None:\n if student_name in self.enrolled_students:\n self.enrolled_students.remove(student_name)\n self.add_student(self.waitlist[0])\n self.waitlist.remove(self.waitlist[0])\n elif student_name in self.waitlist:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a list of Students's attendence for a specific event
async def add_students_attendance_for_event( uid: str, student_id_list: List[str], username=Depends(auth_handler.auth_wrapper) ): logger.debug(f"User({username}) trying to add attendance for Event({uid}).") permission_ok = Access.is_admin_write(username) or Access.is_student_hg(username) if not permiss...
[ "def add_attendee(name, host, restaurant, user, new_list):\n new_list.append(user)\n change_event = DB.session.query(models.Event).filter_by(event_name=name, host=host,\n restaurant=restaurant).first()\n change_event.attendees = new_list\n DB.se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a list of Students's attendence for a specific event
async def remove_students_attendance_for_event( uid: str, student_id_list: List[str], username=Depends(auth_handler.auth_wrapper) ): logger.debug(f"User({username}) trying to remove attendance for Event({uid}).") permission_ok = Access.is_admin_write(username) or Access.is_student_hg(username) if not pe...
[ "def remove_event(self, event):\r\n all_strucs = self.instruction.parse.strucs\r\n for struc in all_strucs:\r\n if struc.accounted_for_by_sem == event:\r\n struc.accounted_for_by_sem = None\r\n self.events.remove(event)\r\n event.schedule = None", "async def d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Seed numpy with a random seed.
def seed_numpy(self): np.random.seed(42)
[ "def set_seed(seed):\r\n if (seed <= -1):\r\n np.random.seed(int(time.time())%1000)\r\n else:\r\n np.random.seed(seed)", "def numba_random_seed(seed: int) -> None:\n\n np.random.seed(seed)", "def _reset_random_seed():\n current_time = time.time() * 1e8\n\n np.random.seed(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate dummy sales data for one customer.
def generate_data_for_one_customer( self, id: int, min_date: str, max_date: str, acquisition_date: str = None, n_orders: int = None, equispaced: bool = False, ) -> pd.DataFrame: if not acquisition_date: min_ac_date = pd.to_datetime("1980-0...
[ "def test_one_customer_per_sample(self, sampler, raw_data):\n sampled = sampler.generate_samples(raw_data)\n n_customers = sampled.groupby(\"sample_id\").customer_id.nunique()\n assert np.all(n_customers == 1)", "def get_sales_by_customer(entity):\n \n return Sale.query.filter(Sale.enti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate dummy purchase data for 100 customers.
def raw_data(self) -> pd.DataFrame: min_date = "2016-01-01" max_date = "2019-12-13" raw_data = [ self.generate_data_for_one_customer(i, min_date, max_date) for i in range(100) ] raw_data = pd.concat(raw_data, axis=0) for i in range(10): ...
[ "def fake_vacancies_data(faker):\n def gen_vacancies(sources_count=1, vacancies_count=3):\n vacancies_data = []\n for s in range(sources_count):\n source_name = faker.company()\n for v in range(vacancies_count):\n vacancies_data.append({\n 'so...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIVEN a config with a missing specification for a parameter. WHEN a BinnedUniformSampler is instantiated with the missing keyword argument. THEN a TypeError is raised
def test_instantiation_with_missing_field_fails( self, missing_field: str, config: Dict[str, Any] ): del config[missing_field] with pytest.raises(expected_exception=TypeError): _ = BinnedUniformSampler(**config)
[ "def test_instantiation_with_wrong_data_type_fails(\n self, param: str, value_wrong_type: Any, config: Dict[str, Any]\n ):\n\n config[param] = value_wrong_type\n with pytest.raises(ValueError):\n BinnedUniformSampler(**config)", "def test_instantiation_from_config(self, config: ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIVEN a keyword argument's value of the wrong data type. WHEN a BinnedRandomSampler is instantiated with the wrong value THEN a ValueError is raised.
def test_instantiation_with_wrong_data_type_fails( self, param: str, value_wrong_type: Any, config: Dict[str, Any] ): config[param] = value_wrong_type with pytest.raises(ValueError): BinnedUniformSampler(**config)
[ "def test_instantiation_with_missing_field_fails(\n self, missing_field: str, config: Dict[str, Any]\n ):\n del config[missing_field]\n with pytest.raises(expected_exception=TypeError):\n _ = BinnedUniformSampler(**config)", "def test_param_invalid_keyword_param_type(self):\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIVEN a valid config for a BinnedUniformSampler WHEN the classmethod `from_config` is called with this config THEN a BinnedUniformSampler is instantiated.
def test_instantiation_from_config(self, config: Dict[str, Any]): BinnedUniformSampler.from_config(config)
[ "def test_equals_w_equal_instances(self, config: Dict[str, Any]):\n first_sampler = BinnedUniformSampler(**config)\n second_sampler = BinnedUniformSampler(**config)\n assert first_sampler == second_sampler", "def from_config(cls, config: Dict[str, Any]) -> \"ClassyMeter\":\n raise NotI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIVEN an instantiated BinnedUniformSampler WHEN the instance's `to_dict` method is called and the output is dumped to YAML THEN no exception is raised.
def test_to_dict_is_yaml_serializable(self, sampler: BinnedUniformSampler): yaml.dump(sampler.to_dict())
[ "def test_instantiation_from_to_dict_output(self, sampler: BinnedUniformSampler):\n representation = sampler.to_dict()\n clone = BinnedUniformSampler.from_config(representation)\n assert clone == sampler", "def test_instantiation_from_config(self, config: Dict[str, Any]):\n BinnedUnifo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIVEN keyword arguments for a BinnedUniformSampler WHEN two samplers are instantiated from the same config THEN they are equal.
def test_equals_w_equal_instances(self, config: Dict[str, Any]): first_sampler = BinnedUniformSampler(**config) second_sampler = BinnedUniformSampler(**config) assert first_sampler == second_sampler
[ "def test_equals_wo_equal_instance(\n self, sampler: BinnedUniformSampler, config: Dict[str, Any]\n ):\n first_sampler = BinnedUniformSampler(**config)\n config[\"lookback\"] = str(sampler.lookback / 2)\n second_sampler = BinnedUniformSampler(**config)\n assert first_sampler !=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIVEN a valid set of keyword arguments for a BinnedUniformSampler WHEN one sampler is instantiated with that config and another sampler is instantiated \ with a slightly changed set of keyword arguments THEN the two samplers are not equal.
def test_equals_wo_equal_instance( self, sampler: BinnedUniformSampler, config: Dict[str, Any] ): first_sampler = BinnedUniformSampler(**config) config["lookback"] = str(sampler.lookback / 2) second_sampler = BinnedUniformSampler(**config) assert first_sampler != second_sampl...
[ "def test_equals_w_equal_instances(self, config: Dict[str, Any]):\n first_sampler = BinnedUniformSampler(**config)\n second_sampler = BinnedUniformSampler(**config)\n assert first_sampler == second_sampler", "def test_result_is_reproduceable_between_samplers(self, config, raw_data, seed):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIVEN the output from a samplers `to_dict` method WHEN a new sampler is instantiated from this output via the `from_config` classmethod THEN the two resulting samplers are equal.
def test_instantiation_from_to_dict_output(self, sampler: BinnedUniformSampler): representation = sampler.to_dict() clone = BinnedUniformSampler.from_config(representation) assert clone == sampler
[ "def test_equals_w_equal_instances(self, config: Dict[str, Any]):\n first_sampler = BinnedUniformSampler(**config)\n second_sampler = BinnedUniformSampler(**config)\n assert first_sampler == second_sampler", "def test_equals_wo_equal_instance(\n self, sampler: BinnedUniformSampler, con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIVEN a sampler instance and some dummy purchase data for multiple customers WHEN samples are created from this data using the sampler THEN the prediction times of all samples is within `[sampler.min_date, sampler.max_date]`
def test_no_prediction_time_outside_min_and_max_date( self, sampler: BinnedUniformSampler, raw_data: pd.DataFrame ): sampled = sampler.generate_samples(raw_data) max_date = sampler.max_date min_date = sampler.min_date assert np.all(sampled.prediction_time > min_date) ...
[ "def test_x_data_but_no_y_data(self):\n lead_time = pd.to_timedelta(\"1d\")\n lookback = pd.to_timedelta(\"2y\")\n prediction_period = pd.to_timedelta(\"180d\")\n min_date = pd.to_datetime(\"2018-01-01\")\n max_date = (\n min_date + lookback + lead_time + prediction_per...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIVEN a sampler instance and some dummy purchase data for multiple customers WHEN samples are generated from the data THEN each sample is based on exactly one customer's data.
def test_one_customer_per_sample(self, sampler, raw_data): sampled = sampler.generate_samples(raw_data) n_customers = sampled.groupby("sample_id").customer_id.nunique() assert np.all(n_customers == 1)
[ "def test_x_data_but_no_y_data(self):\n lead_time = pd.to_timedelta(\"1d\")\n lookback = pd.to_timedelta(\"2y\")\n prediction_period = pd.to_timedelta(\"180d\")\n min_date = pd.to_datetime(\"2018-01-01\")\n max_date = (\n min_date + lookback + lead_time + prediction_per...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIVEN a set of parameters for a sampler WHEN samples are generated from one customers data using a sampler instantiated \ with these parameters THEN all samples for this customers fall into equispaced bins of the customers's \ purchase history.
def test_samples_within_bins( self, min_date, max_date, lead_time, prediction_period, lookback, samples_per_lookback, random_seed, ): np.random.seed(random_seed) # generate data for timespan customer_data = self.generate_data_f...
[ "def test_y_data_but_no_x_data(self):\n lead_time = pd.to_timedelta(\"1d\")\n lookback = pd.to_timedelta(\"2y\")\n prediction_period = pd.to_timedelta(\"180d\")\n max_date = pd.to_datetime(\"2020-01-01\")\n min_date = (\n max_date - prediction_period - lead_time - lookb...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIVEN a set of parameters for a sampler WHEN samples are generated from a customer's purchase history that does not cover a \ full lookback THEN the number of samples generated for this customer is still proportional to the \ time period covered by the customers purchase history and there is at least one \ sample regar...
def test_samples_for_new_customers( self, min_date, max_date, lookback, prediction_period, lead_time, samples_per_lookback, ): min_date = pd.to_datetime(min_date) max_date = pd.to_datetime(max_date) lookback = pd.to_timedelta(lookback) ...
[ "def test_x_data_but_no_y_data(self):\n lead_time = pd.to_timedelta(\"1d\")\n lookback = pd.to_timedelta(\"2y\")\n prediction_period = pd.to_timedelta(\"180d\")\n min_date = pd.to_datetime(\"2018-01-01\")\n max_date = (\n min_date + lookback + lead_time + prediction_per...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIVEN a sampler and dummy data for a customer with no purchases falling into the \ prediction period WHEN samples are generated from that customers data THEN there are no orderpositions marked with `y_include` in the result.
def test_x_data_but_no_y_data(self): lead_time = pd.to_timedelta("1d") lookback = pd.to_timedelta("2y") prediction_period = pd.to_timedelta("180d") min_date = pd.to_datetime("2018-01-01") max_date = ( min_date + lookback + lead_time + prediction_period + pd.Timedelta(...
[ "def test_y_data_but_no_x_data(self):\n lead_time = pd.to_timedelta(\"1d\")\n lookback = pd.to_timedelta(\"2y\")\n prediction_period = pd.to_timedelta(\"180d\")\n max_date = pd.to_datetime(\"2020-01-01\")\n min_date = (\n max_date - prediction_period - lead_time - lookb...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIVEN a sampler and dummy data for a customer with no purchases falling into the \ lookback period WHEN samples are generated from that customers data THEN there are no orderpositions marked with `x_include` in the result.
def test_y_data_but_no_x_data(self): lead_time = pd.to_timedelta("1d") lookback = pd.to_timedelta("2y") prediction_period = pd.to_timedelta("180d") max_date = pd.to_datetime("2020-01-01") min_date = ( max_date - prediction_period - lead_time - lookback - pd.to_timedel...
[ "def test_x_data_but_no_y_data(self):\n lead_time = pd.to_timedelta(\"1d\")\n lookback = pd.to_timedelta(\"2y\")\n prediction_period = pd.to_timedelta(\"180d\")\n min_date = pd.to_datetime(\"2018-01-01\")\n max_date = (\n min_date + lookback + lead_time + prediction_per...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIVEN a sampler and data for a customer whose acquisition date is greater \ than the samplers `max_date` WHEN the sampler is applied to the data THEN it returns an empty dataframe
def test_acquisition_date_greater_max_date(self): customer_data = self.generate_data_for_one_customer( 1, min_date="2016-01-01", # will be overwritten by acquisition date max_date="2020-08-01", acquisition_date="2020-01-01", n_orders=12, ) ...
[ "def generate_data_for_one_customer(\n self,\n id: int,\n min_date: str,\n max_date: str,\n acquisition_date: str = None,\n n_orders: int = None,\n equispaced: bool = False,\n ) -> pd.DataFrame:\n\n if not acquisition_date:\n min_ac_date = pd.to_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIVEN two samplers with the same random seed and the same other parameters WHEN both samlers are applied to the same raw data THEN the result is the same
def test_result_is_reproduceable_between_samplers(self, config, raw_data, seed): first_sampler = BinnedUniformSampler(random_seed=seed, **config) first_result = first_sampler.generate_samples(raw_data) second_sampler = BinnedUniformSampler(random_seed=seed, **config) second_result = sec...
[ "def test_different_seeds_produce_different_outcomes(self, config, raw_data, seed):\n first_sampler = BinnedUniformSampler(random_seed=seed, **config)\n second_sampler = BinnedUniformSampler(random_seed=seed + 1, **config)\n\n first_result = first_sampler.generate_samples(raw_data)\n sec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
GIVEN two samplers with the same parameters but different random seeds WHEN both samplers are applied to the same raw data THEN the result is different
def test_different_seeds_produce_different_outcomes(self, config, raw_data, seed): first_sampler = BinnedUniformSampler(random_seed=seed, **config) second_sampler = BinnedUniformSampler(random_seed=seed + 1, **config) first_result = first_sampler.generate_samples(raw_data) second_result...
[ "def test_result_is_reproduceable_between_samplers(self, config, raw_data, seed):\n first_sampler = BinnedUniformSampler(random_seed=seed, **config)\n first_result = first_sampler.generate_samples(raw_data)\n\n second_sampler = BinnedUniformSampler(random_seed=seed, **config)\n second_re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r"""Decompress PackBits encoded byte string. >>> packbits_decode(b'\x80\x80') NOP b'' >>> packbits_decode(b'\x02123') b'123' >>> packbits_decode( ... b'\xfe\xaa\x02\x80\x00\x2a\xfd\xaa\x03\x80\x00\x2a\x22\xf7\xaa'
def packbits_decode(encoded: bytes, /, *, out=None) -> bytes: out = [] out_extend = out.extend i = 0 try: while True: n = ord(encoded[i : i + 1]) + 1 i += 1 if n > 129: # replicate out_extend(encoded[i : i + 1] * (258 - n)) ...
[ "def msg_unpack(packb_obj):\n return unpackb(packb_obj, object_hook=custom_decode, raw=False)", "def unpackb(packed, **kwargs):\n unpacker = Unpacker(None, **kwargs)\n unpacker.feed(packed)\n try:\n ret = unpacker._unpack()\n except OutOfData:\n raise UnpackValueError(\"Data is not en...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decompress bytes to array of integers. This implementation only handles itemsizes 1, 8, 16, 32, and 64 bits. Install the Imagecodecs package for decoding other integer sizes.
def packints_decode( data: bytes, /, dtype: numpy.dtype | str, bitspersample: int, runlen: int = 0, *, out=None, ) -> numpy.ndarray: if bitspersample == 1: # bitarray data_array = numpy.frombuffer(data, '|B') data_array = numpy.unpackbits(data_array) if runlen % ...
[ "def decode_uleb128_bytes_to_int(byte_array):\n ret = 0\n i = 0\n while i < len(byte_array):\n ret = ret | (((byte_array[i] % 256) & 0x7f) << 7*i)\n i += 1\n return ret", "def ints_from_bytes(byte_string):\r\n return imap(ord, byte_string)", "def ints_from_bytes(byte_string):\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Request that new data be sent to subscribers. In response to this method being called, all of this instance's subscribers will be called, with the report being passed as a single argument to the callable subscriber.
def publish(self, report: T): deads = [] for subscriber in self._subscribers: subscriber_callable = subscriber() if subscriber_callable is not None: subscriber_callable(report) else: deads.append(subscriber) # Trim dead referenc...
[ "def notify(self, data):\n for subscriber in self.subscribers:\n subscriber.update(data)", "def TriggerMeasurementReportRegistration(self):\n pass", "async def subscribe(self, instrument):", "def send(self):\n json_report = None\n try:\n json_report = json.dumps(self.report...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a SearchTree objectification of an SearchTree including the same elements, not necessarily in the same ... order.
def __repr__(self): return 'SearchTree(' + str(self.tolist()) + ')'
[ "def test_tree_eq(self):\n tree = ts.Tree()\n tree.root = ts.Node('a', 2)\n assert tree == copy.copy(tree)\n tree2 = ts.Tree()\n tree2.root = ts.Node('b', 2)\n assert tree != tree2\n tree2.root = ts.Node('a', 1)\n assert tree != tree2\n tree2.root = ts....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns { distinct_id > timestamp } mapping. All events >= timestamp should be ignored by that person This is needed to make pagination work.
def next_page_last_seen(self): result = {} for distinct_id, timestamp in self.last_page_last_seen.items(): if timestamp <= self.next_page_start_timestamp: result[distinct_id] = timestamp for session in self.sessions: result[session["distinct_id"]] = int(s...
[ "def get_id_based_maps(userEventData):\n userMapIdBase = userEventData.map(lambda line: line[0])\\\n .distinct()\\\n .zipWithIndex()\\\n .collectAsMap()\n\n musicMapIdBase = userEventData.map(lambda row: row[1])\\\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function that calls the Random subset selection strategy to sample new subset indices and the corresponding subset weights.
def _resample_subset_indices(self): start = time.time() self.logger.debug("Iteration: {0:d}, requires subset selection. ".format(self.cur_iter)) logging.debug("Random budget: %d", self.budget) subset_indices, _ = self.strategy.select(self.budget) end = time.time() self.lo...
[ "def random_subset(self, perc=0.5):", "def _init_subset_loader(self):\n # All strategies start with random selection\n self.subset_indices = self._init_subset_indices()\n self.subset_weights = torch.ones(self.budget)\n self._refresh_subset_loader()", "def randomSubset(self, subsetSiz...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete analytics DB collection in MongoDB.
def delete_db_collection(self): self.conn.drop_collection(self.colname)
[ "def clear_db():\n mongo = MongoDBConnection()\n\n with mongo:\n db = mongo.connection.media\n db.products.drop()\n db.customers.drop()\n db.rentals.drop()\n LOGGER.info(\"Database Collections have been cleared.\")", "def clear_collections(self):\n with MongoDB() as...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add DASQL/MongoDBQL queries into analytics. A unique record is contained for each (qhash, dhash) pair. For each an array of calltimes is contained.
def add_query(self, query, mongoquery): if isinstance(mongoquery, dict): mongoquery = encode_mongo_query(mongoquery) msg = 'query=%s, mongoquery=%s' % (query, mongoquery) self.logger.debug(msg) dhash = genkey(query) qhash = genkey(mongoquery) now = time.time...
[ "def run_aggregation_queries():\n query_list = []\n for method_name in args.keys():\n requested = args[method_name]\n if requested and isinstance(requested, bool):\n # Only those args supplied as boolean flags will run as queries\n # getattr(foo, 'bar') equals foo.bar \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Standalone method to clean up expired calltimes from query records, since otherwise only the active record is cleaned. This is too expensive to do with every operation, and mongodb does not allow multiple modifications to a single field in a single update operation (ie, we can't do $push and $pull in one update), so it...
def clean_queries(self): self.logger.debug('') now = time.time() #clean out the times array self.col.update({'times': {'$exists': True}}, {'$pull': {'times': {'$lt': now - self.history}}}) #now delete any with no times self.col.remove({'times': ...
[ "def clean_expired(self):\n\t\tl_time = datetime.datetime.now() - datetime.timedelta(seconds = 600)\n\t\tself.get_query_set().filter(last_update__lt=l_time).delete()", "def clean_realtime_data():\n logger.info('BEGIN -- running task: clean_realtime_data')\n date = datetime.datetime.now() - datetime.timedelt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add an analyzer summary, with given analyzer identifier, start and finish times and payload. It is intended that a summary document is deposited on each run of an analyzer (if desirable) and is thereafter immutable.
def add_summary(self, identifier, start, finish, **payload): msg = '(%s, %s->%s, %s)' % (identifier, start, finish, payload) self.logger.debug(msg) # clean-up analyzer records whose start timestamp is too old spec = {'start':{'$lt':time.time()-self.history}, 'analyzer': ...
[ "def add_summary(summary_writer, global_step, tag, value):\n summary = tf.Summary(value=[tf.Summary.Value(tag=tag, simple_value=value)])\n summary_writer.add_summary(summary, global_step)", "def add_new_summary(self, school):\n student_school_summary = StudentSchoolSummary.create(self, school)\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve a summary document for a given analyzeridentifier, optionally specifying a time range.
def get_summary(self, identifier, after=None, before=None, **query): cond = {'analyzer': identifier} if after: cond['start'] = {'$gte': after} if before: cond['finish'] = {'$lte': before} if query: cond.update(query) return list(self.col.find(c...
[ "def documents_get_summary(self,\r\n document_id):\r\n\r\n # Validate required parameters\r\n self.validate_parameters(document_id=document_id)\r\n\r\n # Prepare query URL\r\n _query_builder = Configuration.get_base_uri()\r\n _query_builder += '/signat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add API info to analytics DB. Here args is a dict of API parameters.
def add_api(self, system, query, api, args): orig_query = query if isinstance(query, dict): query = encode_mongo_query(query) msg = '(%s, %s, %s, %s)' % (system, query, api, args) self.logger.debug(msg) # find query record qhash = genkey(query) record...
[ "async def add_api(self, api: \"Api\"):\n schema = api_to_schema(api)\n self.local_schemas[api.meta.name] = schema\n await self.schema_transport.store(api.meta.name, schema, ttl_seconds=self.max_age_seconds)", "def create_api(self, *args, **kw):\r\n blueprint = self.create_api_blueprin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }