query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
The version(GUID) of secret in Key Vault. | def secret_version(self) -> pulumi.Input[str]:
return pulumi.get(self, "secret_version") | [
"def get_secret(secret_id, version_id=\"latest\"):\n # Build the resource name of the secret version.\n name = sm_client.secret_version_path(project_id, secret_id, version_id)\n\n # Access the secret version.\n response = sm_client.access_secret_version(name)\n\n payload = response.payload.data.decod... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The additional latency in milliseconds for probes to fall into the lowest latency bucket | def additional_latency_in_milliseconds(self) -> Optional[pulumi.Input[int]]:
return pulumi.get(self, "additional_latency_in_milliseconds") | [
"def latency(self):\n # type: () -> int\n return self._latency",
"def latency(self):\n kokoro = self.kokoro\n if kokoro is None:\n latency = Kokoro.DEFAULT_LATENCY\n else:\n latency = kokoro.latency\n return latency",
"def calc_ras_latency( self )... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Defines a managed rule group override setting. | def __init__(__self__, *,
rule_group_name: pulumi.Input[str],
rules: Optional[pulumi.Input[Sequence[pulumi.Input['ManagedRuleOverrideArgs']]]] = None):
pulumi.set(__self__, "rule_group_name", rule_group_name)
if rules is not None:
pulumi.set(__self__, "rules... | [
"def origin_group_override(self) -> Optional[pulumi.Input['OriginGroupOverrideArgs']]:\n return pulumi.get(self, \"origin_group_override\")",
"def __init__(__self__, *,\n name: pulumi.Input[str],\n parameters: pulumi.Input['OriginGroupOverrideActionParametersArgs']):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Identifier for the managed rule. | def rule_id(self) -> pulumi.Input[str]:
return pulumi.get(self, "rule_id") | [
"def grammar_rule_api_name(rule):\n return names.Name.from_lower(rule + '_rule')",
"def identifier(self) -> str:\n if not self._identifier:\n self.load()\n return self._identifier",
"def _get_id(self) -> \"std::string\" :\n return _core.Property__get_id(self)",
"def conf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Defines the list of managed rule sets for the policy. | def __init__(__self__, *,
managed_rule_sets: Optional[pulumi.Input[Sequence[pulumi.Input['ManagedRuleSetArgs']]]] = None):
if managed_rule_sets is not None:
pulumi.set(__self__, "managed_rule_sets", managed_rule_sets) | [
"async def rulesets(ctx: commands.Context, choice=None):\n if choice is None:\n embed = discord.Embed()\n for ruleset_name, config in state[\"rulesets\"].items():\n embed.add_field(\n name=\"`{}`\".format(ruleset_name),\n value=\"Map pool: `{}`, order: `{}`\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Defines the rule set type to use. | def rule_set_type(self) -> pulumi.Input[str]:
return pulumi.get(self, "rule_set_type") | [
"def rule_type(self) -> pulumi.Input[Union[str, 'GovernanceRuleType']]:\n return pulumi.get(self, \"rule_type\")",
"def set_type(self,atype):\n return _ldns.ldns_dnssec_rrsets_set_type(self,atype)\n #parameters: ldns_dnssec_rrsets *,ldns_rr_type,\n #retvals: ldns_status",
"def set_ty... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Defines the version of the rule set to use. | def rule_set_version(self) -> pulumi.Input[str]:
return pulumi.get(self, "rule_set_version") | [
"def from_specifier_set(version):\n pass",
"def from_specifier_set(version):\n if len(version) > 1:\n return Config.any_version\n return InstalledVersion.strip_operators(str(version))",
"def version_satisfies(cls, req):\n\n if req not in cls.__version_satisfies:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Type of managed service identity (where both SystemAssigned and UserAssigned types are allowed). | def type(self) -> pulumi.Input[Union[str, 'ManagedServiceIdentityType']]:
return pulumi.get(self, "type") | [
"def aad_service_principal_credential_type(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"aad_service_principal_credential_type\")",
"def os_type_id(self):\n ret = self._get_attr(\"OSTypeId\")\n return ret",
"def type(self):\n return self._service_type",
"def is_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Match variable to compare against. | def match_variable(self) -> pulumi.Input[Union[str, 'WafMatchVariable']]:
return pulumi.get(self, "match_variable") | [
"def find_solution_values_match(self, tv, qv) :\n if is_any_var(tv) :\n if is_out_lit_var(tv) :\n # if the pattern is an out_lit_var, qv must be a lit_var or a literal\n if is_lit_var(qv):\n return {tv : qv}\n elif is_any_var(qv) :\n return False\n else :\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Defines the origin group override action for the delivery rule. | def __init__(__self__, *,
name: pulumi.Input[str],
parameters: pulumi.Input['OriginGroupOverrideActionParametersArgs']):
pulumi.set(__self__, "name", 'OriginGroupOverride')
pulumi.set(__self__, "parameters", parameters) | [
"def origin_group_override(self) -> Optional[pulumi.Input['OriginGroupOverrideArgs']]:\n return pulumi.get(self, \"origin_group_override\")",
"def rule_action_overrides(self) -> Optional[Sequence['outputs.WebAclRuleActionOverride']]:\n return pulumi.get(self, \"rule_action_overrides\")",
"def appl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Protocol this rule will use when forwarding traffic to backends. | def forwarding_protocol(self) -> Optional[pulumi.Input[Union[str, 'ForwardingProtocol']]]:
return pulumi.get(self, "forwarding_protocol") | [
"def do_change_protocol(self, args):\n lb = self.findlb(args.loadbalancer, readonly=False)\n lb.protocol = args.protocol\n lb.update()",
"def __getProtocolBinding (self):\n return self.__protocolBinding",
"def loadbalancer_protocol(self) -> str:\n return pulumi.get(self, \"loa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the action type is block, customer can override the response body. The body must be specified in base64 encoding. | def default_custom_block_response_body(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "default_custom_block_response_body") | [
"def send_raw(\n self, body: str, *, content_type: str = None, content_encoding: str = None\n ):",
"def setBody(self, body, title='', is_error=False, lock=None):\n # allow locking of the body in the same way as the status\n if self._locked_body:\n return\n elif lock:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If the action type is block, this field defines the default customer overridable http response status code. | def default_custom_block_response_status_code(self) -> Optional[pulumi.Input[int]]:
return pulumi.get(self, "default_custom_block_response_status_code") | [
"def default_success_code(self):\n return self.method.default_success_code",
"def http_status_code(self):\n return self._status_code",
"def status_code(self) -> int:\n if self.status_code == 0:\n raise NotImplementedError\n return self.status_code",
"def expected_status_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If action type is redirect, this field represents the default redirect URL for the client. | def default_redirect_url(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "default_redirect_url") | [
"def get_default_redirect_uri(self, client_id, request, *args, **kwargs):\n return None",
"def get_default_redirect_uri(self, client_id, request, *args, **kwargs):\r\n request.client = request.client or self._clientgetter(client_id)\r\n redirect_uri = request.client.default_redirect_uri\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Describes if it is in detection mode or prevention mode at policy level. | def mode(self) -> Optional[pulumi.Input[Union[str, 'PolicyMode']]]:
return pulumi.get(self, "mode") | [
"def is_policy(self):\n return self._policy",
"def _get_robust_status(self, mode):\n if mode in {'george', 'random_gdro', 'superclass_gdro', 'true_subclass_gdro'}:\n return True\n elif mode == 'erm':\n return False\n raise ValueError(\n 'mode {mode} not... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Defines contents of rate limit rules | def __init__(__self__, *,
rules: Optional[pulumi.Input[Sequence[pulumi.Input['RateLimitRuleArgs']]]] = None):
if rules is not None:
pulumi.set(__self__, "rules", rules) | [
"def ratelimits(self, irc, msg, args):\n # before we do anything, make sure we have a twitterApi object.\n if not self.twitterApi:\n irc.reply(\n \"ERROR: Twitter is not authorized. Please check logs before running \"\n \"this command.\"\n )\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List of match conditions. | def match_conditions(self) -> pulumi.Input[Sequence[pulumi.Input['MatchConditionArgs']]]:
return pulumi.get(self, "match_conditions") | [
"def match_expressions(self) -> Optional[List[\"LabelSelectorRequirement\"]]:\n return self.__match_expressions",
"def get_conditions():\n return _conditions.keys()",
"def rule_matches(self):\n return self._rule_matches",
"def _get_matchers(cls):\n return [re.compile('^' + \\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Defines rate limit duration. Default is 1 minute. | def rate_limit_duration_in_minutes(self) -> pulumi.Input[int]:
return pulumi.get(self, "rate_limit_duration_in_minutes") | [
"def duration_minutes(self, duration: int) -> None:\n self._duration = duration",
"def rate_limit_threshold(self) -> pulumi.Input[int]:\n return pulumi.get(self, \"rate_limit_threshold\")",
"def duration(self, duration):\n self._duration = duration",
"async def set_frequency_duration_minutes(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Defines rate limit threshold. | def rate_limit_threshold(self) -> pulumi.Input[int]:
return pulumi.get(self, "rate_limit_threshold") | [
"def check_rate_limiting():\n if not flaskbb_config[\"AUTH_RATELIMIT_ENABLED\"]:\n return None\n return limiter.check()",
"def set_threshold(self, threshold):\n self.threshold = threshold",
"def __init__(self, threshold=0.5):\n self.threshold = threshold",
"def InitialTh... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Describes if the custom rule is in enabled or disabled state. Defaults to Enabled if not specified. | def enabled_state(self) -> Optional[pulumi.Input[Union[str, 'CustomRuleEnabledState']]]:
return pulumi.get(self, "enabled_state") | [
"def GetEnabled(self):\n return self._is_enabled",
"def is_custom_mode_enabled(base_mode,custom_mode):\n if base_mode & mavlink.MAV_MODE_FLAG_CUSTOM_MODE_ENABLED:\n return True\n else:\n return False",
"def get_enabled(self):\n\n return self.proxied.enabled",
"def is_enabled(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The list of Http status code ranges that are considered as server errors for origin and it is marked as unhealthy. | def http_error_ranges(self) -> Optional[pulumi.Input[Sequence[pulumi.Input['HttpErrorRangeParametersArgs']]]]:
return pulumi.get(self, "http_error_ranges") | [
"def validate_fail_on_code(self):\n fail_on_list = self.task.get(\"fail_on\", [])\n for fail_on in fail_on_list:\n code = fail_on.get(\"code\")\n if code and code == self._response_code():\n return self._response(\n \"FAILED\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Type of response errors for real user requests for which origin will be deemed unhealthy | def response_based_detected_error_types(self) -> Optional[pulumi.Input['ResponseBasedDetectedErrorTypes']]:
return pulumi.get(self, "response_based_detected_error_types") | [
"def test_08_http_unexceptional(self):\n with self.app.test_client() as client:\n client.get(\"/http/500\")\n assert hasattr(g, \"exceptional\") is False",
"def _adapt_response(self, response):\n errors, meta = super(ServerError, self)._adapt_response(response)\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The percentage of failed requests in the sample where failover should trigger. | def response_based_failover_threshold_percentage(self) -> Optional[pulumi.Input[int]]:
return pulumi.get(self, "response_based_failover_threshold_percentage") | [
"def failure_rate(self) -> float:\n return self._failure_rate",
"def get_job_failure_percent(self):\n return (self.failure['Njobs'] / self.total_Njobs) * 100. if self.total_Njobs > 0 \\\n else 0.",
"def csnonhttpprobehitrate(self) :\n\t\ttry :\n\t\t\treturn self._csnonhttpprobehitrate\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The caching configuration associated with this rule. To disable caching, do not provide a cacheConfiguration object. | def cache_configuration(self) -> Optional[pulumi.Input['CacheConfigurationArgs']]:
return pulumi.get(self, "cache_configuration") | [
"def getConfigCacheID(self):\n return getattr(self.data.application.configuration, 'retrieveConfigUrl', None)",
"def cache_enable(self):\n return self.param_info.cache_enable",
"def _cache(self):\n return self.__cache",
"def get_configuration(self):\n return get_configuration_from_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A reference to the origin group override configuration. Leave empty to use the default origin group on route. | def origin_group_override(self) -> Optional[pulumi.Input['OriginGroupOverrideArgs']]:
return pulumi.get(self, "origin_group_override") | [
"def __init__(__self__, *,\n name: pulumi.Input[str],\n parameters: pulumi.Input['OriginGroupOverrideActionParametersArgs']):\n pulumi.set(__self__, \"name\", 'OriginGroupOverride')\n pulumi.set(__self__, \"parameters\", parameters)",
"def cdn_frontdoor_origin_group_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The location of the shared private link resource | def private_link_location(self) -> Optional[pulumi.Input[str]]:
return pulumi.get(self, "private_link_location") | [
"def file_share_witness_location(self) -> str:\n return pulumi.get(self, \"file_share_witness_location\")",
"def gen_dir_share_link(token):\n return gen_shared_link(token, 'd')",
"def portal_path(): # pragma: no cover",
"def location(self) -> ConsoleLinkLocation:\n return self.__location",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Status of the shared private link resource. Can be Pending, Approved, Rejected, Disconnected, or Timeout. | def status(self) -> Optional[pulumi.Input['SharedPrivateLinkResourceStatus']]:
return pulumi.get(self, "status") | [
"def get_link_status(self, link_id: ObjectId) -> Any:\n link = self.get_unsafe_link_document(link_id)\n return link['status']",
"def share_subscription_status(self) -> str:\n return pulumi.get(self, \"share_subscription_status\")",
"def get_status (self):\n return self.__status",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The redirect type the rule will use when redirecting traffic. | def redirect_type(self) -> pulumi.Input[Union[str, 'RedirectType']]:
return pulumi.get(self, "redirect_type") | [
"def rule_type(self) -> pulumi.Input[Union[str, 'GovernanceRuleType']]:\n return pulumi.get(self, \"rule_type\")",
"def validate_ruletype(ruletype):\n\n VALID_RULETYPES = (\"SYSTEM\", \"FORWARD\")\n\n if ruletype not in VALID_RULETYPES:\n raise ValueError(\"Rule type must be one of: %s\" % \",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Whether to preserve unmatched path. Default value is true. | def preserve_unmatched_path(self) -> Optional[pulumi.Input[bool]]:
return pulumi.get(self, "preserve_unmatched_path") | [
"def _ignorePath(self, name, fullpath, isdir):\r\n # Ignore the metadata and tree cache data when indexing\r\n if name == self._mdFile or name == self._treeFile:\r\n return True\r\n else:\r\n return False",
"def same_path(self, other):\n return self.expand() == ot... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Defines the url signing action for the delivery rule. | def __init__(__self__, *,
name: pulumi.Input[str],
parameters: pulumi.Input['UrlSigningActionParametersArgs']):
pulumi.set(__self__, "name", 'UrlSigning')
pulumi.set(__self__, "parameters", parameters) | [
"def _action_url(base: str,\n subpath: str,\n version_path: str,\n action_type: str = None) -> str:",
"def submit_url(self, **kwargs):\n\n rule = self.get_submit_url_rule()\n return url_for(rule, **kwargs)",
"def get_submit_url_rule(self):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes all tournament competitors from the database. | def deleteCompetitors():
dbconnection = connect()
dbcursor = dbconnection.cursor()
dbcursor.execute("DELETE FROM competitors;")
dbconnection.commit()
dbconnection.close() | [
"def deletePlayers():\n\n # Remove relational data\n deleteTournamentPlayers()\n\n # Remove all the player records from the database.\n db_connect, cursor = connect()\n query = (\"DELETE FROM players;\")\n cursor.execute(query)\n db_connect.commit()\n db_connect.close()",
"def delete_playe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes all tournaments from the database. | def deleteTournaments():
dbconnection = connect()
dbcursor = dbconnection.cursor()
dbcursor.execute("DELETE FROM tournaments;")
dbconnection.commit()
dbconnection.close() | [
"def delete_tournaments():\n conn = connect()\n c = conn.cursor()\n query = \"DELETE FROM tournaments;\"\n c.execute(query)\n conn.commit()\n conn.close()",
"def deleteTournaments():\n db, cursor = connectOpen()\n cursor.execute(\"TRUNCATE tournament_registrations CASCADE;\")\n cursor.e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the number of competitors currently registered in a specific tournament. | def countCompetitors(tournament_id):
dbconnection = connect()
dbcursor = dbconnection.cursor()
# Use of 'COALESCE' returns zero instead of 'None' when table is empty
dbcursor.execute("""SELECT COALESCE(COUNT(*), 0)
FROM competitors
WHERE tournament_id = %... | [
"def countPlayers():\n\n # establish db connection\n DB, cursor = connect()\n\n # fetch number of players registered\n cursor.execute(\"SELECT count(*) from player_registry\")\n player_count = cursor.fetchone()[0]\n DB.close()\n\n return player_count",
"def count_players(self):\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Registers an existing player as a competitor in a specific tournament. | def registerCompetitor(tournament_id, competitor_id):
dbconnection = connect()
dbcursor = dbconnection.cursor()
dbcursor.execute("""INSERT INTO competitors (tournament_id, competitor_id,
competitor_bye)
VALUES (%s, %s, %s);""",
(tournamen... | [
"def registerPlayer(player_id, tournament_id):\n conn = connect()\n cursor = conn.cursor()\n\n cursor.execute(\"insert into registrations (player_id, tournament_id) values (%s, %s);\",\n (player_id, tournament_id,))\n\n conn.commit()\n conn.close()",
"def registerPlayer(argPlayerN... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if the two players passed as arguments have played each other already in this tournament. Queries the matches database looking for the lowest player id as player_1_id because we wrote reportMatch() to always sort the player ids before creating a new row. This eliminates us having to look for the pair in ei... | def havePlayedPreviously(tournament_id, player1, player2):
# Assign player ids in a way that'll allow us to search for the lowest
# first
player1ID = min(player1, player2)
player2ID = max(player1, player2)
# Query the database for this pairing
dbconnection = connect()
dbcursor = dbconnecti... | [
"def checkPairing(playerid_1, playerid_2, standings):\n if playerid_2 >= len(standings):\n return playerid_1\n elif validMatch(standings[playerid_1][0], standings[playerid_2][0]):\n return playerid_2\n else:\n return checkPairing(playerid_1, playerid_2 + 1, standings)",
"def swissPai... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Post new meter(s) to the database. | def put_meter(self, meters, **kwargs):
raise NotImplementedError | [
"def post_measurements(self, measurements):\n token = StudentManager.get_student()[\"token\"]\n has_success = httpService.post(config.URLS['post_measures'], measurements.get_measurement_dto(), token)\n # if has success it means the connection eith the server is on\n if has_success:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set retention days for the defined by ID timeseries. | def define_retention(self, tsuid, retention_days):
raise NotImplementedError | [
"def setDaysToExpire(self, limit):\n if self.__daysToExpire == limit:\n return\n \n self.__daysToExpire = limit\n self.__checkForExpired()\n self.__saveTimer.changeOccurred()",
"def days(self, days):\n \n self._days = days",
"def setGeneratedDays(self,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Used to get the list of default aggregation functions. | def get_aggregators(self):
raise NotImplementedError | [
"def agg_names(self):\n return [\n name\n for name, setting in (\n (AGG_MEAN, self.wants_agg_mean),\n (AGG_MEDIAN, self.wants_agg_median),\n (AGG_STD_DEV, self.wants_agg_std_dev),\n )\n if setting.value\n ]",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that meters to be put are having nice format. | def _check_meters(meters):
if type(meters) == dict:
meters = [meters]
for meter_dict in meters:
if (set(meter_dict.keys())
!= set(['metric', 'timestamp', 'value', 'tags'])):
raise opentsdbclient.InvalidOpenTSDBFormat(
actual... | [
"def test_meter_validate_list(self):\n meter = micrometers_to.meters([1.0, 2.0, 3.0, 4.0])\n comparison = np.array([1.0e-6, 2.0e-6, 3.0e-6, 4.0e-6])\n\n try:\n for i in range(len(comparison)):\n self.assertTrue(math.isclose(meter[i], comparison[i], rel_tol=self.accepte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create masks, then apply them to the inputs. | def create_and_apply_masks(self, inputs):
mask = (
tf.random.uniform(inputs.shape, minval=0, maxval=1, dtype=tf.dtypes.float32)
< 0.15
)
random_tensor = tf.random.uniform(
inputs.shape, minval=0, maxval=1, dtype=tf.dtypes.float32
)
mask_index ... | [
"def apply_mask_operations(stack, mask_list):\n for mask in mask_list:\n stack = mask.apply_mask(stack)\n return stack",
"def masks(self, args):\n if isinstance(args.object, ImageI):\n image_id = args.object.id\n image = self._lookup(self.gateway, \"Image\", image_id)\n self.ctx.out... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks that the wing model and serial numbers are compatible. | def CheckModelAndSerialCompatibility(model, serial):
incompatible = False
if (model == 'oktoberkite' and system_types.WingSerialToModel(serial) !=
system_types.kWingModelOktoberKite):
incompatible = True
elif (model == 'm600' and system_types.WingSerialToModel(serial) !=
system_types... | [
"def check_compatibility(cls, data):\n model_api = data.get('api_version', 'undefined')\n if model_api != cls.API_VERSION:\n raise ValueError((\"Incompatible model API version: {!r},\\n\"\n \" Required version: {!r}\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes for distance of nearby rain gauges from the site. | def get_distance(site_coord, rg_coord):
site_id = site_coord['site_id'].values[0]
site_lat = site_coord['latitude'].values[0]
site_lon = site_coord['longitude'].values[0]
rg_coord['latitude'] = rg_coord['latitude'].apply(lambda x: float(x))
rg_coord['longitude'] = rg_coord['longitude'].apply(lambd... | [
"def light_distance(self):\n \treturn self.sight_dist()",
"def distance_regions_centra(r1,r2):\n return lib.eu_dist(r1.center(), r2.center())",
"def calc_dist(grain1,grain2):\n\tdist=np.sqrt((grain1.xyz[0][0]-grain2.xyz[0][0])**2+(grain1.xyz[0][1]-grain2.xyz[0][1])**2\n +(grain1.xyz[0][2]-grain2.x... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes in rainfall_priorities information on nearest rain gauges from the project sites for rainfall alert analysis | def main(site_code=''):
start = datetime.now()
qdb.print_out(start)
coord = all_site_coord()
if site_code == '':
try:
site_code = sys.argv[1].lower()
site_code = site_code.replace(' ', '').split(',')
except:
pass
else:
site_code = sit... | [
"def most_average_rainfall(data):\r\n min_difference = max(data.rainfall)\r\n round_average_rainfall = round(np.mean(data.rainfall), 2)\r\n for i in range(len(data.index)):\r\n current_difference = abs(data.rainfall[i] - round_average_rainfall)\r\n # computes min_difference from average to cu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the decrypted & decoded plaintext of encrypted_number. | def decrypt(self, encrypted_number):
if encrypted_number==0:
return 0
# r=len(message)//96
# C = bytes2int(message,32,r*3)
X1=encrypted_number.X1
C=encrypted_number.C
# data = []
# X1=(C[0],C[1])
X2=ECC.MultipyPoint(self.privateKey,X1,a,p)
C_y=(-C[1]+p)%p
newC=(C[0],C_y)
# V=ECC.modinv(X2[0]... | [
"def rsa_decrypt_number(number, private_key):\n # TODO: Chase\n decrypted_number = 22\n\n return decrypted_number",
"def decrypt(self, data):\n a, b = data\n cipher_text = CipherText(a, b)\n decrypted_message = Elgamal.decrypt(cipher_text, self.private_key)\n\n return decrypte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a sequence of Pytorch nn.Module `all_layers`, representing a feedforward neural network, merge the layers when two sucessive modules are nn.Linear and can therefore be equivalenty computed as a single nn.Linear | def simplify_network(all_layers):
new_all_layers = [all_layers[0]]
for layer in all_layers[1:]:
if (type(layer) is nn.Linear) and (type(new_all_layers[-1]) is nn.Linear):
# We can fold together those two layers
prev_layer = new_all_layers.pop()
joint_weight = torch.m... | [
"def _init_layers(self, layers):\n self.module_list = nn.ModuleList() # Initialize the module list so PyTorch recognizes it\n last_layer = self.input_dim # with the last layer as input dimension size\n for index, width in enumerate(layers): # Chain together linear modules\n self.modu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sign in until success | def sign_in_until_success(self):
while True:
signed_in = self.check()
if signed_in:
return True
signed_in, cookies = self.sign_in()
if signed_in:
return True | [
"def is_signed_on():\n try:\n func_keys['SIGN ON'].wait('ready')\n except:\n try:\n func_keys['BACK'].click()\n func_keys['SIGN ON'].wait('ready')\n except:\n try:\n func_keys['UNLOCK'].wait('ready')\n except:\n try... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Single class classification test with BinarySVMNode. | def testSingleClass(self, level=1):
params = svm.svm_parameter(kernel_type = svm.RBF, C = 10)
node = BinarySVMNode(2,1,params)
node.train(self.sc_samples, self.sc_labels)
node.stop_training()
testresult = node(self.sc_samples)
# rescale from SVM output [... | [
"def testMultiClass(self, level=1):\n params = svm.svm_parameter(kernel_type = svm.RBF, C = 10)\n node = BinarySVMNode(2,4,params)\n node.train(self.mc_samples, self.mc_labels)\n node.stop_training()\n \n testresult = node(self.mc_samples)\n \n # test if label... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Multiclass classification test with BinarySVM Node. | def testMultiClass(self, level=1):
params = svm.svm_parameter(kernel_type = svm.RBF, C = 10)
node = BinarySVMNode(2,4,params)
node.train(self.mc_samples, self.mc_labels)
node.stop_training()
testresult = node(self.mc_samples)
# test if labels are the sam... | [
"def testSingleClass(self, level=1):\n params = svm.svm_parameter(kernel_type = svm.RBF, C = 10)\n node = BinarySVMNode(2,1,params)\n node.train(self.sc_samples, self.sc_labels)\n node.stop_training()\n \n testresult = node(self.sc_samples)\n \n # rescale from... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Single class classification test with BinaryLinearSVMNode. | def testSingleClassLinear(self, level=1):
node = BinaryLinearSVMNode(2,1,C=2)
node.train(self.sc_samples, self.sc_labels)
node.stop_training()
testresult = node(self.sc_samples)
target = np.array([[-0.68643796],
[-0.75505737],
... | [
"def testSingleClass(self, level=1):\n params = svm.svm_parameter(kernel_type = svm.RBF, C = 10)\n node = BinarySVMNode(2,1,params)\n node.train(self.sc_samples, self.sc_labels)\n node.stop_training()\n \n testresult = node(self.sc_samples)\n \n # rescale from... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Multiclass classification test with BinaryLinearSVM Node. | def testMultiClassLinear(self, level=1):
node = BinaryLinearSVMNode(2,4,C=2)
node.train(self.mc_samples, self.mc_labels)
node.stop_training()
testresult = node(self.mc_samples)
target = np.array([[-0.0140, 1., -0.6870, 0.6869],
[-0.01... | [
"def testMultiClass(self, level=1):\n params = svm.svm_parameter(kernel_type = svm.RBF, C = 10)\n node = BinarySVMNode(2,4,params)\n node.train(self.mc_samples, self.mc_labels)\n node.stop_training()\n \n testresult = node(self.mc_samples)\n \n # test if label... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given lon, lat, and bathymetry, generate vectors of line segments of the coastline. This can be exported to matlab (via savemat) to be used with the 'editmask' routine for creating grid masks. Input | def gen_coastline(lon, lat, bathy, depth=0):
CS = plt.contour(lon, lat, bathy, [depth - 0.25, depth + 0.25])
lon = list()
lat = list()
for col in CS.collections:
for path in col.get_paths():
lon.append(path.vertices[:, 0])
lon.append(np.nan)
lat.append(path.ve... | [
"def line_map_to_segments(junctions, line_map): \n line_map_tmp = line_map.copy()\n\n output_segments = np.zeros([0, 2, 2])\n for idx in range(junctions.shape[0]):\n # if no connectivity, just skip it\n if line_map_tmp[idx, :].sum() == 0:\n continue\n # Record the line segme... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
zoom the figure to a specified lat, lon range | def zoom(self, xrange, yrange):
x, y = self.basemap(xrange, yrange)
self.ax.set_xlim(x)
self.ax.set_ylim(y)
self.fig.canvas.draw() | [
"def zoom_in(self, x, y):\n\n pass",
"def _autozoom(self):\n level_start = self.osm.props.zoom\n p1lat, p1lon = self.begin_selection.get_degrees()\n p2lat, p2lon = self.end_selection.get_degrees()\n lat = p1lat + ( p2lat - p1lat ) / 2\n lon = p1lon + ( p2lon - p1lon ) / 2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pcolormesh field data onto our geographic plot | def pcolormesh(self, lon, lat, data, **kwargs):
# Pcolor requires a modification to the locations to line up with
# the geography
dlon = lon * 0
dlat = lat * 0
dlon[:, 0:-1] = lon[:, 1:] - lon[:, 0:-1]
dlat[0:-1, :] = lat[1:, :] - lat[0:-1, :]
x, y = self.basemap(... | [
"def latlon_meshgrid(hdul):\n\n # get the latitude and longitude arrays\n latitude = hdul['pixelgeometry'].data['pixel_corner_lat']\n longitude = hdul['pixelgeometry'].data['pixel_corner_lon']\n altitude = hdul['pixelgeometry'].data['pixel_corner_mrh_alt'][:, :, 4]\n\n # make meshgrids to hold latitu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
scatter plot data onto our geographic plot | def scatter(self, lon, lat, data, **kwargs):
x, y = self.basemap(lon, lat)
self.pc = self.ax.scatter(x, y, c=data, **kwargs) | [
"def plot(data_dict, x_data, y_data):\n data = featureFormat(data_dict, [x_data, y_data, 'poi'])\n\n for value in data:\n x = value[0]\n y = value[1]\n poi = value[2]\n color = 'blue' if poi else 'grey'\n plt.scatter(x, y, color=color)\n plt.xlabel(x_data)\n plt.ylabel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
See if gjslint is on the system path. | def check_dependencies(self):
return in_path('gjslint') or npm_exists('gjslint') | [
"def check_psspy_already_in_path():\n syspath = find_file_on_path(\"psspy.pyc\", sys.path)\n\n if syspath:\n # file in one of the files on the sys.path (python's path) list.\n envpaths = os.environ[\"PATH\"].split(\";\")\n envpath = find_file_on_path(\"psspy.pyc\", envpaths)\n if e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if a face `f` is already in the list `l`. | def check_face_in(f, l):
for _ in range(len(f)):
if f in l or f[::-1] in l:
return True
f = f[-1:] + f[:-1]
return False | [
"def exists(l, f):\n for x in l:\n if f(x):\n return True\n return False",
"def featureExists(self, f):\n return (f in self.all_features)",
"def is_face(self, other):\n def is_subinterval(i1, i2):\n return ((i1[0] == i2[0] and i1[1] == i2[1]) or\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Export the vertices of a face to povray array. | def export_pov_array(arr):
declare = "#declare vertices_list = array[{}] {{ {} }};\n"
return declare.format(len(arr), helpers.pov_vector_list(arr)) | [
"def save_ply_data(filename, vertex, face):\n\n vertices = np.zeros(vertex.shape[0], dtype=[('x', 'f4'), ('y', 'f4'),('z', 'f4')])\n for i in range(vertex.shape[0]):\n vertices[i] = (vertex[i][0], vertex[i][1], vertex[i][2])\n # print(vertex, vertex.dtype)\n \n faces = np.zeros(face.shape[0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transform a vector by a word in the symmetry group. | def _transform(self, vector, word):
for w in word:
vector = np.dot(vector, self._reflections[w])
return vector | [
"def ApplySymmetryToVector(symmetry, vector, unit_cell, irt):\n \n # Get the vector in crystalline coordinate\n nat, dumb = np.shape(vector)\n work = np.zeros( (nat, 3))\n sym = symmetry[:, :3]\n\n v1 = Methods.covariant_coordinates(unit_cell, vector)\n w1 = sym.dot(v1.T).T\n\n # Return in c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transform a vertex by a word in the symmetry group. Return the index of the resulting vertex. | def _move(self, vertex, word):
for w in word:
vertex = self._vtable[vertex][w]
return vertex | [
"def remap_vertex(vertex, symmetry):\n assert vertex >= 0 and vertex < 361\n x = vertex % 19\n y = vertex // 19\n if symmetry >= 4:\n x, y = y, x\n symmetry -= 4\n if symmetry == 1 or symmetry == 3:\n x = 19 - x - 1\n if symmetry == 2 or symmetry == 3:\n y = 19 - y - 1\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the total bytes used by a bucket. | def bucket_du(bucket_name):
s3 = boto.connect_s3()
total_bytes = 0
bucket = s3.lookup(bucket_name)
if bucket:
for key in bucket:
total_bytes += key.size
else:
print 'Warning: bucket %s was not found!' % bucket_name
return total_bytes | [
"def quotaUsedBytes(): # @NoSelf",
"def get_size_and_checksum(bucket, key):\n return _objstore_backend.get_size_and_checksum(bucket, key)",
"def totalbytes(self):\n raise NotImplementedError(\"TODO\")",
"def length(self): # O(N)\n length = 0 # Constant\n\n for bucket in self.buc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch data to populate the first "overview" table | def fetch_overview(self):
session = meta.Session()
#Total deployed servers
qry = session.query(models.House.serverid)
qry = qry.filter(models.House.serverid != None)
qry = qry.distinct()
deployed_serv = qry.count()
logging.debug("Total Deployed Servers: {0}".for... | [
"def _load(self):\n self.get_table()\n self._get_pole()\n self._get_winners()",
"def gather(self):\n quandl.ApiConfig.api_key = self.apikey\n # this would be where I would construct it's own api call, using quandl's get_table method instead\n #base = quandl.ApiConfig.api_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch details of houses that have had readings today | def fetch_housestatus(self):
session = meta.Session()
now = self.reportdate
today = datetime.datetime.now()
heartbeat = today - datetime.timedelta(hours=8)
#qry = session.query(models.House)
houseqry = session.query(models.House)
houseqry = houseqry.filter(mod... | [
"def get_readings(station_id, start, end):\n return Reading.objects.filter(\n station_id=station_id,\n timestamp__gte=start,\n timestamp__lte=end)",
"def get_db_avails(building_name, room_name, date):\n # 1. find room. 2. find avail object. 3. get avails filtered by date.\n fa = get_fa_for_room(buildi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check for pulse output nodes that could be having issues. IE the value has not increased in the past 24 hours | def check_pulse_nodes(self):
session = meta.Session()
now = self.reportdate
yesterday = now - datetime.timedelta(days=1)
#Get sensor type ids for the pulse output nodes
pulsenodes = ["Heat Energy", "Heat Volume", "Gas Pulse Count"]
qry = session.query(models.SensorType... | [
"def pulse_checker(self):\n\n\t\twhile True:\n\t\t\t\tcheck = (time.time()-self.timer)*1000\n\t\t\t\tif check > self.checkTime: \n\t\t\t\t\t#print(check)\n\t\t\t\t\tbreak\n\t\t\t\ttime.sleep(0.01) \n\n\t\tdecode = self.decode_pulse(self.pList) \n\n\t\tself.pList = []\n\t\tself.de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets and updates expectation function | def set_expect(self, expect):
self.expect = expect
self.update_expect() | [
"def test_set_policy(self):\n ret = {\"name\": \"salt\", \"changes\": {}, \"result\": True, \"comment\": \"\"}\n\n mock = MagicMock(return_value=[])\n with patch.object(nftables, \"_STATE_INTERNAL_KEYWORDS\", mock):\n mock = MagicMock(return_value=\"stack\")\n with patch.d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates results from preds and confs Assumes that example_lists_and_indices or to_raw_examples or to_raw_file was called before, so that self.result_indexes exists | def update_results_from_preds(self, preds, confs):
result_indexes = self.result_indexes
if type(self.data[0]) == list:
self.results.preds = [[] for _ in self.data]
self.results.confs = [[] for _ in self.data]
for i, p, c in zip(result_indexes, preds, confs):
... | [
"def update(self, image_files, results):\n for index, image_file in enumerate(image_files):\n result = results[index]\n self[image_file] = result",
"def update(self, result):\r\n self.results.append(result)\r\n ret = self.summarize(result)\r\n self.summary.append(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recovers a previously computed example_list_and_indices | def recover_example_list_and_indices(self):
idxs = list(range(len(self.data)))
if self.run_idxs is not None:
idxs = self.run_idxs
if type(self.data[0]) in [list, np.array, np.ndarray]:
examples = [y for i in idxs for y in self.data[i]]
else:
exa... | [
"def reindexObject(idxs=[]):",
"def process_example(self, example):\n example = text_to_vocab_indices(self.effective_vocab_size, example)[0]\n\n fake_example = [x for x in example]\n fake_example[self.left_context] = randint(0, self.effective_vocab_size - 1)\n return (example, fake_exa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create a database connection to the SQLite database specified by db_file | def create_connection(self, db_file):
conn = sqlite3.connect(db_file)
return conn | [
"def testCreateDatabaseFile(self):\n from conf import DATABASE_NAME, DATABASE_FILE\n import sqlite3\n from sqlite3 import Error \n \n db_file = DATABASE_FILE\n try:\n conn = sqlite3.connect(db_file)\n except Error as e:\n print(e)\n final... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the wrong salt for testing | def generate_wrong_salt(cls, claims):
return '\xbb4;\xc7\xb2Vn\xa5\xb7\xb0^\xc6J%\x1d\x90\xb8Ik:' | [
"def salt(self):\n return None",
"def salt():\n return uuid.uuid4().hex",
"def make_salt():\n return uuid.uuid4().hex",
"def new_salt():\n alphabet = \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n salt = ''.join(secrets.choice(alphabet) for i in range(16))\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A decorator that limits the usage of a slash command to guild contexts. The command won't be able to be used in private message channels. Example | def guild_only() -> Callable:
def inner(command: Callable):
if isinstance(command, ApplicationCommand):
command.guild_only = True
else:
command.__guild_only__ = True
return command
return inner | [
"async def guild(self, ctx):\n\t\tif ctx.invoked_subcommand is None:\n\t\t\tawait self.bot.send_cmd_help(ctx)",
"def command_access_decorator(user_ids):\n def real_decorator(function):\n def wrapper(*args, **kwargs):\n message = args[0]\n user_id = message.from_user.id\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set the weights of the model from the input model | def set_weights(self, new_model):
self.model.set_weights(new_model.model.get_weights()) | [
"def target_model_update(self):\n self.set_weights(self.model, self.target_model)",
"def assign_weights(model, weights):\n state_dict = model.state_dict(keep_vars=True)\n # The index keeps track of location of current weights that is being un-flattened.\n index = 0\n # just for safety, no grads... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if an element has attribute of zip code | def is_zip(elem):
return (elem.attrib['k'] == "addr:postcode") | [
"def is_zip(elem):\n return elem.attrib['k'] == \"addr:postcode\"",
"def is_postal(elem):\n return (elem.attrib['k'] == \"addr:postcode\")",
"def is_city(elem):\n return elem.attrib['k'] == \"addr:city\"",
"def validate_zip_usa(zip):\n return bool(zip and zipcodes.is_real(zip))",
"def check_zipc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the maximum 307 redirects the SDK will automatically handle before throwing an exception. | def with_max_redirects(self, maxredirects):
self.maxredirects = maxredirects
return self | [
"def EnableAutoRedirect(self):\r\n self.__opener.add_handler(urllib2.HTTPRedirectHandler())",
"def temporary_redirect(absolute_url):\n response = HTTPResponse()\n response.redirect(absolute_url, 307)\n return response",
"def initialize_redirect(self, *args, **kwargs):\n def immediately_re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load camera calibration parameters MTX and DIST from the file CALIB. | def load_camera_calibration(calib):
params = np.load(calib)
return params['mtx'], params['dist'] | [
"def _load_calib(self):\n # We'll build the calibration parameters as a dictionary, then\n # convert it to a namedtuple to prevent it from being modified later\n data = {}\n\n # Load the calibration file\n calib_filepath = os.path.join(\n self.base_path, 'calib/{}.txt'.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given camera distortion coefficients MTX and DIST, load an image from the file BOARD, then undistort and return it. | def undistorted_imread(mtx, dist, board):
# load the board image
img = v.imread(board)
wh = img.shape[1::-1]
tx, roi = v.getOptimalNewCameraMatrix(mtx, dist, wh, 1, wh)
# undo the camera distortion
return v.undistort(img, mtx, dist, None, tx) | [
"def undistort(self) -> np.ndarray:\n distortion_config = self._get_distortion_config(self.camera_uuid)\n matrix = distortion_config[0]\n coefficients = distortion_config[1]\n undistorted_image = cv2.undistort(\n self.image,\n matrix,\n coefficients,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the chessboard inner corners in source image space, and the final width and height of the chessboard in output image space, computes and returns the outside corners of the board in both source and destination image space. | def getChessboardOutsideCorners(corners, size):
srccorners = np.zeros((4,2), np.float32)
dstcorners = np.float32([(0,0), (size,0), (size,size), (0,size)])
srccorners[0] = 3*corners[0] - corners[7] - corners[1]
srccorners[1] = 3*corners[6] - corners[5] - corners[13]
srccorners[2] = 3*corners[48] - c... | [
"def _find_chessboard_corners(gray, dims):\n return cv2.findChessboardCorners(gray, dims, None)",
"def coor_crop_shift(original_coordinates, cropped_image_corners):\n cropped_coordinates = np.zeros([0, 2])\n min_x = min(cropped_image_corners[0][0], cropped_image_corners[1][0])\n max_x = max(cropped_im... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return all nodes which belong to a real emulation (therefore belong to a qemu instance). Returns EmulationNodes | def filter_real_emulation_nodes(self):
from miniworld.model.emulation.nodes.virtual.VirtualNode import VirtualNode
return self.filter_type(fun=lambda node: not isinstance(node, VirtualNode)) | [
"def nodes():\n factory = platform_nodes.PlatformNodesFactory()\n nodes = factory.get_nodes_platform()\n return nodes",
"def get_test_device():\n\n devices = []\n for node_name,node in LOCAL[\"node\"].iteritems():\n device = node[\"device\"]\n if device not in devices: devices.append(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Basically curl, but doesn't require the developer to have curl installed locally. Returns True if succeeded at downloading file. | def curlish(download_url, output_path):
if not output_path or not download_url:
print('need both output path and download URL to download, exiting.')
return False
print('downloading from "{}" to "{}"'.format(download_url, output_path))
script_contents = ''
try:
response = urlop... | [
"def download_to_file(url, fname, cksum=None):\n try:\n if os.path.isfile(fname):\n if cksum is not None and cksum == hash_file(fname):\n __FETCHED.add(fname)\n return True\n else:\n os.unlink(fname)\n\n dname = os.path.dirname(fnam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the embedding dimension. | def embedding_dim(self) -> Optional[int]:
return None | [
"def embedding_size(self):\n pass",
"def dimension(self):\n return self.field(Field.POSITION).shape[1]",
"def embeddings_size(self) -> int:",
"def dim(self):\n return self._dim",
"def entity_dim(self) -> int:\n return self.entity[0]",
"def num_dimensions(self):\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct initializer from pretrained embeddings stored under a path. | def from_path(directory: Union[pathlib.Path, str], side: MatchSideEnum) -> 'PretrainedNodeEmbeddingInitializer':
return PretrainedNodeEmbeddingInitializer(
embeddings=torch.load(
PretrainedNodeEmbeddingInitializer.output_file_path(
directory=directory,
... | [
"def load_pretrained_embeddings(path, vocab=None):\n vectors = Vectors(name=path, cache=os.getcwd())\n if vocab is not None:\n vectors = vectors.get_vecs_by_tokens(vocab, True)\n return vectors",
"def setup_embedding_initializer(self):\n embed_config = self.model_config['embed_config']\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save pretrained node embedding into a file. | def save_to_path(self, directory: Union[pathlib.Path, str], side: MatchSideEnum) -> pathlib.Path:
output_path = PretrainedNodeEmbeddingInitializer.output_file_path(directory=directory, side=side)
torch.save(obj=self.pretrained, f=output_path)
return output_path | [
"def save(self, path):\n\n torch.save({'embeddings': self.embeddings, 'indices': self.data_index}, path)",
"def save(self, epoch, file_path=\"output/bert_trained.model\"):\n output_path = file_path + \".ep%d\" % epoch\n torch.save(self.model.cpu(), output_path)\n self.model.to(self.dev... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse either percentage allocations or relative size allocations into rounded integer allocations of size batch precision determines how many optional decimal points to include | def parse_allocation(allocation, batch, precision=0):
if precision > 0:
batch = batch * (10 ** precision)
rounded_allocs = [x * batch / float(sum(allocation)) for x in allocation]
dec_allocs = [x - int(x) for x in rounded_allocs]
floor_allocs = [int(x) for x in rounded_allocs]
diff = batc... | [
"def test_mean_valid():\n\n assert mean([4096, 49152, 64738]) == Decimal('39328.66666666666666666666667')",
"def test_Precision1():\n metric = fluid.metrics.Precision(\"Precision\")\n # 生成预测值和标签\n preds = [[0.1], [0.7], [0.8], [0.9], [0.2], [0.2], [0.3], [0.5], [0.8],\n [0.6]]\n labels ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns environment's current run date | def get_run_date(self):
return self.run_date | [
"def get_current_date():\n return datetime.datetime.now().isoformat()",
"def getnow(self):\n print()\n print(\"Current date:\")\n print(datetime.date.today())",
"def get_current_date():\n return datetime.datetime.strftime(datetime.datetime.now(), \"%Y-%m-%d\")",
"def last_run_at... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns environment's arm names | def get_arm_names(self):
return self.arm_names | [
"def list_envs():\n for env in gym.envs.registry.all():\n print(env.id)",
"def _environment_variable_names(self):\n return ['TRELLO_ORG_NAME', 'GITHUB_ORG_LOGIN', 'GITHUB_ORG_WEBHOOK_ID', 'JIRA_SERVER_ADDRESS']",
"def all_camera_names(self):\n return self.mobile_camera_names + self.camer... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates run date after every cycle. If incremental, updates run_date by 1, mainly used for testing and generating test data. Otherwise, updates to one past the last day data was collected. | def update_run_date(self, run_date=None, incremental=False):
if run_date is not None:
self.run_date = run_date
return
if incremental:
self.run_date = self.run_date + timedelta(days=1)
else:
max_dates = [max(data.index) for data in self.data]
... | [
"def adj_run_date():\n global current_run\n if current_run == None:\n print(\"No run selected. Returning to main menu.\")\n return False\n old_date = current_run.date\n date = datetime.datetime.strptime(current_run.date, \"%Y-%m-%d\")\n date += datetime.timedelta(days=1)\n current_ru... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a new arm to the bandit. Data must be a pandas series indexed by date collected. | def add_arm(self, name=None, data=None):
self.k += 1
self.arm_names.append(name)
if data is None:
self.data.append(pd.Series())
else:
self.data.append(data) | [
"def add_MW_data(self, MW_data_object):\n self.MW_pulse_data.append(MW_data_object)\n self._update_end_time(MW_data_object.stop)",
"def newSeries(self):\r\n\t\tself.__data.append(self.__thisSeries)\r\n\t\tself.__thisSeries = list()",
"def add_item(self, index: int, quantum_circuit: qcirc.QuantumCi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print sum of circular prime from 1 to number | def circular_prime_answer(number, total):
for i in range(1, number + 1):
if circular_prime(i):
total += i
print(total) | [
"def problem35(limit):\n\n result = 0\n for p in pelib.primes_sieve(limit):\n if is_circular_primes(p):\n result += 1\n\n return result",
"def primo(num):\r\n acumulador_suma = 0\r\n total_de_numeros_primos = 0\r\n while num > 1:\r\n count = 1\r\n count_nun_primos... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return true if number is circular prime else return false | def circular_prime(number):
for i in range(len(str(number))):
# rotate number
rotate = str(number)
rotate = rotate[i:] + rotate[:i]
rotate = int(rotate)
# check prime number
if not is_prime(rotate):
return False
return True | [
"def is_circular_prime(n, prime_set):\n for x in rotate_digits(n):\n if x not in prime_set:\n return False\n return True",
"def is_prime(number):\n division = 2\n while number % division != 0:\n division += 1\n if division == number:\n return True\n return False",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transforms an image by first applying an optional center crop, then resizing it. | def transform(image, crop_height, crop_width, resize_height=64, resize_width=64, is_crop=True):
def center_crop(image, crop_h, crop_w, resize_h=64, resize_w=64):
"""Performs a center crop followed by a resize.
Args:
image: Image of type np.ndarray
... | [
"def zoom_and_resize(self, image):\r\n zoom_x = self.parameter_dict['zoom'] * 4\r\n zoom_y = self.parameter_dict['zoom'] * 4 * self.rows/self.cols\r\n croped = image[int(zoom_y/2.0):int(self.rows_raw - (zoom_y/2.0)), int(zoom_x/2.0):int(self.cols_raw -(zoom_x/2.0))]\r\n \r\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize a drawer of socks. | def __init__(self, count=1):
# The socks to be found in the drawer.
self.choices = ["white"] * (4 * count)
self.choices += ["black"] * (3 * count)
self.choices += ["red", "blue", "green", "argyle"] * (2 * count)
self.choices += ["stripey", "fuzzy", "toe"] * (1 * count)
... | [
"def init_drone(self):\n dronePosition = DronePosition()\n droneConnection = DroneConnection(\"192.168.100.1\", 4646, 19798)\n self.drone = Drone(droneConnection, dronePosition)",
"def __init__(self):\n\n self.viewmodes = itertools.cycle([\"colours\", \"waiting\"])\n self.curren... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plots color of lake through time series | def plot_color_timeseries(ax, data, start, stop, delta):
# set time period (x axis)
ax.set_xlim(start, stop)
# create higher resolution timestamps
numdays = (stop-start).days
samples = range(0, numdays+delta, delta)
hires_dates = [start + datetime.timedelta(days=x) for x in samples]
hires_time = [t... | [
"def scatterplot_moonlighters(self):\n if self.scatter_data.empty:\n self._get_scatter_data()\n plot_title = 'Moonlighting genes'\n xvar = 'go_con'\n yvar = 'frac_rel_go'\n xlab = 'Number of GO annotations (per gene)'\n ylab = 'Fraction of relevant GO terms (per ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save CingSummary object as XML file. Return True on error | def save(self, path):
result = obj2XML( self, path=path )
if result == None:
nTerror('CingSummary.save: saving to "%s"', path)
return True
#end if | [
"def exportXML(self):\r\n encoding:str = self.encodingVariable.get()\r\n\r\n try:\r\n self.filePath:str = asksaveasfilename(\r\n defaultextension = \".xml\",\r\n filetypes = [(\"XML file\", \"*.xml\")],\r\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Static method to restore CingSummary object from XMLfile path. Return None on error. | def restore( path ): #@NoSelf # pylint: disable=E0213
if not os.path.exists( path ):
nTerror('CingSummary.restore: path "%s" does not exist', path)
return True
#end if
return xML2obj(path = path) | [
"def save(self, path):\n result = obj2XML( self, path=path )\n if result == None:\n nTerror('CingSummary.save: saving to \"%s\"', path)\n return True\n #end if",
"def load_summary(self):\n summary_path = os.path.join(self.base_dir, 'result_summary.npz')\n i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads the dataset and based on n_steps/lags to consider in the time series, creates input output pairs | def curateData(pth, price_col, date_col, n_steps):
df = pd.read_csv(pth)
# Create lags for the price column
for idx in range(n_steps):
df[f"lag_{idx + 1}"] = df[price_col].shift(periods = (idx + 1))
# Create a dataframe which has only the lags and the date
new_df = df[[date_col, price_... | [
"def make_instances(data, input_steps, input_lags, output_steps,\n output_series_list, use_date_features):\n logging.info('Create inputs from time series')\n # Fix output series to consider\n if len(output_series_list) == 1 and output_series_list[0] == ALL:\n output_series_list = d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Poll for presence of tag, read data, until stop() is called. | def poll_loop(self):
# initialize music mixer
pygame.mixer.init()
# set default volume
util.set_volume(settings.DEFAULT_VOLUME)
while not self.do_stop:
with self.mutex:
# initialize tag state
self.uid[0] = None
self.... | [
"def _read_job(self):\n while not self._stop.is_set():\n self._comm_tasks.put(StreamDemultiplexer.RD_TASK)\n time.sleep(0.1)",
"def collect_data(self):\n while(self.is_streaming):\n self.skipped_bytes = 0\n self.read_serial_binary()",
"def pull_data(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set dictionary of file hashes and music files | def set_music_files_dict(self, mfd):
with self.mutex:
for k, v in mfd.items():
self.music_files_dict[k] = v | [
"def music_files():\n global music_files_dict\n\n file_paths = sorted(glob.glob(path.join(settings.MUSIC_ROOT, '*')))\n\n out = []\n music_files_dict = dict()\n for file_path in file_paths:\n file_name = path.split(file_path)[1]\n file_hash = music_file_hash(file_name)\n out.appe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set flag to reset the startup timer | def reset_startup_timer(self):
self.reset_startup.value = 1 | [
"def start_timer(self):\n\t\tself.start_time = time.clock()",
"def init_timer(self):\n self._start_time = time.time()",
"def reset_timer(self):\n self.timer = datetime.datetime.now()",
"def start():\n global timer_running\n timer_running = True\n timer.start()",
"def _start_timer(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get hash of music file name, replace first byte with a control byte for music playing. | def music_file_hash(file_name):
m = hashlib.md5()
m.update(file_name)
return CONTROL_BYTES['MUSIC_FILE'] + m.digest()[1:] | [
"def video_file_name(\n\t\tself,\n\t\tshow_url,\n\t\tseason_title,\n\t\tepisode_title):\n\t\treturn hashlib.sha1(bytes(show_url+season_title+episode_title,encoding='utf8')).hexdigest()",
"def _source_hash_file(source):\n h = hashlib.sha1()\n h.update(source.encode('utf-8'))\n return h.hexdige... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of music files and file identifier hashes as JSON; also refresh internal cache of music files and hashes. | def music_files():
global music_files_dict
file_paths = sorted(glob.glob(path.join(settings.MUSIC_ROOT, '*')))
out = []
music_files_dict = dict()
for file_path in file_paths:
file_name = path.split(file_path)[1]
file_hash = music_file_hash(file_name)
out.append(dict(name=fi... | [
"def _retrieveCacheFiles(ticker_list):\n filenames = os.listdir('./cache_files')\n # Remove any files we aren't actively looking for.\n filenames = [filename for filename in filenames if filename.split('.')[\n 0] in ticker_list]\n output = {}\n pool = Pool()\n content_dicts = pool.map(_retr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write data to NFC tag Data is contained in get argument 'data'. | def write_nfc():
hex_data = request.args.get('data')
if hex_data is None:
logger.error("No data argument given for writenfc endpoint")
return
# convert from hex to bytes
data = binascii.a2b_hex(hex_data)
if data[0] == CONTROL_BYTES['MUSIC_FILE']:
if data not in music_files... | [
"def write(self, data):\n try:\n # Hack to support unicode under Python 2.x\n if isinstance(data, str) or (sys.version_info < (3,) and isinstance(data, unicode)):\n data = data.encode('utf-8')\n\n self._device.write(data)\n\n except serial.SerialTimeoutE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tries to create the lockfile, using O_EXCL to prevent races. If it succeeds it returns a tuple (fd, None). Otherwise try and connect to the server specified in the lockfile. If this succeeds, a tuple (None, server) is returned. Otherwise remove the lockfile and try again. | def get_fd_or_server(
config: SimpleConfig,
) -> Tuple[Optional[int], Optional[jsonrpclib.Server]]:
lockfile = get_lockfile(config)
limit = 5
latest_exc = None
for n in range(limit):
try:
return os.open(lockfile, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644), None
except ... | [
"def test_fdopen_works_correctly(self):\n lockfile = join('/tmp', sha1(settings.SECRET_KEY).hexdigest() +'.semaphore')\n \n try:\n os.open(lockfile, os.O_EXCL | os.O_RDWR | os.O_CREAT)\n os.open(lockfile, os.O_EXCL | os.O_RDWR | os.O_CREAT)\n except OSError as e:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |