query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Sanitizes a string so it could be used as part of a filename. If restricted is set, use a stricter subset of allowed characters. Set is_id if this is not an arbitrary string, but an ID that should be kept if possible.
def sanitize_filename(s, restricted=False, is_id=False): def replace_insane(char): if restricted and char in ACCENT_CHARS: return ACCENT_CHARS[char] if char == '?' or ord(char) < 32 or ord(char) == 127: return '' elif char == '"': return '' if restricted e...
[ "def sanitize_id(dirty_id):\n clean_id = dirty_id.upper()\n clean_id = re.sub(r\"[^A-F0-9]\", \"\", clean_id)\n return clean_id", "def sanitize(s, strict=True):\n allowed = ''.join(\n [\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',\n 'abcdefghijklmnopqrstuvwxyz',\n '012345678...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The timestep() function computes the advective timestep (CFL) constraint. The CFL constraint says that information cannot propagate further than one zone per timestep. We use the driver.cfl parameter to control what fraction of the CFL step we actually take.
def method_compute_timestep(self): myg = self.cc_data.grid cfl = self.rp.get_param("driver.cfl") u = self.cc_data.get_var("x-velocity") v = self.cc_data.get_var("y-velocity") # the timestep is min(dx/|u|, dy|v|) xtmp = ytmp = 1.e33 if not abs(u).max() == 0: ...
[ "def method_compute_timestep(self):\n\n cfl = self.rp.get_param(\"driver.cfl\")\n k = self.rp.get_param(\"diffusion.k\")\n\n # the timestep is min(dx**2/k, dy**2/k)\n xtmp = self.cc_data.grid.dx**2/k\n ytmp = self.cc_data.grid.dy**2/k\n\n self.dt = cfl*min(xtmp, ytmp)", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
preevolve is called before we being the timestepping loop. For the low Mach solver, this does an initial projection on the velocity field and then goes through the full evolution to get the value of phi. The fluid state (rho, u, v) is then reset to values before this evolve.
def preevolve(self): self.in_preevolve = True myg = self.cc_data.grid rho = self.cc_data.get_var("density") u = self.cc_data.get_var("x-velocity") v = self.cc_data.get_var("y-velocity") self.cc_data.fill_BC("density") self.cc_data.fill_BC("x-velocity") ...
[ "def main_pre_displacement(self):\n # Step 1: initialisation of parameters v and D\n \n # advective velocity in each grid element of the soil matrix\n self.v = 1 * self.k\n # diffusivity in each grid element of the soil matrix\n self.D = 1 * self.k / self.c\n \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Opening a Spark session and adding it to the context
def open_spark_session(config: Config): if not config.session_exists("SparkSession"): config.debug("SparkSession", "Opening Spark session") session = SparkSess(config).spark config.add_session("SparkSession", session) config.debug("SparkSession", f"Spark session added to sessions ope...
[ "def initialize_SparkSession():\r\n logging.info(\"INITIALIZING SparkSession...\")\r\n spark = SparkSession \\\r\n .builder \\\r\n .appName(\"Sparkify_Data_Lake\") \\\r\n .getOrCreate()\r\n\r\n return spark", "def create_sparksession():\n return SparkSessio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a random number every 1 second and emit to a socketio instance (broadcast) Ideally to be run in a separate thread?
def randomNumberGenerator(self): #infinite loop of magical random numbers print "Making random numbers" while not thread_stop_event.isSet(): global counter #if counter == 8: # emit('done', {'data': 'finito'}) # break ...
[ "async def generate_random():\n return randint(0, 1024)", "async def getrandom_number() :\n\n # run an infinite loop to continue generating random numbers\n while True: \n await asyncio.sleep(2) # let this task sleep for a while\n yield random.randint(0, sys.maxsize) # yield a random int", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Obtain a piece of HTML for a new progress bar (should be called through AJAX)
def progress_bar_new() -> str: pb_id = int(request.args['pb_id']) has_insights = request.args['has_insights'] == 'true' # Obtain progress bar details. Only show the user@host part if it doesn't equal the user@host of this process # (in case someone connected to this dashboard from another machine or us...
[ "def getProgress(self):", "def RenderProgress(self) -> float:", "def progress_bar(width, total, completed):\n # --------- YOUR CODE HERE --------------\n ratio = (completed / total)\n\n tags = width * ratio\n tags = int(tags)\n s = '#' * tags + '-' * (width - tags)\n print('{} {} '.format(tags...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Starts a new MPIRE dashboard
def start_dashboard(port_range: Sequence = range(8080, 8100)) -> Dict[str, Union[int, str]]: global _DASHBOARD_MANAGER, _DASHBOARD_TQDM_DICT, _DASHBOARD_TQDM_DETAILS_DICT if not DASHBOARD_STARTED_EVENT.is_set(): # Prevent signal from propagating to child process with DisableKeyboardInterruptSi...
[ "def dashboard(self):\n self.program()\n self._url_name = 'gsoc_dashboard'\n return self", "def start_exporter(config, port, interval):\n REGISTRY.register(NovaCollector(config))\n start_http_server(port)\n while True:\n generate_latest(REGISTRY)\n time.sleep(30)", "def start(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connects to an existing MPIRE dashboard
def connect_to_dashboard(manager_port_nr: int, manager_host: Optional[Union[bytes, str]] = None) -> None: global _DASHBOARD_MANAGER, _DASHBOARD_TQDM_DICT, _DASHBOARD_TQDM_DETAILS_DICT if not DASHBOARD_STARTED_EVENT.is_set(): # Set connection variables so we can connect to the right manager mana...
[ "def dashboard(self):\n self.program()\n self._url_name = 'gsoc_dashboard'\n return self", "def open_panel_browser():\n import webbrowser\n # xxx . should open localhost, not the .onion\n webbrowser.open(apaf.hiddenservices[0].hs.hostname)", "def show_dashboard(self):\n secret_cmd = f\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A Gaussian curve. x = Variable t = time shift sigma = standard deviation
def Gaussian(x,t,sigma): return np.exp(-(x-t)**2/(2*sigma**2))
[ "def Gaussian(x, t, sigma):\n return np.exp(-(x - t)**2 / (2 * sigma**2))", "def gaussian(t, params):\n DeprecationWarning(\"Using standard width. Better use gaussian_sigma.\")\n params['sigma'] = Qty(\n value=params['t_final'].get_value()/6,\n min_val=params['t_final'].get_value()/8,\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the broker url based on environment variables
def broker_url(settings): broker = 'amqp://' broker += settings.get('BROKER_USER') or 'guest' broker += ':' + (settings.get('BROKER_PASSWORD') or 'guest') broker += '@' + (settings.get('BROKER_HOST') or 'localhost') broker += ':' + (settings.get('BROKER_PORT') or '5672') return broker
[ "def broker_url(host):\n return '{broker_scheme}://{username}:{password}@{host}:{port}//'.format(host=host, **CONFIG_JOB_QUEUE)", "def get_server_url():\n try:\n url = os.environ['API_HOST']\n # print('[ OK ] Server url loaded: ', url)\n except KeyError:\n url = 'http://localhost:3...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this lets you see whether one privilege is "higher" than another, though it's really meant more for display sorting than determining ability to do something, since possession of a "higher" privilege doesn't necessarily imply the ability to do anything a "lower" privilege can.
def comparator(cls, priv1, priv2): priv1_idx = cls._ORDERED_PRIV_LIST.index(priv1) priv2_idx = cls._ORDERED_PRIV_LIST.index(priv2) if priv1_idx == priv2_idx: return 0 if priv1_idx < priv2_idx: return -1 return 1
[ "def CheckForCurrentUserHigherPrivileges(self, user_id):\n cur = self.conn.cursor()\n cur.execute(\"SELECT type_id FROM users WHERE id = %s\", (user_id,))\n result = cur.fetchone()\n \n if not result:\n self.ReportError(\"User not found.\")\n return None\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns counts of answers per weekdays (first value is Monday etc)
def weekday_activity(frame): data = DataFrame() data['weekday'] = DatetimeIndex(frame.inserted).weekday counts = DataFrame(arange(7)*0) return (counts[0]+data.weekday.value_counts()).fillna(0)
[ "def weekdays(frame):\n\n data = pd.DataFrame()\n data['weekday'] = pd.DatetimeIndex(frame.inserted).weekday\n counts = pd.DataFrame(np.arange(7)*0)\n return (counts[0]+data.weekday.value_counts()).fillna(0)", "def gen_weeklyFrequency(self):\n\n if len(self.fields) == 0:\n return Non...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns number of users for every time period
def number_of_users(frame, frequency = 'M'): times = frame.groupby('user').apply(lambda x: x.inserted.values[0]) times = times.reset_index() times = times.set_index(DatetimeIndex(times[0])) return times.resample(frequency,how=len).user
[ "def users_daily_length(self):\n transactions = self.usertrans\n fr = []\n for user in transactions:\n usertrans = transactions[user]\n for day in usertrans:\n userdaytrans = usertrans[day]\n fr.append(len(userdaytrans))\n return fr", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns number of answers for every time period
def number_of_answers(frame, frequency= 'M'): result = frame.set_index(DatetimeIndex(frame.inserted)) if frequency=='M': result = result.groupby(['user',lambda x: x.year,lambda x: x.month]) elif frequency == 'W': result = result.groupby(['user',lambda x: x.year,lambda x: x.week]) e...
[ "def progress(self):\n answered = self.answer_set.filter(end_to_answer_date__isnull=False).count()\n total = Question.objects.filter(series__in=self.series.all()).count()\n return answered, total", "def get_counts(question_object):\n\n\n def user_to_most_recent_responses(stream_of_resp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
sum days since purchase between all copies of a given book and get an average from today why average? some book copies may be bought at different dates.
def get_days_since_purchase(database, ISBN_list): date_format = "%d/%m/%Y" todays_date = date.today().strftime(date_format) avg_days_since_purchases = [] for book in range(len(ISBN_list)): # print("ISBN: " + str(ISBN_list[book])) sum_days_per_book = 0 copies_found = 0 ...
[ "def getAveragePrice(cryptocurrency_sold, cryptocurrency_bought, date_start, date_end, source_price=0):\n if(not hasattr(cryptocurrency_sold, 'id')):\n cryptocurrency_sold = Cryptocurrency.objects.filter(name=cryptocurrency_sold)[0]\n if(not hasattr(cryptocurrency_bought, 'id')):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a rotatable instance of this hit box. The internal ``PointList`` is transferred directly instead of deepcopied, so care should be taken if using a mutable internal representation.
def create_rotatable( self, angle: float = 0.0, ) -> RotatableHitBox: return RotatableHitBox( self._points, position=self._position, scale=self._scale, angle=angle )
[ "def transformed(\n self: T, rotate: VectorLike = (0, 0, 0), offset: VectorLike = (0, 0, 0)\n ) -> T:\n\n # old api accepted a vector, so we'll check for that.\n if isinstance(rotate, Vector):\n rotate = rotate.toTuple()\n\n if isinstance(offset, Vector):\n offse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
__member_ordinals__ reflects ordinal lookup
def test_member_ordinals(): yield (tools.eq_, BlogPostStatus.__member_ordinals__, {'draft': 0, 'published': 1, 'archived': 2}) for element in BlogPostStatus.__member_ordinals__: yield (tools.assert_is_instance, element, BlogPostStatus)
[ "def getOrdinal(self):\n hint = self['Ordinal Number']\n return (hint, 'Ordinal%d'% hint) # microsoft-convention", "def list_indices(self):", "def memberName(self, p_int): # real signature unknown; restored from __doc__\n return \"\"", "def revmembers(self):\n return [self.des...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
next returns the following enum member
def test_next(): members = tuple(BlogPostStatus) for (number, member) in enumerate(members[:-1], 1): yield (tools.eq_, member.next, members[number]) yield (tools.assert_is_none, members[-1].next)
[ "def get_next(self): \n return self.nextval", "def next(self) -> LogLevel:\n\t\treturn {\n\t\t\tLogLevel.DEBUG:\t\tLogLevel.INFO,\n\t\t\tLogLevel.INFO:\t\tLogLevel.WARNING,\n\t\t\tLogLevel.WARNING:\tLogLevel.ERROR,\n\t\t\tLogLevel.ERROR:\t\tLogLevel.OFF,\n\t\t\tLogLevel.OFF:\t\tLogLevel.DEBUG,\n\t\t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Enums are free to define lookup aliases without affecting ordinals
def test_enum_aliases(): class RedundantStatus(OrderedStrEnum): draft = 'draft' unpublished = 'draft' published = 'published' archived = 'archived' __order__ = 'draft, unpublished, published, archived' yield (tools.eq_, RedundantStatus.draft.ordinal, RedundantStatus.un...
[ "def fixup_enum(self, name, v):\n return self.classifier.enumerations[name][v.lower()]", "def def_enum(dct, name):\n return type(name, (Enum,), dct)", "def _context_enum_name_table(prefix):\n name_table = {}\n for key, value in context.__dict__.iteritems():\n if (key.startswith(prefix...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the last_executed of this WorkflowExecutionStatisticReport.
def last_executed(self, last_executed): self._last_executed = last_executed
[ "def last_failed(self, last_failed):\n\n self._last_failed = last_failed", "def last_updated(self, last_updated):\n\n self._last_updated = last_updated", "def last_processed(self, last_processed):\n\n self._last_processed = last_processed", "def last_edited_by(self, last_edited_by):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the failed of this WorkflowExecutionStatisticReport.
def failed(self, failed): self._failed = failed
[ "def set_test_failed(self):\n self.set_result(Status.FAILED)", "def failed_reason(self, failed_reason):\n self._failed_reason = failed_reason", "def failed_parsed(self, failed_parsed):\n self._failed_parsed = failed_parsed", "def failed_assert(self, failed_assert):\n self._failed_a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Collects all products in catalogue as items in the data list and then prints them using tabulate
def show_all_products(): data = cur.execute("""SELECT productid, productname, unitcost, stock FROM catalogue""").fetchall() print(tabulate(data, headers=["Product ID", "Name", "Cost", "Stock"]))
[ "def show_catalogue(self):\n\n data = cur.execute(\"\"\"SELECT productid, productname, unitcost, stock, location \n FROM catalogue WHERE vendorname = ?\"\"\", (self.vendorname,)).fetchall()\n print(tabulate(data, headers=[\"Product ID\", \"Name\", \"Unit Cost\", \"Stock\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Collects all products with name that match the search term as items in data list, then prints them using tabulate.
def search_catalogue(search_term): data = cur.execute("""SELECT productid, productname, unitcost, stock FROM catalogue WHERE productname = ?""", (search_term, )).fetchall() print(tabulate(data, headers=["Product ID", "Name", "Cost", "Stock"]))
[ "def test_list_products_filtered_by_keyword(self):\n self._require_login(self.user1)\n response = self.client.get('/api/1.0/products/?name=1')\n self.assertEqual(response.status_code, status.HTTP_200_OK)\n self.assertEqual(response.data.__len__(), 1)\n self.assertEqual(response.da...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return whether the value of this value tracker evaluates as true.
def __bool__(self): return bool(self.get_value())
[ "def __bool__(self):\n return True if self.value is True else False", "def is_true(value):\n \n return (value is True)", "def __bool__(self):\n\t\t\n\t\treturn self.__getValueWithType(bool)", "def __bool__(self):\n if self.id or (self.type and self.value):\n return True\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the value of this value tracker to the floor division of the current value by ``d_value``.
def __ifloordiv__(self, d_value: float): self.set_value(self.get_value() // d_value) return self
[ "def __imod__(self, d_value: float):\n self.set_value(self.get_value() % d_value)\n return self", "def setValue(self, value):\n super().setValue(int(round(value / self.step)))", "def __itruediv__(self, d_value: float):\n self.set_value(self.get_value() / d_value)\n return self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the value of this value tracker to the current value modulo ``d_value``.
def __imod__(self, d_value: float): self.set_value(self.get_value() % d_value) return self
[ "def refresh(self):\n\t\tself.value = self.value % self.mod", "def update( self, dval ):\n self.val[:] += dval[:]\n return", "def setValue(self, value):\n super().setValue(int(round(value / self.step)))", "def __itruediv__(self, d_value: float):\n self.set_value(self.get_value() / ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the value of this value tracker to the current value raised to the power of ``d_value``.
def __ipow__(self, d_value: float): self.set_value(self.get_value() ** d_value) return self
[ "def position_d_gain(self, value):\n self._write(MX_POSITION_D_GAIN, value)", "def __imod__(self, d_value: float):\n self.set_value(self.get_value() % d_value)\n return self", "def update( self, dval ):\n self.val[:] += dval[:]\n return", "def setPowerFromDensity(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the value of this value tracker to the current value divided by ``d_value``.
def __itruediv__(self, d_value: float): self.set_value(self.get_value() / d_value) return self
[ "def __imod__(self, d_value: float):\n self.set_value(self.get_value() % d_value)\n return self", "def setValue(self, value):\n super().setValue(int(round(value / self.step)))", "def __ifloordiv__(self, d_value: float):\n self.set_value(self.get_value() // d_value)\n return se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turns self into an interpolation between mobject1 and mobject2.
def interpolate(self, mobject1, mobject2, alpha, path_func=straight_path()): self.set_points(path_func(mobject1.points, mobject2.points, alpha)) return self
[ "def interpolate(self, mobject1, mobject2, alpha):\n #TODO\n Mobject.align_data(mobject1, mobject2)\n for attr in self.get_array_attrs():\n setattr(target_mobject, attr, interpolate(\n getattr(mobject1, attr), \n getattr(mobject2, attr), \n al...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the current value of this value tracker as a complex number. The value is internally stored as a points array [a, b, 0]. This can be accessed directly to represent the value geometrically, see the usage example.
def get_value(self): return complex(*self.points[0, :2])
[ "def complex_value(self) -> global___Expression.ComplexValue:", "def __complex__(self):\n return complex(self.__data)", "def __complex__(self) -> complex:\n return self._translate_in_type(complex, self.integer, self.float_num)", "def __complex__(self): \n return complex(self.real, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets a new complex value to the ComplexValueTracker
def set_value(self, z): z = complex(z) self.points[0, :2] = (z.real, z.imag) return self
[ "def complex_value(self) -> global___Expression.ComplexValue:", "def fill(self, value: complex) -> None:\n self.coeff.fill(value)", "def complex_param(param_object, name, param_desc, default=None):\n if default is None:\n default = complex(0)\n else:\n default = complex(default)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a single NF node to the NFFG.
def add_nf (self): raise NotImplementedError
[ "def addNode(self, G, nlabel, **kwargs):\n G.node(nlabel, **kwargs)", "def do_add_node(self, line=''):\n self.fibbing.add_node()", "def add_node_field(self,name,data,on_exists='fail'):\n if name in np.dtype(self.node_dtype).names:\n if on_exists == 'fail':\n raise ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a single SAP node to the NFFG.
def add_sap (self): raise NotImplementedError
[ "def add(self, node):\n pass", "def add_node(self, node):", "def do_add_node(self, line=''):\n self.fibbing.add_node()", "def addDeviceNode(self, path):\n self.devNodes.append(path)", "def add_node(self, node):\n self.nodes.add(node)", "def addNode (self,node):\r\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a single infrastructure node to the NFFG.
def add_infra (self): raise NotImplementedError
[ "def add_node(self, node):", "def add(self, node):\n pass", "def add_node(self, *args, **kwargs):\n raise NotImplementedError", "def add_node(self, node):\n self.nodes.add(node)", "def add_node(cmd):\n exaconf = read_exaconf(cmd.exaconf)\n exaconf.add_node(nid = cmd.id, priv_net=c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add an SG link to the NFFG.
def add_sglink (self, src, dst): raise NotImplementedError
[ "def add_sglink (self, src_port, dst_port, hop=None, id=None, flowclass=None,\n tag_info=None, delay=None, bandwidth=None):\n if hop is None:\n hop = EdgeSGLink(src=src_port, dst=dst_port, id=id, flowclass=flowclass,\n tag_info=tag_info, bandwidth=bandwidth, delay=dela...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a SG next hop edge to the structure.
def add_sglink (self, src_port, dst_port, hop=None, id=None, flowclass=None, tag_info=None, delay=None, bandwidth=None): if hop is None: hop = EdgeSGLink(src=src_port, dst=dst_port, id=id, flowclass=flowclass, tag_info=tag_info, bandwidth=bandwidth, delay=delay) se...
[ "def add_next(self, next):\n self.next.add(next)", "def add_edge(self, edge):\n src = edge.get_source()\n dest = edge.get_destination()\n #weightEdge = WeightedEdge(src, dest, edge.get_total_distance(), edge.get_outdoor_distance())\n if not (src in self.edges and dest in self.ed...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add metadata with the given `name`.
def add_metadata (self, name, value): self.metadata[name] = value return self
[ "def name_metadata(self, name_metadata):\n\n self._name_metadata = name_metadata", "def add_metadata(self, metadata: dict) -> None:", "def addMetaData(self, name, value):\n metaTag = self.head.addChildElement(MetaData())\n metaTag.setName(name)\n metaTag.setValue(value)\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert the NFFG structure to a NFFGModel format and return the plain text representation.
def dump (self): # Create the model nffg = NFFGModel(id=self.id, name=self.name, service_id=self.service_id, version=self.version, mode=self.mode, metadata=self.metadata) # Load Infras for infra in self.infras: nffg.node_infras.append(infra) # Load SAP...
[ "def __str__(self):\n return 'This is an NGramModel object'", "def __repr__(self):\n s = 'text model name: ' + self.name + '\\n'\n s += ' number of words: ' + str(len(self.words)) + '\\n'\n s += ' number of word lengths: ' + str(len(self.word_lengths)) + '\\n'\n s += ' number...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse NFFG from file given by the path.
def parse_from_file (path): with open(path) as f: return NFFG.parse(f.read())
[ "def getNF_FGFromFile(file_name):\n base_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile( inspect.currentframe() ))[0])).rpartition('/')[0]\n json_data=open(base_folder+\"/graphs/\"+file_name).read()\n nffg_dict = json.loads(json_data)\n ValidateNF_FG().validate(n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if the NFFG is an infrastructure view with Infrastructure nodes.
def is_infrastructure (self): return sum([1 for i in self.infras]) != 0
[ "def check_infrastructure(infrastructure, data):\n if infrastructure == 'way[\"highway\"]':\n if data['type'] == 'way' and 'tags' in data and 'highway' in data['tags']:\n return True\n else:\n return False\n elif infrastructure == 'way[\"railway\"]':\n if data['type'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if the topology does not contain any NF or flowrules need to install or remap.
def is_bare (self): # If there is no VNF if len([v for v in self.nfs]) == 0: fr_sum = sum([sum(1 for fr in i.ports.flowrules) for i in self.infras]) # And there is no flowrule in the ports if fr_sum == 0: sg_sum = len([sg for sg in self.sg_hops]) # And there is not SG hop ...
[ "def has_remap(self):\n return self.mapping1 is not None or self.mapping2 is not None", "def has_all_pacbps(self):\n if not self.pacbps:\n return False \n elif self.edge_count() > len(self.pacbps):\n return False\n else:\n all_pacbps_present = True \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if the topology contains at least one virtualized BiSBiS node.
def is_virtualized (self): return len([i for i in self.infras if i.infra_type not in (self.TYPE_INFRA_SDN_SW, self.TYPE_INFRA_EE, self.TYPE_INFRA_STATIC_EE)]) > 0
[ "def has_node(self, i):\r\n return i in self.nodes", "def all_nodes_provisioned(self):\n ironic_hypervisors = self.os_conn.nova.hypervisors.findall(\n hypervisor_type='ironic')\n if len(ironic_hypervisors) == 0:\n return False\n for hypervisor in ironic_hypervisor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return with an iterator over the out edge data of the given Node not counting the SG and E2E requirement links.
def real_out_edges_iter (self, node): return (data for data in self.network.out_edges_iter(node, data=True) if data[2].type in (self.TYPE_LINK_STATIC, self.TYPE_LINK_DYNAMIC))
[ "def get_exiting_edges(self,node):\n exit_edge_pattern=re.compile('edge_{0}_(?P<end_node>\\w+)_(?P<iterator>\\w+)'.format(node))\n exit_edges=[]\n for index,edge in enumerate(self.edges):\n if re.match(exit_edge_pattern,edge):\n exit_edges.append(edge)\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extend the NFFG model with backward links for STATIC links to fit for the orchestration algorithm.
def duplicate_static_links (self): # Create backward links backwards = [EdgeLink(src=link.dst, dst=link.src, id=str(link.id) + "-back", backward=True, delay=link.delay, bandwidth=link.bandwidth) for u, v, link in self.network.edges_iter(data=T...
[ "def defreeze_model(self):\n # defreeze all parameters\n for param in self.parameters():\n param.requires_grad = True\n # make the whole network trainable\n self.train()", "def l_model_backward(self):\n\n# print(\"initialisation de grad\")\n L = self.layer_nb-...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detect duplicated STATIC links which both are connected to the same Port/Node and have switched source/destination direction to fit for the simplified NFFG dumping. Only leaves one of the links, but that's not defined which one.
def merge_duplicated_links (self): # Collect backward links backwards = [(src, dst, key) for src, dst, key, link in self.network.edges_iter(keys=True, data=True) if ( link.type == Link.STATIC or link.type == Link.DYNAMIC) and link.backward is True] # Dele...
[ "def duplicate_static_links (self):\n # Create backward links\n backwards = [EdgeLink(src=link.dst, dst=link.src, id=str(link.id) + \"-back\",\n backward=True, delay=link.delay,\n bandwidth=link.bandwidth) for u, v, link in\n self.network.edges...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list with the outbound or inbound SGHops from an NF.
def adjacent_sghops (self, nf_id): return [sg for sg in self.sg_hops if sg.src.node.id == nf_id or \ sg.dst.node.id == nf_id]
[ "def get_all_sghop_info (nffg, return_paths=False):\n sg_map = {}\n for i in nffg.infras:\n for p in i.ports:\n for fr in p.flowrules:\n # if fr.external:\n # continue\n if fr.id not in sg_map:\n # The path is unordered!!\n path_of_shop = []\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return an iterator for the NodeNFs which are mapped to the given Infra node.
def running_nfs (self, infra_id): return (self.network.node[id] for id in self.network.neighbors_iter(infra_id) if self.network.node[id].type == Node.NF)
[ "def neighbors_iter(node, topology):\n return topology[node]", "def motif_iter(self, nnode=None):\n if nnode is None:\n nnodes = self.all.keys()\n elif isinstance(nnode, int):\n nnodes = [nnode]\n elif isinstance(nnode, list):\n nnodes = nnode\n\n fo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove every specific Link from the NFFG defined by given ``type``.
def clear_links (self, link_type): return self.network.remove_edges_from( [(u, v, link.id) for u, v, link in self.network.edges_iter(data=True) if link.type == link_type])
[ "def clear_nodes (self, node_type):\n return self.network.remove_nodes_from(\n [id for id, node in self.network.nodes_iter(data=True) if\n node.type == node_type])", "def remove_nodes_with_type(node_type: str, onnx_graph: onnx.onnx_pb.GraphProto):\n input_output_pairs = {}\n for node in onnx_g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove every specific Node from the NFFG defined by given ``type``.
def clear_nodes (self, node_type): return self.network.remove_nodes_from( [id for id, node in self.network.nodes_iter(data=True) if node.type == node_type])
[ "def remove_nodes_with_type(node_type: str, onnx_graph: onnx.onnx_pb.GraphProto):\n input_output_pairs = {}\n for node in onnx_graph.node:\n if node.op_type == node_type:\n input_output_pairs[node.output[0]] = node.input[0]\n onnx_graph.node.remove(node)\n for node in onnx_grap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the deep copy of the NFFG object.
def copy (self): copy = NFFG(id=self.id, name=self.name, version=self.version, mode=self.mode, metadata=self.metadata.copy(), status=self.status) copy.network = self.network.copy() return copy
[ "def get_copy_of_graph(self):\r\n return deepcopy(self)", "def get_deepcopy(self):\r\n return copy.deepcopy(self)", "def deepcopy(self):\n return copy.deepcopy(self)", "def clone(self):\n return _libsbml.GraphicalObject_clone(self)", "def clone(self):\r\n import copy\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates available bandwidth on all the infrastructure links. Stores them in 'availbandwidth' field of the link objects. Modifies the NFFG instance.
def calculate_available_link_res (self, sg_hops_to_be_ignored, mode=MODE_ADD): # set availbandwidth to the maximal value for i, j, k, d in self.network.edges_iter(data=True, keys=True): if d.type == 'STATIC': setattr(self.network[i][j][k], 'availbandwidth', d.bandwidth) # subtract the reserved...
[ "def build_links_capacity(self):\n\n links_capacity = {}\n # Iterates all the edges in the topology formed by switches\n for src, dst in self.topo.keep_only_p4switches().edges:\n bw = self.topo.edges[(src, dst)]['bw']\n # add both directions\n links_capacity[(sr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates available computation and networking resources of the nodes of NFFG. Creates a NodeResource instance for each NodeInfra to store the available resources in the 'availres' attribute added by this fucntion.
def calculate_available_node_res (self, vnfs_to_be_left_in_place={}, mode=MODE_ADD): # add available res attribute to all Infras and subtract the running # NFs` resources from the given max res for n in self.infras: setattr(self.network.node[n.id], 'availres', ...
[ "def set_resources():\n global available_resources\n global EdgenodeResources\n recv_json = request.get_json()\n for resourcename, value in recv_json.items():\n available_resources[resourcename] = value\n # TODO make this better\n EdgenodeResources = [TaskResources(ram=int(available_resourc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes all flowrules, which belong to a given SGHop ID. Compares based on Flowrule.ID and SGHop.ID they should be identical only for the corresponding Flowrules.
def del_flowrules_of_SGHop (self, hop_id_to_del): for n in self.infras: for p in n.ports: for fr in p.flowrules: if fr.id == hop_id_to_del: p.del_flowrule(id=fr.id)
[ "def remove_flows(self, datapath, table_id):\n parser = datapath.ofproto_parser\n ofproto = datapath.ofproto\n empty_match = parser.OFPMatch()\n instructions = []\n flow_mod = self.remove_table_flows(datapath, table_id,\n empty_match, instruc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return with the set of detected domains in the given ``nffg``.
def detect_domains (nffg): return {infra.domain for infra in nffg.infras}
[ "def _get_isns_discovery_domain_list(self):\n return self.__isns_discovery_domain_list", "def dict_of_domains(fc):\r\n # need to find root database (GDB or SDE)\r\n db_root = os.path.dirname(fc)\r\n while db_root[-4:].lower() != '.gdb' and db_root[-4:].lower() != '.sde':\r\n old_db_root = db_ro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search for possible interdomain ports examining ports' metadata and recreate associated SAPs.
def recreate_inter_domain_SAPs (nffg, log=logging.getLogger("SAP-recreate")): for infra in nffg.infras: for port in infra.ports: # Check ports of remained Infra's for SAP ports if port.get_property("type") == "inter-domain": # Found inter-domain SAP port log.debug("Found in...
[ "def update_ports(self):\n \n # fetch only those ports having\n # VID:PID == a valid (VID, PID) pair in target_vid_pid\n ports = []\n\n for valid_pair in self.target_vid_pid:\n vid_pid = valid_pair[0] + ':' + valid_pair[1]\n ports = ports + [p for p in list_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge the given ``nffg`` into the ``base`` NFFG using the given domain name.
def merge_new_domain (cls, base, nffg, log=logging.getLogger("MERGE")): # Get new domain name domain = cls.detect_domains(nffg=nffg) if len(domain) == 0: log.error("No domain detected in new %s!" % nffg) return if len(domain) > 1: log.warning("Multiple domain name detected in new %s!" ...
[ "def clear_domain (cls, base, domain, log=logging.getLogger(\"CLEAN\")):\n base_domain = cls.detect_domains(nffg=base)\n if domain not in base_domain:\n log.warning(\"No node was found in %s with domain: %s for cleanup! \"\n \"Leave NFFG unchanged...\" % (base, domain))\n return bas...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Recreate TAGs for flowrules forwarding traffic from a different domain. In case there is a hop in the service request mapped as a collocated link it might break down to multiple links/flowrules in a lower layer where the links are placed into different domains therefore the match/action field are created without tags b...
def recreate_missing_match_TAGs (cls, nffg, log=logging.getLogger("TAG")): log.debug("Recreate missing TAG matching fields...") for infra in nffg.infras: # Iterate over flowrules of the infra for flowrule in infra.flowrules(): # Get the source in_port of the flowrule from match field ...
[ "def update_tags_for_domain(DomainName=None, TagsToUpdate=None):\n pass", "def rewrite_interdomain_tags (cls, slices,\n log=logging.getLogger(\"adaptation.TAG\")):\n log.debug(\"Calculating inter-domain tags...\")\n\n for nffg in slices:\n log.debug(\"Processing domain...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate and rewrite interdomain tags. Interdomain connections via interdomain SAPs are harmonized here. The abstract tags in flowrules are rewritten to technology specific ones based on the information retrieved from interdomain SAPs.
def rewrite_interdomain_tags (cls, slices, log=logging.getLogger("adaptation.TAG")): log.debug("Calculating inter-domain tags...") for nffg in slices: log.debug("Processing domain %s" % nffg[0]) # collect SAP ports of infra nodes sap_ports = [] for sap in...
[ "def recreate_inter_domain_SAPs (nffg, log=logging.getLogger(\"SAP-recreate\")):\n for infra in nffg.infras:\n for port in infra.ports:\n # Check ports of remained Infra's for SAP ports\n if port.get_property(\"type\") == \"inter-domain\":\n # Found inter-domain SAP port\n lo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search for splitted requirement links in the NFFG. If a link connects interdomain SAPs rebind the link as an e2e requirement link.
def rebind_e2e_req_links (nffg, log=logging.getLogger("REBIND")): log.debug( "Search for requirement link fragments to rebind as e2e requirement...") req_cache = [] def __detect_connected_sap (port): """ Detect if the given port is connected to a SAP. :param port: port object ...
[ "def family_links(entity_list, connection_list):\n\n for subset in combinations(entity_list, 2):\n name1 = str(subset[0][0]).split(\" \")\n name2 = str(subset[1][0]).split(\" \")\n if len(name1) > 1 and len(name2) > 1 and name1[1] == name2[1]:\n connection_list.append([subset[0], ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Detect if the given port is connected to a SAP.
def __detect_connected_sap (port): connected_port = [l.dst for u, v, l in nffg.real_out_edges_iter(port.node.id) if str(l.src.id) == str(port.id)] # If the number of detected nodes is unexpected continue to the next req if len(connected_port) < 1: ...
[ "def is_port_switch_available(self, port):\n try:\n self.cli_send_command(\n command=r'find /sys/class/net/{}/switch -type d'.format(port))\n except UICmdException as e:\n if e.rc == 1:\n return False\n else:\n raise\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the trivial virtual topology a.k.a one BisBis or Single BisBis representation with calculated resources and transferred NF and SAP nodes.
def generate_SBB_representation (nffg, add_sg_hops=False, log=logging.getLogger("SBB")): if nffg is None: log.error("Missing global resource info! Skip OneBisBis generation!") return None # Create Single BiSBiS NFFG log.debug("Generate trivial SingleBiSBiS NFFG...
[ "def generateTopology():\n switches = {}\n interfaces = {}\n links = {}\n return (switches,links)", "def _create_structure_topology_and_geometry(self, design):\n lattice_type = design.lattice_type\n max_vhelix_size = design.max_base_id + 1\n row_list = []\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clean domain by removing initiated NFs and flowrules related to BiSBiS nodes of the given domain
def clear_domain (cls, base, domain, log=logging.getLogger("CLEAN")): base_domain = cls.detect_domains(nffg=base) if domain not in base_domain: log.warning("No node was found in %s with domain: %s for cleanup! " "Leave NFFG unchanged..." % (base, domain)) return base for infra ...
[ "def preProcess(self, variables, domains, constraints, vconstraints): # \"\"\"\n if len(variables) == 1:\n variable = variables[0]\n domain = domains[variable]\n for value in domain[:]:\n if not self(variables, domains, {variable: value}):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the mapped elements of given nffg with given status.
def update_status_info (cls, nffg, status, log=logging.getLogger("UPDATE-STATUS")): log.debug("Add %s status for NFs and Flowrules..." % status) for nf in nffg.nfs: nf.status = status for infra in nffg.infras: for flowrule in infra.flowrules(): flowrule.status =...
[ "def update_nffg_by_status (cls, base, updated,\n log=logging.getLogger(\"UPDATE-DOMAIN-STATUS\")):\n # Update NF status\n base_nfs = {nf.id for nf in base.nfs}\n updated_nfs = {nf.id for nf in updated.nfs}\n log.debug(\"Update status of NF nodes: %s\" % updated_nfs)\n for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update status of the elements of the given ``base`` nffg based on the given ``updated`` nffg.
def update_nffg_by_status (cls, base, updated, log=logging.getLogger("UPDATE-DOMAIN-STATUS")): # Update NF status base_nfs = {nf.id for nf in base.nfs} updated_nfs = {nf.id for nf in updated.nfs} log.debug("Update status of NF nodes: %s" % updated_nfs) for nf in base_nfs...
[ "def update_status_info (cls, nffg, status,\n log=logging.getLogger(\"UPDATE-STATUS\")):\n log.debug(\"Add %s status for NFs and Flowrules...\" % status)\n for nf in nffg.nfs:\n nf.status = status\n for infra in nffg.infras:\n for flowrule in infra.flowrules():\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new NFFG from the given ``nffg`` and filter out the stopped/failed Nfs.
def filter_non_running_NFs (self, nffg, log=logging.getLogger("FILTER")): # TODO implement pass
[ "def generate_difference_of_nffgs (cls, old, new, ignore_infras=False):\n add_nffg = copy.deepcopy(new)\n add_nffg.mode = NFFG.MODE_ADD\n del_nffg = copy.deepcopy(old)\n del_nffg.mode = NFFG.MODE_DEL\n add_nffg = NFFGToolBox.subtract_nffg(add_nffg, old,\n consi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove all the installed NFs, flowrules and dynamic ports from given NFFG.
def remove_deployed_services (cls, nffg, log=logging.getLogger("CLEAN")): for infra in nffg.infras: log.debug("Remove deployed elements from Infra: %s" % infra.id) del_ports = [] del_nfs = [] for src, dst, link in nffg.network.out_edges_iter(data=True): if link.type == NFFG.TYPE_LINK...
[ "def remove_ufd_network_files(self, ports=None):\n self.networkd.clear_settings(exclude_ports=ports)", "def remove_all():\n _plugins.uninstall_all()\n _devices.remove_all()\n _configs.remove_all()", "def _delete_vports(self):\n self._api._remove(self._ixn_vport, self._api.config.ports)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Copies all element from iterator if it is not in target, and merges their port lists.
def _copy_node_type (cls, type_iter, target, log): for obj in type_iter: if obj.id not in target: c_obj = target.add_node(deepcopy(obj)) log.debug("Copy NFFG node: %s" % c_obj) else: for p in obj.ports: if p.id not in target.network.node[obj.id].ports: targe...
[ "def transfer(i_list,target):\n i=0\n _shallow1 = []\n _shallow2 = []\n done = False\n while i < len(i_list):\n if i_list[i] != target or done:\n _shallow2.append(i_list[i])\n i+=1\n continue\n else:\n _shallow1.append(i_list[i])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merges new `NFFG` to target `NFFG` keeping all parameters and copying port object from new. Comparison is done based on object id, resources and requirements are kept unchanged in target.
def merge_nffgs (cls, target, new, log=logging.getLogger("UNION")): # Copy Infras target = cls._copy_node_type_with_flowrules(new.infras, target, log) # Copy NFs target = cls._copy_node_type(new.nfs, target, log) # Copy SAPs target = cls._copy_node_type(new.saps, target, log) # Copy remaini...
[ "def copy (self):\n copy = NFFG(id=self.id, name=self.name, version=self.version,\n mode=self.mode, metadata=self.metadata.copy(),\n status=self.status)\n copy.network = self.network.copy()\n return copy", "def generate_difference_of_nffgs (cls, old, new, ignore_infras=False...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes every (all types of) node from minuend which have higher degree in subtrahend. And removes every (all types of) edge from minuend which are present in subtrahend. Changes minuend, but doesn't change subtrahend.
def subtract_nffg (cls, minuend, subtrahend, consider_vnf_status=False, ignore_infras=False): if ignore_infras: minuend_degrees = {} for nf in minuend.nfs: minuend_degrees[nf.id] = len(minuend.adjacent_sghops(nf.id)) subtrahend_degrees = [(nf.id, len(subtrahend.adjacen...
[ "def remove_subset(minuend, subtrahend):\n difference = copy.deepcopy(minuend)\n for element in subtrahend:\n try:\n difference.remove(ship)\n except:\n pass\n return difference", "def prune_subgraph_automaton(self, subgraph):\n # remove the edge following ID an...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates two NFFG objects which can be used in NFFG.MODE_ADD and NFFG.MODE_DEL operation modes of the mapping algorithm. Doesn't modify input objects. If infra nodes shall be ignored, node degree comparison is only based on SGHops, but the output structure still contains the infras which were in the input.
def generate_difference_of_nffgs (cls, old, new, ignore_infras=False): add_nffg = copy.deepcopy(new) add_nffg.mode = NFFG.MODE_ADD del_nffg = copy.deepcopy(old) del_nffg.mode = NFFG.MODE_DEL add_nffg = NFFGToolBox.subtract_nffg(add_nffg, old, consider_vnf_sta...
[ "def new_graph_without_constants(self) -> Tuple[\"Graph\", Dict[int, int]]:\n new_nodes = dict()\n output_ids = []\n\n new_graph = Graph.from_other(self)\n\n num_removed = 0\n lookup = dict()\n for node in new_graph._nodes.values():\n is_constant = node.type is N...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Interprets the match field of a flowrule as everything is flowclass except "TAG=" and "in_port=" fields. Returns the string to be put into the flowclass field. Hopefully the order of the match segments are kept or irrelevant.
def _extract_flowclass (splitted_matches): flowclass = "" for match in splitted_matches: field, mparam = match.split("=", 1) if field == "flowclass": flowclass += mparam elif field != "TAG" and field != "in_port": flowclass += "".join((field, "=", mparam)) if flowclass == "...
[ "def parse_flow_line(self, line):\n comment = \"\"\n line = line.split(\"#\", 1)\n content = line[0].strip()\n if len(line) > 1:\n comment = line[1].strip()\n if len(content) > 0:\n (out, fullin) = content.split(\":\", 1)\n out = out.strip()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the Flowrule which belongs to the path of SGHop with ID 'fr_id'.
def _get_flowrule_and_its_starting_port (infra, fr_id): for p in infra.ports: for fr in p.flowrules: if fr.id == fr_id: return fr, p else: raise RuntimeError("Couldn't find Flowrule for SGHop %s in Infra %s!" % (fr_id, infra.id))
[ "def get_flowpath(cursor, huc12, fpath):\n cursor.execute(\n \"\"\"\n SELECT fid from flowpaths where huc_12 = %s and fpath = %s\n and scenario = %s\n \"\"\",\n (huc12, fpath, SCENARIO),\n )\n if cursor.rowcount == 0:\n cursor.execute(\n \"\"\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the port object where this Flowrule sends the traffic out.
def _get_output_port_of_flowrule (infra, fr): for action in fr.action.split(";"): comm, arg = action.split("=", 1) if comm == 'output': if "://" in arg: # target-less flow rule -> skip return arg = NFFGToolBox.try_to_convert(arg) return infra.ports[arg] el...
[ "def _get_out_port_id(self):\n return self.__out_port_id", "def OutPort(self):\n if self.force_auto_sync:\n self.get('OutPort')\n return self._OutPort", "def getDestinationPort(self):\n return self.destinationPort", "def find_outport_by_ip(self, dst_ip):\n for port_no...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks whether there is an inconsistencity with Flowrule or SGHop 'fr_sg' and the other flowrules which are part of the SGHop's sequence OR SGHop which is in sg_map. Throws runtime exception if error found. Uses only the common fields of Flowrules and SGHops. 'flowclass' needs to be extracted if 'fr_sg' is not an SGHop...
def _check_flow_consistencity (sg_map, fr_sg): if isinstance(fr_sg, Flowrule): flowclass = NFFGToolBox._extract_flowclass(fr_sg.match.split(";")) else: flowclass = fr_sg.flowclass consistent = True if sg_map[fr_sg.id][2] != flowclass: consistent = False if (sg_map[fr_sg.id][3] is N...
[ "def _sanity_check(G):\n # Compute the number of connected components\n if G.is_directed():\n num_ccs = nx.number_weakly_connected_components(G)\n else:\n num_ccs = nx.number_connected_components(G)\n\n # Rise an error if more than one CC exists\n if num_ccs != 1:\n raise ValueEr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a dictionary keyed by sghopid, data is [PortObjsrc, PortObjdst, SGHop.flowclass, SGHop.bandwidth, SGHop.delay] list of port objects. Source and destination VNFs can be retreived from port references (port.node.id). The function 'recreate_all_sghops' should receive this exact NFFG object and the output of this f...
def get_all_sghop_info (nffg, return_paths=False): sg_map = {} for i in nffg.infras: for p in i.ports: for fr in p.flowrules: # if fr.external: # continue if fr.id not in sg_map: # The path is unordered!! path_of_shop = [] flowcla...
[ "def recreate_all_sghops (nffg):\n sg_map = NFFGToolBox.get_all_sghop_info(nffg)\n for sg_hop_id, data in sg_map.iteritems():\n src, dst, flowclass, bandwidth, delay = data\n if not (src and dst):\n continue\n if not nffg.network.has_edge(src.node.id, dst.node.id, key=sg_hop_id):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extracts the SGHop information from the input NFFG, and creates the SGHop objects in the NFFG.
def recreate_all_sghops (nffg): sg_map = NFFGToolBox.get_all_sghop_info(nffg) for sg_hop_id, data in sg_map.iteritems(): src, dst, flowclass, bandwidth, delay = data if not (src and dst): continue if not nffg.network.has_edge(src.node.id, dst.node.id, key=sg_hop_id): nffg.add_s...
[ "def get_all_sghop_info (nffg, return_paths=False):\n sg_map = {}\n for i in nffg.infras:\n for p in i.ports:\n for fr in p.flowrules:\n # if fr.external:\n # continue\n if fr.id not in sg_map:\n # The path is unordered!!\n path_of_shop = []\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Redirect flowrules from `from` to `to_port` handling match/action fields.
def redirect_flowrules (from_port, to_port, infra, mark_external=False, log=logging.getLogger("MOVE")): # Flowrules pointing to the from_port -> rewrite output reference in action for port in infra.ports: for fr in port.flowrules: output = fr.action.split(';', 1)[0].split...
[ "def port_forward(srcport, destport, rule=None):\n return NotImplemented", "def install_rule_destport (conn, tcpport, port):\n\tmsg = of.ofp_flow_mod()\n\tmsg.match.nw_proto = 6\n\tmsg.match.dl_type = 0x0800\n\tmsg.match.tp_dst = tcpport\n\tmsg.actions.append(of.ofp_action_output(port = port))\n\tconn.send(msg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge detected external ports in nodes of given `nffg` and only leave the original SAP port.
def merge_external_ports (cls, nffg, log=logging.getLogger("MERGE")): for infra in nffg.infras: for ext_port in [p for p in infra.ports if p.role == "EXTERNAL"]: log.debug("Found external port: %s" % ext_port) # Collect ports with the same SAP tag origin_port = [p for p in infra.ports ...
[ "def recreate_inter_domain_SAPs (nffg, log=logging.getLogger(\"SAP-recreate\")):\n for infra in nffg.infras:\n for port in infra.ports:\n # Check ports of remained Infra's for SAP ports\n if port.get_property(\"type\") == \"inter-domain\":\n # Found inter-domain SAP port\n lo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return true if there is a Static outbound or inbound EdgeLink, false if there is a Dynamic outbound or inbound link, throws exception if borth, or warning if multiple of the same type.
def isStaticInfraPort (cls, G, p): static_link_found = False dynamic_link_found = False for edge_func, src_or_dst in ((G.out_edges_iter, 'src'), (G.in_edges_iter, 'dst')): for i, j, k, link in edge_func([p.node.id], data=True, keys=True): src_or_dst_port = get...
[ "def is_link_graph(self):\n return self.number_of_nodes == 2", "def is_cross_onap_link(self, logical_link):\n for relationship in logical_link[\"relationship-list\"][\"relationship\"]:\n if relationship[\"related-to\"] == \"ext-aai-network\":\n return True\n return F...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If history_table_name is Not None and its not created yet by a provided template, create it here
def create_hist_table(sc, table_name, history_table_name): tgt_db, tgt_tbl = table_name.split(".") hist_db, hist_tbl = history_table_name.split(".") hist_db_tables = [_i.name for _i in sc.catalog.listTables(hist_db)] if hist_tbl not in hist_db_tables: ddl = sc.sql("show create table {}".format...
[ "def _create_table_if_not_exist(self, table_name: str) -> None:\n # check if the fire_history table exists\n # if the pipeline is run for the first time\n # then the fire_history table will not exist\n is_table_exist = table_name in self.existing_tables\n # table is the result of ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This will create and purge history table. If no history table is passed then still the old S3 data needs to be removed, because every time current table points to a new location
def purge_history(sc, table, history_table, keep_latest_n): if sys.platform != "darwin": # remove the corresponding s3 location - safety check that the location is a run_id location in particular buckets. # wants to make sure we are deleting s3 path with expected pattern. # Expected S3 path...
[ "def clear_sold_history_cache(self) -> None:\n self._cache = {}", "def deleteTableHistory(self, when, writeToDb=False):\n sql = (\"DELETE FROM snowflake_test.table_history \" +\n \"WHERE query_date = '%s' \" % when.date())\n if writeToDb:\n self.rawQuery(sql)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shows a list with all subrecipes of the user, ordered by name. Also, if the search form is submitted, it redirects to the search_by_name route.
def sort_by_name(arg): form = SearchForm() if form.validate_on_submit(): return redirect(url_for( 'subrecipes.search_by_name', arg=form.name.data )) return render_template( 'overview/subrecipe.html', title='Subrecetas', recipe_form=SearchRecipeForm(), ...
[ "def my_recipes(username):\n logged_user = {\"created_by\": username}\n my_recipes = mongo.db.recipes.find(logged_user).sort(\"_id\", -1)\n username = mongo.db.users.find_one(\n {\"username\": session[\"user\"]})[\"username\"]\n\n if session[\"user\"]:\n return render_template(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes the attributes of a new Java method.
def __init__(self, exact=None, javadocs=None, modifiers=None, return_type=None, name=None, params=None, exceptions=None, body=None, indent=4): super(JavaMethod, self).__init__(exact=exact, javadocs=javadocs, modifiers=modifiers, name=nam...
[ "def __init__(self, key, method_name):\n Determinant.check_init(key, method_name)\n self.key = key\n self.method_name = method_name", "def BaseConstructorArgs(self) -> CodeExpressionCollection:", "def __init__(self, *args):\n _snap.TAttr_swiginit(self, _snap.new_TAttr(*args))", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the type of the return value of this method
def set_return_type(self, return_type, this_class_name=''): retval = None if not return_type else self.add_dependency(return_type, this_class_name) self._set_instance_data('return_type', retval)
[ "def return_type(self, return_type):\n\n self._return_type = return_type", "def return_type(self) -> global___Type:", "def return_type(self):\r\n return Type(self._ptr.getReturnType())", "def return_type(self) -> str:\n return self._return_type", "def return_type(self):\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a parameter to this method. The argument type is added to list of dependencies. param_type String representation of the argument type param_name String representation of the argument name
def add_parameter(self, param_type, param_name, this_class_name=''): self._set_instance_data('parameters', ' '.join([self.add_dependency(param_type, this_class_name), param_name]))
[ "def addParam(cls, name, param_type=StringType, required=False):\n cls.parameters[name] = {\"type\":param_type, \"required\":required}", "def addParams(self, type, param):\n pass", "def add_param(self, param):\n self._params.append(param)\n self.add_decompostion(param)", "def _add_para...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds line to method body
def add_line(self, line): self._set_instance_data('body', self.indent + ' ' * 4 + line)
[ "def add(self, line):\n self.body.append(line)", "def log(self, line):\n self.body.append(line)", "def add_line(self, line):\n self.code.extend([\" \" * self.indent_level, line, \"\\n\"])", "def addLine(self, line = '\\n'):\n self.script += line + '\\n'\n return", "def bod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Wrap each generator invocation with the context manager factory. The input should be a function that returns a context manager, not a context manager itself, to handle oneshot context managers.
def _wrap_generator(ctx_factory, func): @functools.wraps(func) def generator_context(*args, **kwargs): gen = func(*args, **kwargs) # Generators are suspended and unsuspended at `yield`, hence we # make sure the grad mode is properly set every time the execution # flow returns in...
[ "def contextmanager(func):\n @wraps(func)\n def helper(*args, **kwds):\n return _GeneratorContextManager(func, *args, **kwds)\n return helper", "def as_contextmanager(self, *context):\n self.setup(*context)\n yield self\n self.teardown()", "def _as_context_ma...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pseudonymize value with salt, using HMACSHA256 encoding
def pseudonymize(value, salt=SALT_KEY): # NOTE: Here we must bypass empty or None value as # it will introduce specific hash value if value is None or value is np.nan or value == '': return None return hmac.new( key=salt.encode('utf-8'), # La clé msg=str(value).encode('...
[ "def make_salt() -> str:\n return secrets.token_hex(SALT_LENGTH)", "def ssha(val, salt):\n ecrypt = hashlib.sha1(val.encode())\n ecrypt.update(salt)\n return ecrypt", "def get_salt():\n salt = os.urandom(16)\n return binascii.hexlify(salt).upper()", "def create_salt():\n return sha1(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method to retrieve a list of team instances from a text file
def get_teams_from_text(file_name, index): teams = [] List = open("teams/" + file_name + ".txt",'r').read().splitlines() j = 0 for i in range(0,len(List)): if j < index: dummy_team = Team(List[i], "Wappen") teams.append(dummy_team) j = j+1 return teams
[ "def from_file(cls, filename):\n teams = []\n with open(filename) as file:\n for line in file:\n if not line.strip(): # skip empty lines\n continue\n teams.append(line.strip())\n return cls(teams)", "def load_teams():\n team_list...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method compares the name of an instance Team to names of a list of instances Team
def eq_name(team_a,team_list): for i in range (0,len(team_list)): if team_a.name == team_list[i].name: return True else: return False
[ "def test__TeamMembershipState__name():\n for instance in TeamMembershipState.INSTANCES.values():\n vampytest.assert_instance(instance.name, str)", "def test_list_teams(self):\n pass", "def update_team_names(self):\n\n\t\tprint(\"\\nTEAM NAME UPDATE\")\n\t\tteam_names = []\n\n\t\twith open('Own...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
With this function, it is possible to set the league of a list of instances of Team
def set_league(teams, l): #~ print teams[0].name if l>0 and l<10: for team in teams: team.league = l else: print("Error! Only leagues between 1 and 9 can be set.") return teams
[ "def update_teams(self, user):", "def teams(self, teams):\n\n self._teams = teams", "def schedule_set(teams):\n for day in league:\n for num in day:\n num[0] = teams[num[0]]\n num[1] = teams[num[1]]\n show_schedule()\n return league", "def update_league(local_team,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints the table of top scoring players
def print_top_scorers(teams): all_players = [] for i in range(0,len(teams)): for j in range(0, len(teams[i].players)): all_players.append(teams[i].players[j]) players_sorted_score = sorted(all_players, key=attrgetter('shot_goals'), reverse=True) for player in players_sorted_score: if player.shot_goa...
[ "def print_scoreboard():\n data = db.get_scoreboard()\n headers = [\"Team #\", \"Name\", \"Score\"]\n content = tabulate(data, headers)\n\n return \"```\\n\" + content + \"\\n```\"", "def print_stats(stats):\n\n print(\"\\nNFL Top 20 Players' Stats\\n\")\n # Print header border\n print(\"+-{:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
adding books to cart
def cart_add(request,book_id): cart = Cart(request) book = get_object_or_404(Book, id=book_id) form = CartAddProductForm(request.POST) if book.get_discounted_price()>0 : if form.is_valid(): cd = form.cleaned_data if book.has_inventory(cd['quantity']):...
[ "def add_book(self, books):\n shelf.books_list.append(books)\n #return shelf.books_list", "def add_cart():\n user_id = current_user.id\n book_id = request.json['book_id']\n quantity = request.json['quantity']\n\n cart_service = CartService()\n\n cart_service.cart_add(user_id, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
removing the book from cart by pressing bottum
def cart_remove(request, book_id): cart = Cart(request) book = get_object_or_404(Book, id=book_id) cart.remove(book) return redirect('cart_detail')
[ "def remove_from_cart(request, pk):\n book = get_object_or_404(Book, pk=pk)\n order_qs = Order.objects.filter(user=request.user, paid=False)\n if order_qs.exists():\n order = order_qs[0]\n if OrderBook.objects.filter(book=book, order=order).exists():\n order_book = OrderBook.object...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add attribute to a components symbol
def add_symbol_attribute(self, symbol_attribute): self.symbol_attributes.append(symbol_attribute)
[ "def add_attribute(self):\n pass", "def add_attribute(node_proto, name, value):\n node_proto.attribute.extend([make_attribute(name, value)])", "def add_attribute(a, name, other):\n raise TypeError(\"can't add new attribute\")", "def add_attribute(self, name, value):\n\t\tif name in self.__attr_ha...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the instance id
def get_instance_id(self): return self.instance_id
[ "def instance_id(self) -> str:\n return pulumi.get(self, \"instance_id\")", "def instance_id(self):\n return self.__instance_id", "def instance_id(self):\n return self._instance_id", "def instance_identifier(self):\n return self._instance_identifier", "def unique_instance_id(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Has pet already departed?
def already_departed( pet_id: int, all_pets: typing.List[pet_record.PetRecord] ) -> bool: all_instances_of_pet_id = (p for p in all_pets if p.animal_id == pet_id) for pet in all_instances_of_pet_id: if not pet.departure: # At least one departure not populated. Pet has not departed. ...
[ "def petExist(animal, pet_id):\n return Animal.objects.filter(pk = pet_id).exists()", "def test_create_a_pet(self):\n pet = Pet(0, \"fido\", \"dog\", False)\n self.assertNotEqual(pet, None)\n self.assertEqual(pet.id, 0)\n self.assertEqual(pet.name, \"fido\")\n self.assertEqua...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Classify current pets as new or existing.
def classify_pets( current_pets: typing.List[int], all_pets: typing.List[pet_record.PetRecord], photos_path: str ) -> typing.Tuple[ typing.List[int], typing.List[int], typing.List[int], typing.List[int] ]: existing = [] new = [] photoless = [] all_pet_ids = set((p.animal_id f...
[ "def add_pet(self, name, species):\n # Write your code here\n p = None\n if species==\"dog\":\n p = Dog(name)\n elif species==\"cat\":\n p = Cat(name)\n else:\n p = Pet(name)\n self.pets.append(p)", "def get_pet(self):\r\n return Ca...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set departure time for adopted pets.
def update_adopted_pets( all_pets: typing.List[pet_record.PetRecord], adopted_pets: typing.List[int], today: datetime.date ) -> None: for adopted in adopted_pets: all_instances_of_adopted = (p for p in all_pets if p.animal_id == adopted) for pet in all_instances_of_adopted: i...
[ "def departure(self, when: datetime.date):\n if self._departure:\n logging.warning(\n f'Overwriting departure date of {self._departure.isoformat()} '\n f'for pet {self.animal_id} with {when.isoformat()}'\n )\n\n self._departure = when\n if sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a random datetime between `start` and `end`
def random_date(start, end): return start + datetime.timedelta( # Get a random amount of seconds between `start` and `end` seconds=random.randint(0, int((end - start).total_seconds())), )
[ "def random_date(start, end):\n return start + datetime.timedelta(\n # Get a random amount of seconds between `start` and `end`\n seconds=random.randint(0, int((end - start).total_seconds())),\n )", "def random_datetime(start: datetime, end: datetime) -> datetime:\n time_delta = (end - star...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }